file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
list | attention_mask
list | labels
list |
---|---|---|---|---|---|---|
/**
*Submitted for verification at Etherscan.io on 2020-09-14
*/
// Copyright (C) 2020 Maker Ecosystem Growth Holdings, INC.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pragma solidity ^0.5.12; //inject UNLIMITED COMPILER VERSIONS
interface DSPauseAbstract {
function delay() external view returns (uint256);
function plot(address, bytes32, bytes calldata, uint256) external;
function exec(address, bytes32, bytes calldata, uint256) external returns (bytes memory);
}
interface VatAbstract {
function file(bytes32, uint256) external;
function file(bytes32, bytes32, uint256) external;
}
interface SpotAbstract {
function file(bytes32, bytes32, uint256) external;
function poke(bytes32) external;
}
interface CatAbstract {
function file(bytes32, uint256) external;
}
contract SpellAction {
// MAINNET ADDRESSES
//
// The contracts in this list should correspond to MCD core contracts, verify
// against the current release list at:
// https://changelog.makerdao.com/releases/mainnet/1.1.1/contracts.json
address constant MCD_VAT = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address constant MCD_SPOT = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address constant MCD_CAT = 0xa5679C04fc3d9d8b0AaB1F0ab83555b301cA70Ea;
// Decimals & precision
uint256 constant MILLION = 10 ** 6;
uint256 constant RAY = 10 ** 27;
uint256 constant RAD = 10 ** 45;
function execute() external {
/*** Risk Parameter Adjustments ***/
// Set the global debt ceiling to 948,000,000
// 823 (current DC) + 100 (USDC-A increase) + 25 (PAXUSD-A increase)
VatAbstract(MCD_VAT).file("Line", 948 * MILLION * RAD);
// Set the USDC-A debt ceiling
//
// Existing debt ceiling: 100 million
// New debt ceiling: 200 million
VatAbstract(MCD_VAT).file("USDC-A", "line", 200 * MILLION * RAD);
// Set the PAXUSD-A debt ceiling
//
// Existing debt ceiling: 5 million
// New debt ceiling: 30 million
VatAbstract(MCD_VAT).file("PAXUSD-A", "line", 30 * MILLION * RAD);
// Set USDC-A collateralization ratio
// Existing ratio: 110%
// New ratio: 103%
SpotAbstract(MCD_SPOT).file("USDC-A", "mat", 103 * RAY / 100); // 103% coll. ratio
SpotAbstract(MCD_SPOT).poke("USDC-A");
// Set PAXUSD-A collateralization ratio
// Existing ratio: 120%
// New ratio: 103%
SpotAbstract(MCD_SPOT).file("PAXUSD-A", "mat", 103 * RAY / 100); // 103% coll. ratio
SpotAbstract(MCD_SPOT).poke("PAXUSD-A");
// Set Cat box variable
// Existing box: 30m
// New box: 15m
CatAbstract(MCD_CAT).file("box", 15 * MILLION * RAD);
}
}
contract DssSpell {
DSPauseAbstract public pause =
DSPauseAbstract(0xbE286431454714F511008713973d3B053A2d38f3);
address public action;
bytes32 public tag;
uint256 public eta;
bytes public sig;
uint256 public expiration;
bool public done;
// Provides a descriptive tag for bot consumption
// This should be modified weekly to provide a summary of the actions
// Hash: seth keccak -- "$(wget https://raw.githubusercontent.com/makerdao/community/15215ebaf8bbb4a20567b3233383788a68afb58b/governance/votes/Executive%20vote%20-%20September%2014%2C%202020.md -q -O - 2>/dev/null)"
string constant public description =
"2020-09-14 MakerDAO Executive Spell | Hash: 0xf0155120204be06c56616181ea82bbfa93f48494455c6d0b3c0ab1d581464657";
constructor() public {
sig = abi.encodeWithSignature("execute()");
action = address(new SpellAction());
bytes32 _tag;
address _action = action;
assembly { _tag := extcodehash(_action) }
tag = _tag;
expiration = now + 30 days;
}
// modifier officeHours {
// uint day = (now / 1 days + 3) % 7;
// require(day < 5, "Can only be cast on a weekday");
// uint hour = now / 1 hours % 24;
// require(hour >= 14 && hour < 21, "Outside office hours");
// _;
// }
function schedule() public {
require(now <= expiration, "This contract has expired");
require(eta == 0, "This spell has already been scheduled");
eta = now + DSPauseAbstract(pause).delay();
pause.plot(action, tag, sig, eta);
}
function cast() public /*officeHours*/ {
require(!done, "spell-already-cast");
done = true;
pause.exec(action, tag, sig, eta);
}
} | Set the global debt ceiling to 948,000,000 823 (current DC) + 100 (USDC-A increase) + 25 (PAXUSD-A increase) Set the USDC-A debt ceiling Existing debt ceiling: 100 million New debt ceiling: 200 million Set the PAXUSD-A debt ceiling Existing debt ceiling: 5 million New debt ceiling: 30 million Set USDC-A collateralization ratio Existing ratio: 110% New ratio: 103% Set PAXUSD-A collateralization ratio Existing ratio: 120% New ratio: 103% Set Cat box variable Existing box: 30m New box: 15m | function execute() external {
VatAbstract(MCD_VAT).file("Line", 948 * MILLION * RAD);
VatAbstract(MCD_VAT).file("USDC-A", "line", 200 * MILLION * RAD);
VatAbstract(MCD_VAT).file("PAXUSD-A", "line", 30 * MILLION * RAD);
SpotAbstract(MCD_SPOT).poke("USDC-A");
SpotAbstract(MCD_SPOT).poke("PAXUSD-A");
CatAbstract(MCD_CAT).file("box", 15 * MILLION * RAD);
}
| 12,655,823 | [
1,
694,
326,
2552,
18202,
88,
5898,
4973,
358,
2468,
8875,
16,
3784,
16,
3784,
1725,
4366,
261,
2972,
21533,
13,
397,
2130,
261,
3378,
5528,
17,
37,
10929,
13,
397,
6969,
261,
28228,
3378,
40,
17,
37,
10929,
13,
1000,
326,
11836,
5528,
17,
37,
18202,
88,
5898,
4973,
28257,
18202,
88,
5898,
4973,
30,
2130,
312,
737,
285,
1166,
18202,
88,
5898,
4973,
30,
4044,
312,
737,
285,
1000,
326,
453,
2501,
3378,
40,
17,
37,
18202,
88,
5898,
4973,
28257,
18202,
88,
5898,
4973,
30,
1381,
312,
737,
285,
1166,
18202,
88,
5898,
4973,
30,
5196,
312,
737,
285,
1000,
11836,
5528,
17,
37,
4508,
2045,
287,
1588,
7169,
28257,
7169,
30,
20168,
9,
1166,
7169,
30,
1728,
23,
9,
1000,
453,
2501,
3378,
40,
17,
37,
4508,
2045,
287,
1588,
7169,
28257,
7169,
30,
15743,
9,
1166,
7169,
30,
1728,
23,
9,
1000,
385,
270,
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,
1836,
1435,
3903,
288,
203,
203,
3639,
25299,
7469,
12,
49,
10160,
67,
58,
789,
2934,
768,
2932,
1670,
3113,
2468,
8875,
380,
490,
15125,
1146,
380,
534,
1880,
1769,
203,
203,
3639,
25299,
7469,
12,
49,
10160,
67,
58,
789,
2934,
768,
2932,
3378,
5528,
17,
37,
3113,
315,
1369,
3113,
4044,
380,
490,
15125,
1146,
380,
534,
1880,
1769,
203,
203,
3639,
25299,
7469,
12,
49,
10160,
67,
58,
789,
2934,
768,
2932,
28228,
3378,
40,
17,
37,
3113,
315,
1369,
3113,
5196,
380,
490,
15125,
1146,
380,
534,
1880,
1769,
203,
203,
3639,
26523,
7469,
12,
49,
10160,
67,
3118,
1974,
2934,
84,
3056,
2932,
3378,
5528,
17,
37,
8863,
203,
203,
3639,
26523,
7469,
12,
49,
10160,
67,
3118,
1974,
2934,
84,
3056,
2932,
28228,
3378,
40,
17,
37,
8863,
203,
203,
3639,
385,
270,
7469,
12,
49,
10160,
67,
14130,
2934,
768,
2932,
2147,
3113,
4711,
380,
490,
15125,
1146,
380,
534,
1880,
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
]
|
pragma solidity ^0.4.24;
/*
* gibmireinbier
* 0xA4a799086aE18D7db6C4b57f496B081b44888888
* [email protected]
*/
library Helper {
using SafeMath for uint256;
uint256 constant public ZOOM = 1000;
uint256 constant public SDIVIDER = 3450000;
uint256 constant public PDIVIDER = 3450000;
uint256 constant public RDIVIDER = 1580000;
// Starting LS price (SLP)
uint256 constant public SLP = 0.002 ether;
// Starting Added Time (SAT)
uint256 constant public SAT = 30; // seconds
// Price normalization (PN)
uint256 constant public PN = 777;
// EarlyIncome base
uint256 constant public PBASE = 13;
uint256 constant public PMULTI = 26;
uint256 constant public LBase = 15;
uint256 constant public ONE_HOUR = 3600;
uint256 constant public ONE_DAY = 24 * ONE_HOUR;
//uint256 constant public TIMEOUT0 = 3 * ONE_HOUR;
uint256 constant public TIMEOUT1 = 12 * ONE_HOUR;
function bytes32ToString (bytes32 data)
public
pure
returns (string)
{
bytes memory bytesString = new bytes(32);
for (uint j=0; j<32; j++) {
byte char = byte(bytes32(uint(data) * 2 ** (8 * j)));
if (char != 0) {
bytesString[j] = char;
}
}
return string(bytesString);
}
function uintToBytes32(uint256 n)
public
pure
returns (bytes32)
{
return bytes32(n);
}
function bytes32ToUint(bytes32 n)
public
pure
returns (uint256)
{
return uint256(n);
}
function stringToBytes32(string memory source)
public
pure
returns (bytes32 result)
{
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
function stringToUint(string memory source)
public
pure
returns (uint256)
{
return bytes32ToUint(stringToBytes32(source));
}
function uintToString(uint256 _uint)
public
pure
returns (string)
{
return bytes32ToString(uintToBytes32(_uint));
}
/*
function getSlice(uint256 begin, uint256 end, string text) public pure returns (string) {
bytes memory a = new bytes(end-begin+1);
for(uint i = 0; i <= end - begin; i++){
a[i] = bytes(text)[i + begin - 1];
}
return string(a);
}
*/
function validUsername(string _username)
public
pure
returns(bool)
{
uint256 len = bytes(_username).length;
// Im Raum [4, 18]
if ((len < 4) || (len > 18)) return false;
// Letzte Char != ' '
if (bytes(_username)[len-1] == 32) return false;
// Erste Char != '0'
return uint256(bytes(_username)[0]) != 48;
}
// Lottery Helper
// Seconds added per LT = SAT - ((Current no. of LT + 1) / SDIVIDER)^6
function getAddedTime(uint256 _rTicketSum, uint256 _tAmount)
public
pure
returns (uint256)
{
//Luppe = 10000 = 10^4
uint256 base = (_rTicketSum + 1).mul(10000) / SDIVIDER;
uint256 expo = base;
expo = expo.mul(expo).mul(expo); // ^3
expo = expo.mul(expo); // ^6
// div 10000^6
expo = expo / (10**24);
if (expo > SAT) return 0;
return (SAT - expo).mul(_tAmount);
}
function getNewEndTime(uint256 toAddTime, uint256 slideEndTime, uint256 fixedEndTime)
public
view
returns(uint256)
{
uint256 _slideEndTime = (slideEndTime).add(toAddTime);
uint256 timeout = _slideEndTime.sub(block.timestamp);
// timeout capped at TIMEOUT1
if (timeout > TIMEOUT1) timeout = TIMEOUT1;
_slideEndTime = (block.timestamp).add(timeout);
// Capped at fixedEndTime
if (_slideEndTime > fixedEndTime) return fixedEndTime;
return _slideEndTime;
}
// get random in range [1, _range] with _seed
function getRandom(uint256 _seed, uint256 _range)
public
pure
returns(uint256)
{
if (_range == 0) return _seed;
return (_seed % _range) + 1;
}
function getEarlyIncomeMul(uint256 _ticketSum)
public
pure
returns(uint256)
{
// Early-Multiplier = 1 + PBASE / (1 + PMULTI * ((Current No. of LT)/RDIVIDER)^6)
uint256 base = _ticketSum * ZOOM / RDIVIDER;
uint256 expo = base.mul(base).mul(base); //^3
expo = expo.mul(expo) / (ZOOM**6); //^6
return (1 + PBASE / (1 + expo.mul(PMULTI)));
}
// get reveiced Tickets, based on current round ticketSum
function getTAmount(uint256 _ethAmount, uint256 _ticketSum)
public
pure
returns(uint256)
{
uint256 _tPrice = getTPrice(_ticketSum);
return _ethAmount.div(_tPrice);
}
// Lotto-Multiplier = 1 + LBase * (Current No. of Tickets / PDivider)^6
function getTMul(uint256 _ticketSum) // Unit Wei
public
pure
returns(uint256)
{
uint256 base = _ticketSum * ZOOM / PDIVIDER;
uint256 expo = base.mul(base).mul(base);
expo = expo.mul(expo); // ^6
return 1 + expo.mul(LBase) / (10**18);
}
// get ticket price, based on current round ticketSum
//unit in ETH, no need / zoom^6
function getTPrice(uint256 _ticketSum)
public
pure
returns(uint256)
{
uint256 base = (_ticketSum + 1).mul(ZOOM) / PDIVIDER;
uint256 expo = base;
expo = expo.mul(expo).mul(expo); // ^3
expo = expo.mul(expo); // ^6
uint256 tPrice = SLP + expo / PN;
return tPrice;
}
// get weight of slot, chance to win grandPot
function getSlotWeight(uint256 _ethAmount, uint256 _ticketSum)
public
pure
returns(uint256)
{
uint256 _tAmount = getTAmount(_ethAmount, _ticketSum);
uint256 _tMul = getTMul(_ticketSum);
return (_tAmount).mul(_tMul);
}
// used to draw grandpot results
// weightRange = roundWeight * grandpot / (grandpot - initGrandPot)
// grandPot = initGrandPot + round investedSum(for grandPot)
function getWeightRange(uint256 grandPot, uint256 initGrandPot, uint256 curRWeight)
public
pure
returns(uint256)
{
//calculate round grandPot-investedSum
uint256 grandPotInvest = grandPot - initGrandPot;
if (grandPotInvest == 0) return 8;
uint256 zoomMul = grandPot * ZOOM / grandPotInvest;
uint256 weightRange = zoomMul * curRWeight / ZOOM;
if (weightRange < curRWeight) weightRange = curRWeight;
return weightRange;
}
}
interface F2mInterface {
function joinNetwork(address[6] _contract) public;
// one time called
function disableRound0() public;
function activeBuy() public;
// Dividends from all sources (DApps, Donate ...)
function pushDividends() public payable;
/**
* Converts all of caller's dividends to tokens.
*/
//function reinvest() public;
//function buy() public payable;
function buyFor(address _buyer) public payable;
function sell(uint256 _tokenAmount) public;
function exit() public;
function devTeamWithdraw() public returns(uint256);
function withdrawFor(address sender) public returns(uint256);
function transfer(address _to, uint256 _tokenAmount) public returns(bool);
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
function setAutoBuy() public;
/*==========================================
= public FUNCTIONS =
==========================================*/
// function totalEthBalance() public view returns(uint256);
function ethBalance(address _address) public view returns(uint256);
function myBalance() public view returns(uint256);
function myEthBalance() public view returns(uint256);
function swapToken() public;
function setNewToken(address _newTokenAddress) public;
}
interface BankInterface {
function joinNetwork(address[6] _contract) public;
// Core functions
function pushToBank(address _player) public payable;
}
interface DevTeamInterface {
function setF2mAddress(address _address) public;
function setLotteryAddress(address _address) public;
function setCitizenAddress(address _address) public;
function setBankAddress(address _address) public;
function setRewardAddress(address _address) public;
function setWhitelistAddress(address _address) public;
function setupNetwork() public;
}
interface LotteryInterface {
function joinNetwork(address[6] _contract) public;
// call one time
function activeFirstRound() public;
// Core Functions
function pushToPot() public payable;
function finalizeable() public view returns(bool);
// bounty
function finalize() public;
function buy(string _sSalt) public payable;
function buyFor(string _sSalt, address _sender) public payable;
//function withdraw() public;
function withdrawFor(address _sender) public returns(uint256);
function getRewardBalance(address _buyer) public view returns(uint256);
function getTotalPot() public view returns(uint256);
// EarlyIncome
function getEarlyIncomeByAddress(address _buyer) public view returns(uint256);
// included claimed amount
// function getEarlyIncomeByAddressRound(address _buyer, uint256 _rId) public view returns(uint256);
function getCurEarlyIncomeByAddress(address _buyer) public view returns(uint256);
// function getCurEarlyIncomeByAddressRound(address _buyer, uint256 _rId) public view returns(uint256);
function getCurRoundId() public view returns(uint256);
// set endRound, prepare to upgrade new version
function setLastRound(uint256 _lastRoundId) public;
function getPInvestedSumByRound(uint256 _rId, address _buyer) public view returns(uint256);
function cashoutable(address _address) public view returns(bool);
function isLastRound() public view returns(bool);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
int256 constant private INT256_MIN = -2**255;
/**
* @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 Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// 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;
}
require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below
int256 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 Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0); // Solidity only automatically asserts when dividing by 0
require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow
int256 c = a / b;
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 Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two 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 Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract Citizen {
using SafeMath for uint256;
event Register(address indexed _member, address indexed _ref);
modifier withdrawRight(){
require((msg.sender == address(bankContract)), "Bank only");
_;
}
modifier onlyAdmin() {
require(msg.sender == devTeam, "admin required");
_;
}
modifier notRegistered(){
require(!isCitizen[msg.sender], "already exist");
_;
}
modifier registered(){
require(isCitizen[msg.sender], "must be a citizen");
_;
}
struct Profile{
uint256 id;
uint256 username;
uint256 refWallet;
address ref;
address[] refTo;
uint256 totalChild;
uint256 donated;
uint256 treeLevel;
// logs
uint256 totalSale;
uint256 allRoundRefIncome;
mapping(uint256 => uint256) roundRefIncome;
mapping(uint256 => uint256) roundRefWallet;
}
//bool public oneWayTicket = true;
mapping (address => Profile) public citizen;
mapping (address => bool) public isCitizen;
mapping (uint256 => address) public idAddress;
mapping (uint256 => address) public usernameAddress;
mapping (uint256 => address[]) levelCitizen;
BankInterface bankContract;
LotteryInterface lotteryContract;
F2mInterface f2mContract;
address devTeam;
uint256 citizenNr;
uint256 lastLevel;
// logs
mapping(uint256 => uint256) public totalRefByRound;
uint256 public totalRefAllround;
constructor (address _devTeam)
public
{
DevTeamInterface(_devTeam).setCitizenAddress(address(this));
devTeam = _devTeam;
// first citizen is the development team
citizenNr = 1;
idAddress[1] = devTeam;
isCitizen[devTeam] = true;
//root => self ref
citizen[devTeam].ref = devTeam;
// username rules bypass
uint256 _username = Helper.stringToUint("f2m");
citizen[devTeam].username = _username;
usernameAddress[_username] = devTeam;
citizen[devTeam].id = 1;
citizen[devTeam].treeLevel = 1;
levelCitizen[1].push(devTeam);
lastLevel = 1;
}
// _contract = [f2mAddress, bankAddress, citizenAddress, lotteryAddress, rewardAddress, whitelistAddress];
function joinNetwork(address[6] _contract)
public
{
require(address(lotteryContract) == 0,"already setup");
f2mContract = F2mInterface(_contract[0]);
bankContract = BankInterface(_contract[1]);
lotteryContract = LotteryInterface(_contract[3]);
}
/*---------- WRITE FUNCTIONS ----------*/
function updateTotalChild(address _address)
private
{
address _member = _address;
while(_member != devTeam) {
_member = getRef(_member);
citizen[_member].totalChild ++;
}
}
function register(string _sUsername, address _ref)
public
notRegistered()
{
require(Helper.validUsername(_sUsername), "invalid username");
address sender = msg.sender;
uint256 _username = Helper.stringToUint(_sUsername);
require(usernameAddress[_username] == 0x0, "username already exist");
usernameAddress[_username] = sender;
//ref must be a citizen, else ref = devTeam
address validRef = isCitizen[_ref] ? _ref : devTeam;
//Welcome new Citizen
isCitizen[sender] = true;
citizen[sender].username = _username;
citizen[sender].ref = validRef;
citizenNr++;
idAddress[citizenNr] = sender;
citizen[sender].id = citizenNr;
uint256 refLevel = citizen[validRef].treeLevel;
if (refLevel == lastLevel) lastLevel++;
citizen[sender].treeLevel = refLevel + 1;
levelCitizen[refLevel + 1].push(sender);
//add child
citizen[validRef].refTo.push(sender);
updateTotalChild(sender);
emit Register(sender, validRef);
}
function updateUsername(string _sNewUsername)
public
registered()
{
require(Helper.validUsername(_sNewUsername), "invalid username");
address sender = msg.sender;
uint256 _newUsername = Helper.stringToUint(_sNewUsername);
require(usernameAddress[_newUsername] == 0x0, "username already exist");
uint256 _oldUsername = citizen[sender].username;
citizen[sender].username = _newUsername;
usernameAddress[_oldUsername] = 0x0;
usernameAddress[_newUsername] = sender;
}
//Sources: Token contract, DApps
function pushRefIncome(address _sender)
public
payable
{
uint256 curRoundId = lotteryContract.getCurRoundId();
uint256 _amount = msg.value;
address sender = _sender;
address ref = getRef(sender);
// logs
citizen[sender].totalSale += _amount;
totalRefAllround += _amount;
totalRefByRound[curRoundId] += _amount;
// push to root
// lower level cost less gas
while (sender != devTeam) {
_amount = _amount / 2;
citizen[ref].refWallet = _amount.add(citizen[ref].refWallet);
citizen[ref].roundRefIncome[curRoundId] += _amount;
citizen[ref].allRoundRefIncome += _amount;
sender = ref;
ref = getRef(sender);
}
citizen[sender].refWallet = _amount.add(citizen[ref].refWallet);
// devTeam Logs
citizen[sender].roundRefIncome[curRoundId] += _amount;
citizen[sender].allRoundRefIncome += _amount;
}
function withdrawFor(address sender)
public
withdrawRight()
returns(uint256)
{
uint256 amount = citizen[sender].refWallet;
if (amount == 0) return 0;
citizen[sender].refWallet = 0;
bankContract.pushToBank.value(amount)(sender);
return amount;
}
function devTeamWithdraw()
public
onlyAdmin()
{
uint256 _amount = citizen[devTeam].refWallet;
if (_amount == 0) return;
devTeam.transfer(_amount);
citizen[devTeam].refWallet = 0;
}
function devTeamReinvest()
public
returns(uint256)
{
address sender = msg.sender;
require(sender == address(f2mContract), "only f2m contract");
uint256 _amount = citizen[devTeam].refWallet;
citizen[devTeam].refWallet = 0;
address(f2mContract).transfer(_amount);
return _amount;
}
/*---------- READ FUNCTIONS ----------*/
function getTotalChild(address _address)
public
view
returns(uint256)
{
return citizen[_address].totalChild;
}
function getAllRoundRefIncome(address _address)
public
view
returns(uint256)
{
return citizen[_address].allRoundRefIncome;
}
function getRoundRefIncome(address _address, uint256 _rId)
public
view
returns(uint256)
{
return citizen[_address].roundRefIncome[_rId];
}
function getRefWallet(address _address)
public
view
returns(uint256)
{
return citizen[_address].refWallet;
}
function getAddressById(uint256 _id)
public
view
returns (address)
{
return idAddress[_id];
}
function getAddressByUserName(string _username)
public
view
returns (address)
{
return usernameAddress[Helper.stringToUint(_username)];
}
function exist(string _username)
public
view
returns (bool)
{
return usernameAddress[Helper.stringToUint(_username)] != 0x0;
}
function getId(address _address)
public
view
returns (uint256)
{
return citizen[_address].id;
}
function getUsername(address _address)
public
view
returns (string)
{
if (!isCitizen[_address]) return "";
return Helper.uintToString(citizen[_address].username);
}
function getUintUsername(address _address)
public
view
returns (uint256)
{
return citizen[_address].username;
}
function getRef(address _address)
public
view
returns (address)
{
return citizen[_address].ref == 0x0 ? devTeam : citizen[_address].ref;
}
function getRefTo(address _address)
public
view
returns (address[])
{
return citizen[_address].refTo;
}
function getRefToById(address _address, uint256 _id)
public
view
returns (address, string, uint256, uint256, uint256, uint256)
{
address _refTo = citizen[_address].refTo[_id];
return (
_refTo,
Helper.uintToString(citizen[_refTo].username),
citizen[_refTo].treeLevel,
citizen[_refTo].refTo.length,
citizen[_refTo].refWallet,
citizen[_refTo].totalSale
);
}
function getRefToLength(address _address)
public
view
returns (uint256)
{
return citizen[_address].refTo.length;
}
function getLevelCitizenLength(uint256 _level)
public
view
returns (uint256)
{
return levelCitizen[_level].length;
}
function getLevelCitizenById(uint256 _level, uint256 _id)
public
view
returns (address)
{
return levelCitizen[_level][_id];
}
function getCitizenLevel(address _address)
public
view
returns (uint256)
{
return citizen[_address].treeLevel;
}
function getLastLevel()
public
view
returns(uint256)
{
return lastLevel;
}
} | bool public oneWayTicket = true; | mapping (address => Profile) public citizen;
| 12,686,262 | [
1,
6430,
1071,
1245,
21831,
13614,
273,
638,
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,
0,
0,
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,
2874,
261,
2867,
516,
11357,
13,
1071,
276,
305,
452,
275,
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
]
|
pragma solidity ^0.5.0;
// Copyright 2019 OpenST Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
//
// http://www.simpletoken.org/
//
// ----------------------------------------------------------------------------
import "./EIP20CoGatewayInterface.sol";
import "../lib/Mutex.sol";
/**
* @title RedeemerProxy is a contract that is deployed by the redeem pool to allow
* redeem of multiple users from within the same redeem pool contract.
* @notice The redeem pool contract will deploy RedeemerProxy contract on behalf of
* the owner. Only the owner can self-destruct the Redeemer Proxy and
* receive all stored value.
*/
contract RedeemerProxy is Mutex {
/* Storage */
/** The Redeem Pool contract address that deployed this contract. */
address public redeemPool;
/** The Redeem Pool deployed the RedeemProxy on behalf of the owner. */
address payable public owner;
/* Modifiers */
/** Requires that msg.sender is the Redeem Pool */
modifier onlyRedeemPool() {
require(
msg.sender == address(redeemPool),
"This function can only be called by the Redeem Pool."
);
_;
}
/** Requires that msg.sender is the owner. */
modifier onlyOwner() {
require(
msg.sender == owner,
"This function can only be called by the owner."
);
_;
}
/* Special Functions */
/**
* @notice Must be constructed by a RedeemPool contract.
*
* @param _owner The owner that this proxy is deployed for.
*/
constructor(address payable _owner)
public
{
redeemPool = msg.sender;
owner = _owner;
}
/* External Functions */
/**
* @notice Initiates the redeem process. In order to redeem, the redeem amount
* and bounty must first be transferred to the RedeemProxy.
* Redeem amount and bounty is transferred to co-gateway contract.
*
* @param _amount Amount that is to be redeem.
* @param _beneficiary The address in the origin chain where value token
* will be returned.
* @param _gasPrice Gas price that redeemer is ready to pay to get the redeem
* and unstake process done.
* @param _gasLimit Gas limit that redeemer is ready to pay.
* @param _nonce Redeem proxy nonce specific to co-gateway.
* @param _hashLock Hashlock provided by the facilitator.
* @param _cogateway Address of the cogateway contract.
*
* @return messageHash_ Hash unique for each request.
*/
function redeem(
uint256 _amount,
address _beneficiary,
uint256 _gasPrice,
uint256 _gasLimit,
uint256 _nonce,
bytes32 _hashLock,
EIP20CoGatewayInterface _cogateway
)
external
payable
mutex
onlyRedeemPool
returns(bytes32 messageHash_)
{
EIP20Interface utilityToken = _cogateway.utilityToken();
uint256 bounty = _cogateway.bounty();
require(
bounty == msg.value,
'Bounty amount must be received.'
);
utilityToken.approve(address(_cogateway),_amount);
messageHash_ = _cogateway.redeem.value(bounty)(
_amount,
_beneficiary,
_gasPrice,
_gasLimit,
_nonce,
_hashLock
);
}
/**
* @notice Destroys this contract. Make sure that you use `transferToken`
* to transfer all remaining token balance of this contract before
* calling this method.
*/
function selfDestruct() external onlyRedeemPool {
selfdestruct(owner);
}
/**
* @notice Transfers EIP20 token to destination address.
*
* @dev It is ok to to be able to transfer to the zero address.
*
* @param _token EIP20 token address.
* @param _to Address to which tokens are transferred.
* @param _value Amount of tokens to be transferred.
*/
function transferToken(
EIP20Interface _token,
address _to,
uint256 _value
)
external
mutex
onlyOwner
{
require(
address(_token) != address(0),
"The token address must not be address zero."
);
require(
_token.transfer(_to, _value),
"EIP20Token transfer returned false."
);
}
}
| * Requires that msg.sender is the owner. */ | modifier onlyOwner() {
require(
msg.sender == owner,
"This function can only be called by the owner."
);
_;
}
public
| 1,758,384 | [
1,
21671,
716,
1234,
18,
15330,
353,
326,
3410,
18,
342,
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,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
12,
203,
5411,
1234,
18,
15330,
422,
3410,
16,
203,
5411,
315,
2503,
445,
848,
1338,
506,
2566,
635,
326,
3410,
1199,
203,
3639,
11272,
203,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
203,
3639,
1071,
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
]
|
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
contract SafeMath {
function safeMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function safeDiv(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 safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// accepted from zeppelin-solidity https://github.com/OpenZeppelin/zeppelin-solidity
/*
* ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
uint public totalSupply;
function balanceOf(address _who) public constant returns (uint);
function allowance(address _owner, address _spender) public constant returns (uint);
function transfer(address _to, uint _value) public returns (bool ok);
function transferFrom(address _from, address _to, uint _value) public returns (bool ok);
function approve(address _spender, uint _value) public returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
// event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
// OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract DSTToken is ERC20, Ownable, SafeMath {
// Token related informations
string public constant name = "Decentralize Silver Token";
string public constant symbol = "DST";
uint256 public constant decimals = 18; // decimal places
uint256 public tokensPerEther = 1500;
// MultiSig Wallet Address
address public DSTMultisig;
// Wallet L,M,N and O address
address dstWalletLMNO;
bool public startStop = false;
mapping (address => uint256) public walletA;
mapping (address => uint256) public walletB;
mapping (address => uint256) public walletC;
mapping (address => uint256) public walletF;
mapping (address => uint256) public walletG;
mapping (address => uint256) public walletH;
mapping (address => uint256) public releasedA;
mapping (address => uint256) public releasedB;
mapping (address => uint256) public releasedC;
mapping (address => uint256) public releasedF;
mapping (address => uint256) public releasedG;
mapping (address => uint256) public releasedH;
// Mapping of token balance and allowed address for each address with transfer limit
mapping (address => uint256) balances;
//mapping of allowed address for each address with tranfer limit
mapping (address => mapping (address => uint256)) allowed;
struct WalletConfig{
uint256 start;
uint256 cliff;
uint256 duration;
}
mapping (uint => address) public walletAddresses;
mapping (uint => WalletConfig) public allWalletConfig;
// @param _dstWalletLMNO Ether Address for wallet L,M,N and O
// Only to be called by Owner of this contract
function setDSTWalletLMNO(address _dstWalletLMNO) onlyOwner external{
require(_dstWalletLMNO != address(0));
dstWalletLMNO = _dstWalletLMNO;
}
// Owner can Set Multisig wallet
// @param _dstMultisig address of Multisig wallet.
function setDSTMultiSig(address _dstMultisig) onlyOwner external{
require(_dstMultisig != address(0));
DSTMultisig = _dstMultisig;
}
function startStopICO(bool status) onlyOwner external{
startStop = status;
}
function addWalletAddressAndTokens(uint _id, address _walletAddress, uint256 _tokens) onlyOwner external{
require(_walletAddress != address(0));
walletAddresses[_id] = _walletAddress;
balances[_walletAddress] = safeAdd(balances[_walletAddress],_tokens); // wallet tokens initialize
}
// function preAllocation(uint256 _walletId, uint256 _tokens) onlyOwner external{
// require(_tokens > 0);
// balances[walletAddresses[_walletId]] = safeAdd(balances[walletAddresses[_walletId]],_tokens); // wallet tokens initialize
// }
function addWalletConfig(uint256 _id, uint256 _start, uint256 _cliff, uint256 _duration) onlyOwner external{
uint256 start = safeAdd(_start,now);
uint256 cliff = safeAdd(start,_cliff);
allWalletConfig[_id] = WalletConfig(
start,
cliff,
_duration
);
}
function assignToken(address _investor,uint256 _tokens) external {
// Check investor address and tokens.Not allow 0 value
require(_investor != address(0) && _tokens > 0);
// Check wallet have enough token balance to assign
require(_tokens <= balances[msg.sender]);
// Debit the tokens from the wallet
balances[msg.sender] = safeSub(balances[msg.sender],_tokens);
// Increasing the totalSupply
totalSupply = safeAdd(totalSupply, _tokens);
// Assign tokens to the investor
if(msg.sender == walletAddresses[0]){
walletA[_investor] = safeAdd(walletA[_investor],_tokens);
}
else if(msg.sender == walletAddresses[1]){
walletB[_investor] = safeAdd(walletB[_investor],_tokens);
}
else if(msg.sender == walletAddresses[2]){
walletC[_investor] = safeAdd(walletC[_investor],_tokens);
}
else if(msg.sender == walletAddresses[5]){
walletF[_investor] = safeAdd(walletF[_investor],_tokens);
}
else if(msg.sender == walletAddresses[6]){
walletG[_investor] = safeAdd(walletG[_investor],_tokens);
}
else if(msg.sender == walletAddresses[7]){
walletH[_investor] = safeAdd(walletH[_investor],_tokens);
}
else{
revert();
}
}
function assignTokenIJK(address _userAddress,uint256 _tokens) external {
require(msg.sender == walletAddresses[8] || msg.sender == walletAddresses[9] || msg.sender == walletAddresses[10]);
// Check investor address and tokens.Not allow 0 value
require(_userAddress != address(0) && _tokens > 0);
// Assign tokens to the investor
assignTokensWallet(msg.sender,_userAddress, _tokens);
}
function withdrawToken() public {
//require(walletA[msg.sender] > 0 || walletB[msg.sender] > 0 || walletC[msg.sender] > 0);
uint256 currentBalance = 0;
if(walletA[msg.sender] > 0){
uint256 unreleasedA = getReleasableAmount(0,msg.sender);
walletA[msg.sender] = safeSub(walletA[msg.sender], unreleasedA);
currentBalance = safeAdd(currentBalance, unreleasedA);
releasedA[msg.sender] = safeAdd(releasedA[msg.sender], unreleasedA);
}
if(walletB[msg.sender] > 0){
uint256 unreleasedB = getReleasableAmount(1,msg.sender);
walletB[msg.sender] = safeSub(walletB[msg.sender], unreleasedB);
currentBalance = safeAdd(currentBalance, unreleasedB);
releasedB[msg.sender] = safeAdd(releasedB[msg.sender], unreleasedB);
}
if(walletC[msg.sender] > 0){
uint256 unreleasedC = getReleasableAmount(2,msg.sender);
walletC[msg.sender] = safeSub(walletC[msg.sender], unreleasedC);
currentBalance = safeAdd(currentBalance, unreleasedC);
releasedC[msg.sender] = safeAdd(releasedC[msg.sender], unreleasedC);
}
require(currentBalance > 0);
// Assign tokens to the sender
balances[msg.sender] = safeAdd(balances[msg.sender], currentBalance);
}
function withdrawBonusToken() public {
//require(walletF[msg.sender] > 0 || walletG[msg.sender] > 0 || walletH[msg.sender] > 0);
uint256 currentBalance = 0;
if(walletF[msg.sender] > 0){
uint256 unreleasedF = getReleasableBonusAmount(5,msg.sender);
walletF[msg.sender] = safeSub(walletF[msg.sender], unreleasedF);
currentBalance = safeAdd(currentBalance, unreleasedF);
releasedF[msg.sender] = safeAdd(releasedF[msg.sender], unreleasedF);
}
if(walletG[msg.sender] > 0){
uint256 unreleasedG = getReleasableBonusAmount(6,msg.sender);
walletG[msg.sender] = safeSub(walletG[msg.sender], unreleasedG);
currentBalance = safeAdd(currentBalance, unreleasedG);
releasedG[msg.sender] = safeAdd(releasedG[msg.sender], unreleasedG);
}
if(walletH[msg.sender] > 0){
uint256 unreleasedH = getReleasableBonusAmount(7,msg.sender);
walletH[msg.sender] = safeSub(walletH[msg.sender], unreleasedH);
currentBalance = safeAdd(currentBalance, unreleasedH);
releasedH[msg.sender] = safeAdd(releasedH[msg.sender], unreleasedH);
}
require(currentBalance > 0);
// Assign tokens to the sender
balances[msg.sender] = safeAdd(balances[msg.sender], currentBalance);
}
function getReleasableAmount(uint256 _walletId,address _beneficiary) public view returns (uint256){
uint256 totalBalance;
if(_walletId == 0){
totalBalance = safeAdd(walletA[_beneficiary], releasedA[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedA[_beneficiary]);
}
else if(_walletId == 1){
totalBalance = safeAdd(walletB[_beneficiary], releasedB[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedB[_beneficiary]);
}
else if(_walletId == 2){
totalBalance = safeAdd(walletC[_beneficiary], releasedC[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedC[_beneficiary]);
}
else{
revert();
}
}
function getReleasableBonusAmount(uint256 _walletId,address _beneficiary) public view returns (uint256){
uint256 totalBalance;
if(_walletId == 5){
totalBalance = safeAdd(walletF[_beneficiary], releasedF[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedF[_beneficiary]);
}
else if(_walletId == 6){
totalBalance = safeAdd(walletG[_beneficiary], releasedG[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedG[_beneficiary]);
}
else if(_walletId == 7){
totalBalance = safeAdd(walletH[_beneficiary], releasedH[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedH[_beneficiary]);
}
else{
revert();
}
}
function getData(uint256 _walletId,uint256 _totalBalance) public view returns (uint256) {
uint256 availableBalanceIn = safeDiv(safeMul(_totalBalance, safeSub(allWalletConfig[_walletId].cliff, allWalletConfig[_walletId].start)), allWalletConfig[_walletId].duration);
return safeMul(availableBalanceIn, safeDiv(getVestedAmount(_walletId,_totalBalance), availableBalanceIn));
}
function getVestedAmount(uint256 _walletId,uint256 _totalBalance) public view returns (uint256) {
uint256 cliff = allWalletConfig[_walletId].cliff;
uint256 start = allWalletConfig[_walletId].start;
uint256 duration = allWalletConfig[_walletId].duration;
if (now < cliff) {
return 0;
} else if (now >= safeAdd(start,duration)) {
return _totalBalance;
} else {
return safeDiv(safeMul(_totalBalance,safeSub(now,start)),duration);
}
}
// Sale of the tokens. Investors can call this method to invest into DST Tokens
function() payable external {
// Allow only to invest in ICO stage
require(startStop);
// Sorry !! We only allow to invest with minimum 1 Ether as value
require(msg.value >= 1 ether);
// multiply by exchange rate to get newly created token amount
uint256 createdTokens = safeMul(msg.value, tokensPerEther);
// Call to Internal function to assign tokens
assignTokensWallet(walletAddresses[3],msg.sender, createdTokens);
}
// DST accepts Cash Investment through manual process in Fiat Currency
// DST Team will assign the tokens to investors manually through this function
//@ param cashInvestor address of investor
//@ param assignedTokens number of tokens to give to investor
function cashInvestment(address cashInvestor, uint256 assignedTokens) onlyOwner external {
// Check if cashInvestor address is set or not
// By mistake tokens mentioned as 0, save the cost of assigning tokens.
require(cashInvestor != address(0) && assignedTokens > 0);
// Call to Internal function to assign tokens
assignTokensWallet(walletAddresses[4],cashInvestor, assignedTokens);
}
// // Function will transfer the tokens to investor's address
// // Common function code for Crowdsale Investor And Cash Investor
// function assignTokens(address investor, uint256 tokens) internal {
// // Creating tokens and increasing the totalSupply
// totalSupply = safeAdd(totalSupply, tokens);
// // Assign new tokens to the sender
// balances[investor] = safeAdd(balances[investor], tokens);
// // Finally token created for sender, log the creation event
// Transfer(0, investor, tokens);
// }
// Function will transfer the tokens to investor's address
// Common function code for Crowdsale Investor And Cash Investor
function assignTokensWallet(address walletAddress,address investor, uint256 tokens) internal {
// Check wallet have enough token balance to assign
require(tokens <= balances[walletAddress]);
// Creating tokens and increasing the totalSupply
totalSupply = safeAdd(totalSupply, tokens);
// Debit the tokens from wallet
balances[walletAddress] = safeSub(balances[walletAddress],tokens);
// Assign new tokens to the sender
balances[investor] = safeAdd(balances[investor], tokens);
// Finally token created for sender, log the creation event
Transfer(0, investor, tokens);
}
function finalizeCrowdSale() external{
// Check DST Multisig wallet set or not
require(DSTMultisig != address(0));
// Send fund to multisig wallet
require(DSTMultisig.send(address(this).balance));
}
// @param _who The address of the investor to check balance
// @return balance tokens of investor address
function balanceOf(address _who) public constant returns (uint) {
return balances[_who];
}
// @param _owner The address of the account owning tokens
// @param _spender The address of the account able to transfer the tokens
// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public constant returns (uint) {
return allowed[_owner][_spender];
}
// Transfer `value` DST tokens from sender's account
// `msg.sender` to provided account address `to`.
// @param _to The address of the recipient
// @param _value The number of DST tokens to transfer
// @return Whether the transfer was successful or not
function transfer(address _to, uint _value) public returns (bool ok) {
//validate receiver address and value.Not allow 0 value
require(_to != 0 && _value > 0);
uint256 senderBalance = balances[msg.sender];
//Check sender have enough balance
require(senderBalance >= _value);
senderBalance = safeSub(senderBalance, _value);
balances[msg.sender] = senderBalance;
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
// Transfer `value` DST tokens from sender 'from'
// to provided account address `to`.
// @param from The address of the sender
// @param to The address of the recipient
// @param value The number of miBoodle to transfer
// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint _value) public returns (bool ok) {
//validate _from,_to address and _value(Now allow with 0)
require(_from != 0 && _to != 0 && _value > 0);
//Check amount is approved by the owner for spender to spent and owner have enough balances
require(allowed[_from][msg.sender] >= _value && balances[_from] >= _value);
balances[_from] = safeSub(balances[_from],_value);
balances[_to] = safeAdd(balances[_to],_value);
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender],_value);
Transfer(_from, _to, _value);
return true;
}
// `msg.sender` approves `spender` to spend `value` tokens
// @param spender The address of the account able to transfer the tokens
// @param value The amount of wei to be approved for transfer
// @return Whether the approval was successful or not
function approve(address _spender, uint _value) public returns (bool ok) {
//validate _spender address
require(_spender != 0);
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
// This method is only use for debit DSTToken from DST wallet L,M,N and O
// @dev Required state: is dstWalletLMNO set
// @param _walletAddress The address of the wallet from tokens debit
// @param token The number of DST tokens to debit
// @return Whether the debit was successful or not
function debitWalletLMNO(address _walletAddress,uint256 token) external onlyDSTWalletLMNO returns (bool){
// Check if DST wallet LMNO is set or not
require(dstWalletLMNO != address(0));
// Check wallet have enough token and token is valid
require(balances[_walletAddress] >= token && token > 0);
// Increasing the totalSupply
totalSupply = safeAdd(totalSupply, token);
// Debit tokens from wallet balance
balances[_walletAddress] = safeSub(balances[_walletAddress],token);
return true;
}
// This method is only use for credit DSTToken to DST wallet L,M,N and O users
// @dev Required state: is dstWalletLMNO set
// @param claimAddress The address of the wallet user to credit tokens
// @param token The number of DST tokens to credit
// @return Whether the credit was successful or not
function creditWalletUserLMNO(address claimAddress,uint256 token) external onlyDSTWalletLMNO returns (bool){
// Check if DST wallet LMNO is set or not
require(dstWalletLMNO != address(0));
// Check claiment address and token is valid or not
require(claimAddress != address(0) && token > 0);
// Assign tokens to user
balances[claimAddress] = safeAdd(balances[claimAddress], token);
// balances[_walletAddress] = safeSub(balances[_walletAddress],token);
return true;
}
// DSTWalletLMNO related modifer
// @dev Throws if called by any account other than the DSTWalletLMNO owner
modifier onlyDSTWalletLMNO() {
require(msg.sender == dstWalletLMNO);
_;
}
} | Token related informations MultiSig Wallet Address Wallet L,M,N and O address Mapping of token balance and allowed address for each address with transfer limitmapping of allowed address for each address with tranfer limit | contract DSTToken is ERC20, Ownable, SafeMath {
string public constant name = "Decentralize Silver Token";
string public constant symbol = "DST";
uint256 public tokensPerEther = 1500;
address public DSTMultisig;
address dstWalletLMNO;
bool public startStop = false;
mapping (address => uint256) public walletA;
mapping (address => uint256) public walletB;
mapping (address => uint256) public walletC;
mapping (address => uint256) public walletF;
mapping (address => uint256) public walletG;
mapping (address => uint256) public walletH;
mapping (address => uint256) public releasedA;
mapping (address => uint256) public releasedB;
mapping (address => uint256) public releasedC;
mapping (address => uint256) public releasedF;
mapping (address => uint256) public releasedG;
mapping (address => uint256) public releasedH;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
struct WalletConfig{
uint256 start;
uint256 cliff;
uint256 duration;
}
mapping (uint => address) public walletAddresses;
mapping (uint => WalletConfig) public allWalletConfig;
function setDSTWalletLMNO(address _dstWalletLMNO) onlyOwner external{
require(_dstWalletLMNO != address(0));
dstWalletLMNO = _dstWalletLMNO;
}
function setDSTMultiSig(address _dstMultisig) onlyOwner external{
require(_dstMultisig != address(0));
DSTMultisig = _dstMultisig;
}
function startStopICO(bool status) onlyOwner external{
startStop = status;
}
function addWalletAddressAndTokens(uint _id, address _walletAddress, uint256 _tokens) onlyOwner external{
require(_walletAddress != address(0));
walletAddresses[_id] = _walletAddress;
}
function addWalletConfig(uint256 _id, uint256 _start, uint256 _cliff, uint256 _duration) onlyOwner external{
uint256 start = safeAdd(_start,now);
uint256 cliff = safeAdd(start,_cliff);
allWalletConfig[_id] = WalletConfig(
start,
cliff,
_duration
);
}
function assignToken(address _investor,uint256 _tokens) external {
require(_investor != address(0) && _tokens > 0);
require(_tokens <= balances[msg.sender]);
balances[msg.sender] = safeSub(balances[msg.sender],_tokens);
totalSupply = safeAdd(totalSupply, _tokens);
if(msg.sender == walletAddresses[0]){
walletA[_investor] = safeAdd(walletA[_investor],_tokens);
}
else if(msg.sender == walletAddresses[1]){
walletB[_investor] = safeAdd(walletB[_investor],_tokens);
}
else if(msg.sender == walletAddresses[2]){
walletC[_investor] = safeAdd(walletC[_investor],_tokens);
}
else if(msg.sender == walletAddresses[5]){
walletF[_investor] = safeAdd(walletF[_investor],_tokens);
}
else if(msg.sender == walletAddresses[6]){
walletG[_investor] = safeAdd(walletG[_investor],_tokens);
}
else if(msg.sender == walletAddresses[7]){
walletH[_investor] = safeAdd(walletH[_investor],_tokens);
}
else{
revert();
}
}
function assignToken(address _investor,uint256 _tokens) external {
require(_investor != address(0) && _tokens > 0);
require(_tokens <= balances[msg.sender]);
balances[msg.sender] = safeSub(balances[msg.sender],_tokens);
totalSupply = safeAdd(totalSupply, _tokens);
if(msg.sender == walletAddresses[0]){
walletA[_investor] = safeAdd(walletA[_investor],_tokens);
}
else if(msg.sender == walletAddresses[1]){
walletB[_investor] = safeAdd(walletB[_investor],_tokens);
}
else if(msg.sender == walletAddresses[2]){
walletC[_investor] = safeAdd(walletC[_investor],_tokens);
}
else if(msg.sender == walletAddresses[5]){
walletF[_investor] = safeAdd(walletF[_investor],_tokens);
}
else if(msg.sender == walletAddresses[6]){
walletG[_investor] = safeAdd(walletG[_investor],_tokens);
}
else if(msg.sender == walletAddresses[7]){
walletH[_investor] = safeAdd(walletH[_investor],_tokens);
}
else{
revert();
}
}
function assignToken(address _investor,uint256 _tokens) external {
require(_investor != address(0) && _tokens > 0);
require(_tokens <= balances[msg.sender]);
balances[msg.sender] = safeSub(balances[msg.sender],_tokens);
totalSupply = safeAdd(totalSupply, _tokens);
if(msg.sender == walletAddresses[0]){
walletA[_investor] = safeAdd(walletA[_investor],_tokens);
}
else if(msg.sender == walletAddresses[1]){
walletB[_investor] = safeAdd(walletB[_investor],_tokens);
}
else if(msg.sender == walletAddresses[2]){
walletC[_investor] = safeAdd(walletC[_investor],_tokens);
}
else if(msg.sender == walletAddresses[5]){
walletF[_investor] = safeAdd(walletF[_investor],_tokens);
}
else if(msg.sender == walletAddresses[6]){
walletG[_investor] = safeAdd(walletG[_investor],_tokens);
}
else if(msg.sender == walletAddresses[7]){
walletH[_investor] = safeAdd(walletH[_investor],_tokens);
}
else{
revert();
}
}
function assignToken(address _investor,uint256 _tokens) external {
require(_investor != address(0) && _tokens > 0);
require(_tokens <= balances[msg.sender]);
balances[msg.sender] = safeSub(balances[msg.sender],_tokens);
totalSupply = safeAdd(totalSupply, _tokens);
if(msg.sender == walletAddresses[0]){
walletA[_investor] = safeAdd(walletA[_investor],_tokens);
}
else if(msg.sender == walletAddresses[1]){
walletB[_investor] = safeAdd(walletB[_investor],_tokens);
}
else if(msg.sender == walletAddresses[2]){
walletC[_investor] = safeAdd(walletC[_investor],_tokens);
}
else if(msg.sender == walletAddresses[5]){
walletF[_investor] = safeAdd(walletF[_investor],_tokens);
}
else if(msg.sender == walletAddresses[6]){
walletG[_investor] = safeAdd(walletG[_investor],_tokens);
}
else if(msg.sender == walletAddresses[7]){
walletH[_investor] = safeAdd(walletH[_investor],_tokens);
}
else{
revert();
}
}
function assignToken(address _investor,uint256 _tokens) external {
require(_investor != address(0) && _tokens > 0);
require(_tokens <= balances[msg.sender]);
balances[msg.sender] = safeSub(balances[msg.sender],_tokens);
totalSupply = safeAdd(totalSupply, _tokens);
if(msg.sender == walletAddresses[0]){
walletA[_investor] = safeAdd(walletA[_investor],_tokens);
}
else if(msg.sender == walletAddresses[1]){
walletB[_investor] = safeAdd(walletB[_investor],_tokens);
}
else if(msg.sender == walletAddresses[2]){
walletC[_investor] = safeAdd(walletC[_investor],_tokens);
}
else if(msg.sender == walletAddresses[5]){
walletF[_investor] = safeAdd(walletF[_investor],_tokens);
}
else if(msg.sender == walletAddresses[6]){
walletG[_investor] = safeAdd(walletG[_investor],_tokens);
}
else if(msg.sender == walletAddresses[7]){
walletH[_investor] = safeAdd(walletH[_investor],_tokens);
}
else{
revert();
}
}
function assignToken(address _investor,uint256 _tokens) external {
require(_investor != address(0) && _tokens > 0);
require(_tokens <= balances[msg.sender]);
balances[msg.sender] = safeSub(balances[msg.sender],_tokens);
totalSupply = safeAdd(totalSupply, _tokens);
if(msg.sender == walletAddresses[0]){
walletA[_investor] = safeAdd(walletA[_investor],_tokens);
}
else if(msg.sender == walletAddresses[1]){
walletB[_investor] = safeAdd(walletB[_investor],_tokens);
}
else if(msg.sender == walletAddresses[2]){
walletC[_investor] = safeAdd(walletC[_investor],_tokens);
}
else if(msg.sender == walletAddresses[5]){
walletF[_investor] = safeAdd(walletF[_investor],_tokens);
}
else if(msg.sender == walletAddresses[6]){
walletG[_investor] = safeAdd(walletG[_investor],_tokens);
}
else if(msg.sender == walletAddresses[7]){
walletH[_investor] = safeAdd(walletH[_investor],_tokens);
}
else{
revert();
}
}
function assignToken(address _investor,uint256 _tokens) external {
require(_investor != address(0) && _tokens > 0);
require(_tokens <= balances[msg.sender]);
balances[msg.sender] = safeSub(balances[msg.sender],_tokens);
totalSupply = safeAdd(totalSupply, _tokens);
if(msg.sender == walletAddresses[0]){
walletA[_investor] = safeAdd(walletA[_investor],_tokens);
}
else if(msg.sender == walletAddresses[1]){
walletB[_investor] = safeAdd(walletB[_investor],_tokens);
}
else if(msg.sender == walletAddresses[2]){
walletC[_investor] = safeAdd(walletC[_investor],_tokens);
}
else if(msg.sender == walletAddresses[5]){
walletF[_investor] = safeAdd(walletF[_investor],_tokens);
}
else if(msg.sender == walletAddresses[6]){
walletG[_investor] = safeAdd(walletG[_investor],_tokens);
}
else if(msg.sender == walletAddresses[7]){
walletH[_investor] = safeAdd(walletH[_investor],_tokens);
}
else{
revert();
}
}
function assignToken(address _investor,uint256 _tokens) external {
require(_investor != address(0) && _tokens > 0);
require(_tokens <= balances[msg.sender]);
balances[msg.sender] = safeSub(balances[msg.sender],_tokens);
totalSupply = safeAdd(totalSupply, _tokens);
if(msg.sender == walletAddresses[0]){
walletA[_investor] = safeAdd(walletA[_investor],_tokens);
}
else if(msg.sender == walletAddresses[1]){
walletB[_investor] = safeAdd(walletB[_investor],_tokens);
}
else if(msg.sender == walletAddresses[2]){
walletC[_investor] = safeAdd(walletC[_investor],_tokens);
}
else if(msg.sender == walletAddresses[5]){
walletF[_investor] = safeAdd(walletF[_investor],_tokens);
}
else if(msg.sender == walletAddresses[6]){
walletG[_investor] = safeAdd(walletG[_investor],_tokens);
}
else if(msg.sender == walletAddresses[7]){
walletH[_investor] = safeAdd(walletH[_investor],_tokens);
}
else{
revert();
}
}
function assignTokenIJK(address _userAddress,uint256 _tokens) external {
require(msg.sender == walletAddresses[8] || msg.sender == walletAddresses[9] || msg.sender == walletAddresses[10]);
require(_userAddress != address(0) && _tokens > 0);
assignTokensWallet(msg.sender,_userAddress, _tokens);
}
function withdrawToken() public {
uint256 currentBalance = 0;
if(walletA[msg.sender] > 0){
uint256 unreleasedA = getReleasableAmount(0,msg.sender);
walletA[msg.sender] = safeSub(walletA[msg.sender], unreleasedA);
currentBalance = safeAdd(currentBalance, unreleasedA);
releasedA[msg.sender] = safeAdd(releasedA[msg.sender], unreleasedA);
}
if(walletB[msg.sender] > 0){
uint256 unreleasedB = getReleasableAmount(1,msg.sender);
walletB[msg.sender] = safeSub(walletB[msg.sender], unreleasedB);
currentBalance = safeAdd(currentBalance, unreleasedB);
releasedB[msg.sender] = safeAdd(releasedB[msg.sender], unreleasedB);
}
if(walletC[msg.sender] > 0){
uint256 unreleasedC = getReleasableAmount(2,msg.sender);
walletC[msg.sender] = safeSub(walletC[msg.sender], unreleasedC);
currentBalance = safeAdd(currentBalance, unreleasedC);
releasedC[msg.sender] = safeAdd(releasedC[msg.sender], unreleasedC);
}
require(currentBalance > 0);
}
function withdrawToken() public {
uint256 currentBalance = 0;
if(walletA[msg.sender] > 0){
uint256 unreleasedA = getReleasableAmount(0,msg.sender);
walletA[msg.sender] = safeSub(walletA[msg.sender], unreleasedA);
currentBalance = safeAdd(currentBalance, unreleasedA);
releasedA[msg.sender] = safeAdd(releasedA[msg.sender], unreleasedA);
}
if(walletB[msg.sender] > 0){
uint256 unreleasedB = getReleasableAmount(1,msg.sender);
walletB[msg.sender] = safeSub(walletB[msg.sender], unreleasedB);
currentBalance = safeAdd(currentBalance, unreleasedB);
releasedB[msg.sender] = safeAdd(releasedB[msg.sender], unreleasedB);
}
if(walletC[msg.sender] > 0){
uint256 unreleasedC = getReleasableAmount(2,msg.sender);
walletC[msg.sender] = safeSub(walletC[msg.sender], unreleasedC);
currentBalance = safeAdd(currentBalance, unreleasedC);
releasedC[msg.sender] = safeAdd(releasedC[msg.sender], unreleasedC);
}
require(currentBalance > 0);
}
function withdrawToken() public {
uint256 currentBalance = 0;
if(walletA[msg.sender] > 0){
uint256 unreleasedA = getReleasableAmount(0,msg.sender);
walletA[msg.sender] = safeSub(walletA[msg.sender], unreleasedA);
currentBalance = safeAdd(currentBalance, unreleasedA);
releasedA[msg.sender] = safeAdd(releasedA[msg.sender], unreleasedA);
}
if(walletB[msg.sender] > 0){
uint256 unreleasedB = getReleasableAmount(1,msg.sender);
walletB[msg.sender] = safeSub(walletB[msg.sender], unreleasedB);
currentBalance = safeAdd(currentBalance, unreleasedB);
releasedB[msg.sender] = safeAdd(releasedB[msg.sender], unreleasedB);
}
if(walletC[msg.sender] > 0){
uint256 unreleasedC = getReleasableAmount(2,msg.sender);
walletC[msg.sender] = safeSub(walletC[msg.sender], unreleasedC);
currentBalance = safeAdd(currentBalance, unreleasedC);
releasedC[msg.sender] = safeAdd(releasedC[msg.sender], unreleasedC);
}
require(currentBalance > 0);
}
function withdrawToken() public {
uint256 currentBalance = 0;
if(walletA[msg.sender] > 0){
uint256 unreleasedA = getReleasableAmount(0,msg.sender);
walletA[msg.sender] = safeSub(walletA[msg.sender], unreleasedA);
currentBalance = safeAdd(currentBalance, unreleasedA);
releasedA[msg.sender] = safeAdd(releasedA[msg.sender], unreleasedA);
}
if(walletB[msg.sender] > 0){
uint256 unreleasedB = getReleasableAmount(1,msg.sender);
walletB[msg.sender] = safeSub(walletB[msg.sender], unreleasedB);
currentBalance = safeAdd(currentBalance, unreleasedB);
releasedB[msg.sender] = safeAdd(releasedB[msg.sender], unreleasedB);
}
if(walletC[msg.sender] > 0){
uint256 unreleasedC = getReleasableAmount(2,msg.sender);
walletC[msg.sender] = safeSub(walletC[msg.sender], unreleasedC);
currentBalance = safeAdd(currentBalance, unreleasedC);
releasedC[msg.sender] = safeAdd(releasedC[msg.sender], unreleasedC);
}
require(currentBalance > 0);
}
balances[msg.sender] = safeAdd(balances[msg.sender], currentBalance);
function withdrawBonusToken() public {
uint256 currentBalance = 0;
if(walletF[msg.sender] > 0){
uint256 unreleasedF = getReleasableBonusAmount(5,msg.sender);
walletF[msg.sender] = safeSub(walletF[msg.sender], unreleasedF);
currentBalance = safeAdd(currentBalance, unreleasedF);
releasedF[msg.sender] = safeAdd(releasedF[msg.sender], unreleasedF);
}
if(walletG[msg.sender] > 0){
uint256 unreleasedG = getReleasableBonusAmount(6,msg.sender);
walletG[msg.sender] = safeSub(walletG[msg.sender], unreleasedG);
currentBalance = safeAdd(currentBalance, unreleasedG);
releasedG[msg.sender] = safeAdd(releasedG[msg.sender], unreleasedG);
}
if(walletH[msg.sender] > 0){
uint256 unreleasedH = getReleasableBonusAmount(7,msg.sender);
walletH[msg.sender] = safeSub(walletH[msg.sender], unreleasedH);
currentBalance = safeAdd(currentBalance, unreleasedH);
releasedH[msg.sender] = safeAdd(releasedH[msg.sender], unreleasedH);
}
require(currentBalance > 0);
}
function withdrawBonusToken() public {
uint256 currentBalance = 0;
if(walletF[msg.sender] > 0){
uint256 unreleasedF = getReleasableBonusAmount(5,msg.sender);
walletF[msg.sender] = safeSub(walletF[msg.sender], unreleasedF);
currentBalance = safeAdd(currentBalance, unreleasedF);
releasedF[msg.sender] = safeAdd(releasedF[msg.sender], unreleasedF);
}
if(walletG[msg.sender] > 0){
uint256 unreleasedG = getReleasableBonusAmount(6,msg.sender);
walletG[msg.sender] = safeSub(walletG[msg.sender], unreleasedG);
currentBalance = safeAdd(currentBalance, unreleasedG);
releasedG[msg.sender] = safeAdd(releasedG[msg.sender], unreleasedG);
}
if(walletH[msg.sender] > 0){
uint256 unreleasedH = getReleasableBonusAmount(7,msg.sender);
walletH[msg.sender] = safeSub(walletH[msg.sender], unreleasedH);
currentBalance = safeAdd(currentBalance, unreleasedH);
releasedH[msg.sender] = safeAdd(releasedH[msg.sender], unreleasedH);
}
require(currentBalance > 0);
}
function withdrawBonusToken() public {
uint256 currentBalance = 0;
if(walletF[msg.sender] > 0){
uint256 unreleasedF = getReleasableBonusAmount(5,msg.sender);
walletF[msg.sender] = safeSub(walletF[msg.sender], unreleasedF);
currentBalance = safeAdd(currentBalance, unreleasedF);
releasedF[msg.sender] = safeAdd(releasedF[msg.sender], unreleasedF);
}
if(walletG[msg.sender] > 0){
uint256 unreleasedG = getReleasableBonusAmount(6,msg.sender);
walletG[msg.sender] = safeSub(walletG[msg.sender], unreleasedG);
currentBalance = safeAdd(currentBalance, unreleasedG);
releasedG[msg.sender] = safeAdd(releasedG[msg.sender], unreleasedG);
}
if(walletH[msg.sender] > 0){
uint256 unreleasedH = getReleasableBonusAmount(7,msg.sender);
walletH[msg.sender] = safeSub(walletH[msg.sender], unreleasedH);
currentBalance = safeAdd(currentBalance, unreleasedH);
releasedH[msg.sender] = safeAdd(releasedH[msg.sender], unreleasedH);
}
require(currentBalance > 0);
}
function withdrawBonusToken() public {
uint256 currentBalance = 0;
if(walletF[msg.sender] > 0){
uint256 unreleasedF = getReleasableBonusAmount(5,msg.sender);
walletF[msg.sender] = safeSub(walletF[msg.sender], unreleasedF);
currentBalance = safeAdd(currentBalance, unreleasedF);
releasedF[msg.sender] = safeAdd(releasedF[msg.sender], unreleasedF);
}
if(walletG[msg.sender] > 0){
uint256 unreleasedG = getReleasableBonusAmount(6,msg.sender);
walletG[msg.sender] = safeSub(walletG[msg.sender], unreleasedG);
currentBalance = safeAdd(currentBalance, unreleasedG);
releasedG[msg.sender] = safeAdd(releasedG[msg.sender], unreleasedG);
}
if(walletH[msg.sender] > 0){
uint256 unreleasedH = getReleasableBonusAmount(7,msg.sender);
walletH[msg.sender] = safeSub(walletH[msg.sender], unreleasedH);
currentBalance = safeAdd(currentBalance, unreleasedH);
releasedH[msg.sender] = safeAdd(releasedH[msg.sender], unreleasedH);
}
require(currentBalance > 0);
}
balances[msg.sender] = safeAdd(balances[msg.sender], currentBalance);
function getReleasableAmount(uint256 _walletId,address _beneficiary) public view returns (uint256){
uint256 totalBalance;
if(_walletId == 0){
totalBalance = safeAdd(walletA[_beneficiary], releasedA[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedA[_beneficiary]);
}
else if(_walletId == 1){
totalBalance = safeAdd(walletB[_beneficiary], releasedB[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedB[_beneficiary]);
}
else if(_walletId == 2){
totalBalance = safeAdd(walletC[_beneficiary], releasedC[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedC[_beneficiary]);
}
else{
revert();
}
}
function getReleasableAmount(uint256 _walletId,address _beneficiary) public view returns (uint256){
uint256 totalBalance;
if(_walletId == 0){
totalBalance = safeAdd(walletA[_beneficiary], releasedA[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedA[_beneficiary]);
}
else if(_walletId == 1){
totalBalance = safeAdd(walletB[_beneficiary], releasedB[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedB[_beneficiary]);
}
else if(_walletId == 2){
totalBalance = safeAdd(walletC[_beneficiary], releasedC[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedC[_beneficiary]);
}
else{
revert();
}
}
function getReleasableAmount(uint256 _walletId,address _beneficiary) public view returns (uint256){
uint256 totalBalance;
if(_walletId == 0){
totalBalance = safeAdd(walletA[_beneficiary], releasedA[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedA[_beneficiary]);
}
else if(_walletId == 1){
totalBalance = safeAdd(walletB[_beneficiary], releasedB[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedB[_beneficiary]);
}
else if(_walletId == 2){
totalBalance = safeAdd(walletC[_beneficiary], releasedC[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedC[_beneficiary]);
}
else{
revert();
}
}
function getReleasableAmount(uint256 _walletId,address _beneficiary) public view returns (uint256){
uint256 totalBalance;
if(_walletId == 0){
totalBalance = safeAdd(walletA[_beneficiary], releasedA[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedA[_beneficiary]);
}
else if(_walletId == 1){
totalBalance = safeAdd(walletB[_beneficiary], releasedB[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedB[_beneficiary]);
}
else if(_walletId == 2){
totalBalance = safeAdd(walletC[_beneficiary], releasedC[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedC[_beneficiary]);
}
else{
revert();
}
}
function getReleasableAmount(uint256 _walletId,address _beneficiary) public view returns (uint256){
uint256 totalBalance;
if(_walletId == 0){
totalBalance = safeAdd(walletA[_beneficiary], releasedA[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedA[_beneficiary]);
}
else if(_walletId == 1){
totalBalance = safeAdd(walletB[_beneficiary], releasedB[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedB[_beneficiary]);
}
else if(_walletId == 2){
totalBalance = safeAdd(walletC[_beneficiary], releasedC[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedC[_beneficiary]);
}
else{
revert();
}
}
function getReleasableBonusAmount(uint256 _walletId,address _beneficiary) public view returns (uint256){
uint256 totalBalance;
if(_walletId == 5){
totalBalance = safeAdd(walletF[_beneficiary], releasedF[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedF[_beneficiary]);
}
else if(_walletId == 6){
totalBalance = safeAdd(walletG[_beneficiary], releasedG[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedG[_beneficiary]);
}
else if(_walletId == 7){
totalBalance = safeAdd(walletH[_beneficiary], releasedH[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedH[_beneficiary]);
}
else{
revert();
}
}
function getReleasableBonusAmount(uint256 _walletId,address _beneficiary) public view returns (uint256){
uint256 totalBalance;
if(_walletId == 5){
totalBalance = safeAdd(walletF[_beneficiary], releasedF[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedF[_beneficiary]);
}
else if(_walletId == 6){
totalBalance = safeAdd(walletG[_beneficiary], releasedG[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedG[_beneficiary]);
}
else if(_walletId == 7){
totalBalance = safeAdd(walletH[_beneficiary], releasedH[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedH[_beneficiary]);
}
else{
revert();
}
}
function getReleasableBonusAmount(uint256 _walletId,address _beneficiary) public view returns (uint256){
uint256 totalBalance;
if(_walletId == 5){
totalBalance = safeAdd(walletF[_beneficiary], releasedF[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedF[_beneficiary]);
}
else if(_walletId == 6){
totalBalance = safeAdd(walletG[_beneficiary], releasedG[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedG[_beneficiary]);
}
else if(_walletId == 7){
totalBalance = safeAdd(walletH[_beneficiary], releasedH[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedH[_beneficiary]);
}
else{
revert();
}
}
function getReleasableBonusAmount(uint256 _walletId,address _beneficiary) public view returns (uint256){
uint256 totalBalance;
if(_walletId == 5){
totalBalance = safeAdd(walletF[_beneficiary], releasedF[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedF[_beneficiary]);
}
else if(_walletId == 6){
totalBalance = safeAdd(walletG[_beneficiary], releasedG[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedG[_beneficiary]);
}
else if(_walletId == 7){
totalBalance = safeAdd(walletH[_beneficiary], releasedH[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedH[_beneficiary]);
}
else{
revert();
}
}
function getReleasableBonusAmount(uint256 _walletId,address _beneficiary) public view returns (uint256){
uint256 totalBalance;
if(_walletId == 5){
totalBalance = safeAdd(walletF[_beneficiary], releasedF[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedF[_beneficiary]);
}
else if(_walletId == 6){
totalBalance = safeAdd(walletG[_beneficiary], releasedG[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedG[_beneficiary]);
}
else if(_walletId == 7){
totalBalance = safeAdd(walletH[_beneficiary], releasedH[_beneficiary]);
return safeSub(getData(_walletId,totalBalance), releasedH[_beneficiary]);
}
else{
revert();
}
}
function getData(uint256 _walletId,uint256 _totalBalance) public view returns (uint256) {
uint256 availableBalanceIn = safeDiv(safeMul(_totalBalance, safeSub(allWalletConfig[_walletId].cliff, allWalletConfig[_walletId].start)), allWalletConfig[_walletId].duration);
return safeMul(availableBalanceIn, safeDiv(getVestedAmount(_walletId,_totalBalance), availableBalanceIn));
}
function getVestedAmount(uint256 _walletId,uint256 _totalBalance) public view returns (uint256) {
uint256 cliff = allWalletConfig[_walletId].cliff;
uint256 start = allWalletConfig[_walletId].start;
uint256 duration = allWalletConfig[_walletId].duration;
if (now < cliff) {
return 0;
return _totalBalance;
return safeDiv(safeMul(_totalBalance,safeSub(now,start)),duration);
}
}
function getVestedAmount(uint256 _walletId,uint256 _totalBalance) public view returns (uint256) {
uint256 cliff = allWalletConfig[_walletId].cliff;
uint256 start = allWalletConfig[_walletId].start;
uint256 duration = allWalletConfig[_walletId].duration;
if (now < cliff) {
return 0;
return _totalBalance;
return safeDiv(safeMul(_totalBalance,safeSub(now,start)),duration);
}
}
} else if (now >= safeAdd(start,duration)) {
} else {
function() payable external {
require(startStop);
require(msg.value >= 1 ether);
uint256 createdTokens = safeMul(msg.value, tokensPerEther);
assignTokensWallet(walletAddresses[3],msg.sender, createdTokens);
}
function cashInvestment(address cashInvestor, uint256 assignedTokens) onlyOwner external {
require(cashInvestor != address(0) && assignedTokens > 0);
assignTokensWallet(walletAddresses[4],cashInvestor, assignedTokens);
}
function assignTokensWallet(address walletAddress,address investor, uint256 tokens) internal {
require(tokens <= balances[walletAddress]);
totalSupply = safeAdd(totalSupply, tokens);
balances[walletAddress] = safeSub(balances[walletAddress],tokens);
balances[investor] = safeAdd(balances[investor], tokens);
Transfer(0, investor, tokens);
}
function finalizeCrowdSale() external{
require(DSTMultisig != address(0));
require(DSTMultisig.send(address(this).balance));
}
function balanceOf(address _who) public constant returns (uint) {
return balances[_who];
}
function allowance(address _owner, address _spender) public constant returns (uint) {
return allowed[_owner][_spender];
}
function transfer(address _to, uint _value) public returns (bool ok) {
require(_to != 0 && _value > 0);
uint256 senderBalance = balances[msg.sender];
require(senderBalance >= _value);
senderBalance = safeSub(senderBalance, _value);
balances[msg.sender] = senderBalance;
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) public returns (bool ok) {
require(_from != 0 && _to != 0 && _value > 0);
require(allowed[_from][msg.sender] >= _value && balances[_from] >= _value);
balances[_from] = safeSub(balances[_from],_value);
balances[_to] = safeAdd(balances[_to],_value);
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender],_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public returns (bool ok) {
require(_spender != 0);
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function debitWalletLMNO(address _walletAddress,uint256 token) external onlyDSTWalletLMNO returns (bool){
require(dstWalletLMNO != address(0));
require(balances[_walletAddress] >= token && token > 0);
totalSupply = safeAdd(totalSupply, token);
balances[_walletAddress] = safeSub(balances[_walletAddress],token);
return true;
}
function creditWalletUserLMNO(address claimAddress,uint256 token) external onlyDSTWalletLMNO returns (bool){
require(dstWalletLMNO != address(0));
require(claimAddress != address(0) && token > 0);
balances[claimAddress] = safeAdd(balances[claimAddress], token);
return true;
}
modifier onlyDSTWalletLMNO() {
require(msg.sender == dstWalletLMNO);
_;
}
} | 2,132,448 | [
1,
1345,
3746,
26978,
5991,
8267,
20126,
5267,
20126,
511,
16,
49,
16,
50,
471,
531,
1758,
9408,
434,
1147,
11013,
471,
2935,
1758,
364,
1517,
1758,
598,
7412,
1800,
6770,
434,
2935,
1758,
364,
1517,
1758,
598,
13637,
586,
1800,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
463,
882,
1345,
353,
4232,
39,
3462,
16,
14223,
6914,
16,
14060,
10477,
288,
203,
203,
565,
533,
1071,
5381,
508,
273,
315,
1799,
12839,
554,
348,
330,
502,
3155,
14432,
203,
565,
533,
1071,
5381,
3273,
273,
315,
40,
882,
14432,
203,
203,
565,
2254,
5034,
1071,
2430,
2173,
41,
1136,
273,
4711,
713,
31,
203,
203,
565,
1758,
1071,
463,
882,
5049,
291,
360,
31,
203,
203,
565,
1758,
3046,
16936,
17063,
3417,
31,
203,
203,
565,
1426,
1071,
787,
4947,
273,
629,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
9230,
37,
31,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
9230,
38,
31,
7010,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
9230,
39,
31,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
9230,
42,
31,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
9230,
43,
31,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
9230,
44,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
15976,
37,
31,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
15976,
38,
31,
7010,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
15976,
39,
31,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
15976,
42,
31,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
15976,
43,
31,
7010,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
15976,
44,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "../library/openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../library/Pausable.sol";
import "../library/kip/IKIP7.sol";
import "../interface/IPoolToken.sol";
import "../interface/IBasePool.sol";
import "./StableSwap.sol";
/**
* @dev BasePool is the solidity implementation of Curve Finance
* Original code https://github.com/curvefi/curve-contract/blob/master/contracts/pools/3pool/StableSwap3Pool.vy
*/
abstract contract BasePool is IBasePool, StableSwap {
// @dev WARN: be careful to add new variable here
uint256[50] private __storageBuffer;
constructor(uint256 _N) StableSwap(_N) {}
/// @notice Contract initializer
/// @param _coins Addresses of KIP7 contracts of coins
/// @param _poolToken Address of the token representing LP share
/// @param _initialA Amplification coefficient multiplied by n * (n - 1)
/// @param _fee Fee to charge for exchanges
/// @param _adminFee Admin fee
function __BasePool_init(
address[] memory _coins,
uint256[] memory _PRECISION_MUL,
uint256[] memory _RATES,
address _poolToken,
uint256 _initialA,
uint256 _fee,
uint256 _adminFee
) internal initializer {
__StableSwap_init(_coins, _PRECISION_MUL, _RATES, _poolToken, _initialA, _fee, _adminFee);
}
function balances(uint256 i) public view override(II4ISwapPool, StableSwap) returns (uint256) {
return _storedBalances[i];
}
// 10**18 precision
function _xp() internal view returns (uint256[] memory) {
uint256[] memory result = new uint256[](N_COINS);
for (uint256 i = 0; i < N_COINS; i++) {
result[i] = (RATES[i] * _storedBalances[i]) / PRECISION;
}
return result;
}
// 10**18 precision
function _xpMem(uint256[] memory _balances) internal view returns (uint256[] memory) {
uint256[] memory result = new uint256[](N_COINS);
for (uint256 i = 0; i < N_COINS; i++) {
result[i] = (RATES[i] * _balances[i]) / PRECISION;
}
return result;
}
function getDMem(uint256[] memory _balances, uint256 amp) internal view returns (uint256) {
return getD(_xpMem(_balances), amp);
}
function getVirtualPrice() external view override returns (uint256) {
/*
Returns portfolio virtual price (for calculating profit)
scaled up by 1e18
*/
uint256 D = getD(_xp(), _A());
// D is in the units similar to DAI (e.g. converted to precision 1e18)
// When balanced, D = n * x_u - total virtual value of the portfolio
uint256 tokenSupply = IPoolToken(token).totalSupply();
return (D * PRECISION) / tokenSupply;
}
/// @notice Simplified method to calculate addition or reduction in token supply at
/// deposit or withdrawal without taking fees into account (but looking at
/// slippage).
/// Needed to prevent front-running, not for precise calculations!
/// @param amounts amount list of each assets
/// @param deposit the flag whether deposit or withdrawal
/// @return the amount of lp tokens
function calcTokenAmount(uint256[] memory amounts, bool deposit) external view override returns (uint256) {
/*
Simplified method to calculate addition or reduction in token supply at
deposit or withdrawal without taking fees into account (but looking at
slippage) .
Needed to prevent front-running, not for precise calculations!
*/
uint256[] memory _balances = _storedBalances;
uint256 amp = _A();
uint256 D0 = getDMem(_balances, amp);
for (uint256 i = 0; i < N_COINS; i++) {
if (deposit) {
_balances[i] += amounts[i];
} else {
_balances[i] -= amounts[i];
}
}
uint256 D1 = getDMem(_balances, amp);
uint256 tokenAmount = IPoolToken(token).totalSupply();
uint256 diff = 0;
if (deposit) {
diff = D1 - D0;
} else {
diff = D0 - D1;
}
return (diff * tokenAmount) / D0;
}
function addLiquidity(uint256[] memory amounts, uint256 minMintAmount) external payable override nonReentrant whenNotPaused returns (uint256) {
require(msg.value == 0);
uint256 amp = _A();
uint256 tokenSupply = IPoolToken(token).totalSupply();
// Initial invariant
uint256 D0 = 0;
uint256[] memory oldBalances = _storedBalances;
if (tokenSupply > 0) {
D0 = getDMem(oldBalances, amp);
}
uint256[] memory newBalances = arrCopy(oldBalances);
for (uint256 i = 0; i < N_COINS; i++) {
uint256 inAmount = amounts[i];
if (tokenSupply == 0) {
require(inAmount > 0); // dev: initial deposit requires all coins
}
address in_coin = coins[i];
// Take coins from the sender
if (inAmount > 0) {
// "safeTransferFrom" which works for KIP7s which return bool or not
rawCall(in_coin, abi.encodeWithSignature("transferFrom(address,address,uint256)", msg.sender, address(this), amounts[i]));
}
newBalances[i] = oldBalances[i] + inAmount;
}
// Invariant after change
uint256 D1 = getDMem(newBalances, amp);
require(D1 > D0);
// We need to recalculate the invariant accounting for fees
// to calculate fair user's share
uint256 D2 = D1;
uint256[] memory fees = new uint256[](N_COINS);
if (tokenSupply > 0) {
// Only account for fees if we are not the first to deposit
uint256 _fee = (fee * N_COINS) / (4 * (N_COINS - 1));
uint256 _adminFee = adminFee;
for (uint256 i = 0; i < N_COINS; i++) {
uint256 idealBalance = (D1 * oldBalances[i]) / D0;
uint256 difference = 0;
if (idealBalance > newBalances[i]) {
difference = idealBalance - newBalances[i];
} else {
difference = newBalances[i] - idealBalance;
}
fees[i] = (_fee * difference) / FEE_DENOMINATOR;
_storedBalances[i] = newBalances[i] - ((fees[i] * _adminFee) / FEE_DENOMINATOR);
newBalances[i] -= fees[i];
}
D2 = getDMem(newBalances, amp);
} else {
_storedBalances = newBalances;
}
// Calculate, how much pool tokens to mint
uint256 mintAmount = 0;
if (tokenSupply == 0) {
mintAmount = D1; // Take the dust if there was any
} else {
mintAmount = (tokenSupply * (D2 - D0)) / D0;
}
require(mintAmount >= minMintAmount, "Slippage screwed you");
// Mint pool tokens
IPoolToken(token).mint(msg.sender, mintAmount);
emit AddLiquidity(msg.sender, amounts, fees, D1, tokenSupply + mintAmount);
return mintAmount;
}
function _getDy(
uint256 i,
uint256 j,
uint256 dx,
bool withoutFee
) internal view override returns (uint256) {
// dx and dy in c-units
uint256[] memory xp = _xp();
uint256 x = xp[i] + ((dx * RATES[i]) / PRECISION);
uint256 y = getY(i, j, x, xp);
uint256 dy = ((xp[j] - y - 1) * PRECISION) / RATES[j];
uint256 _fee = ((withoutFee ? 0 : fee) * dy) / FEE_DENOMINATOR;
return dy - _fee;
}
// reference: https://github.com/curvefi/curve-contract/blob/c6df0cf14b557b11661a474d8d278affd849d3fe/contracts/pools/y/StableSwapY.vy#L351
function _getDx(
uint256 i,
uint256 j,
uint256 dy
) internal view override returns (uint256) {
uint256[] memory xp = _xp();
uint256 y = xp[j] - (((dy * FEE_DENOMINATOR) / (FEE_DENOMINATOR - fee)) * RATES[j]) / PRECISION;
uint256 x = getY(j, i, y, xp);
uint256 dx = ((x - xp[i]) * PRECISION) / RATES[i];
return dx;
}
function _getDyUnderlying(
uint256 i,
uint256 j,
uint256 dx,
bool withoutFee
) internal view override returns (uint256) {
// dx and dy in underlying units
uint256[] memory xp = _xp();
uint256 x = xp[i] + dx * PRECISION_MUL[i];
uint256 y = getY(i, j, x, xp);
uint256 dy = (xp[j] - y - 1) / PRECISION_MUL[j];
uint256 _fee = ((withoutFee ? 0 : fee) * dy) / FEE_DENOMINATOR;
return dy - _fee;
}
function exchange(
uint256 i,
uint256 j,
uint256 dx,
uint256 minDy
) external payable override nonReentrant whenNotPaused returns (uint256) {
require(msg.value == 0);
uint256[] memory oldBalances = _storedBalances;
uint256[] memory xp = _xpMem(oldBalances);
address inputCoin = coins[i];
// "safeTransferFrom" which works for KIP7s which return bool or not
rawCall(inputCoin, abi.encodeWithSignature("transferFrom(address,address,uint256)", msg.sender, address(this), dx));
uint256 x = xp[i] + (dx * RATES[i]) / PRECISION;
uint256 y = getY(i, j, x, xp);
uint256 dy = xp[j] - y - 1; // -1 just in case there were some rounding errors
uint256 dyFee = (dy * fee) / FEE_DENOMINATOR;
// Convert all to real units
dy = ((dy - dyFee) * PRECISION) / RATES[j];
require(dy >= minDy, "Exchange resulted in fewer coins than expected");
uint256 dyAdminFee = (dyFee * adminFee) / FEE_DENOMINATOR;
dyAdminFee = (dyAdminFee * PRECISION) / RATES[j];
// Change balances exactly in same way as we change actual KIP7 coin amounts
_storedBalances[i] = oldBalances[i] + dx;
// When rounding errors happen, we undercharge admin fee in favor of LP
_storedBalances[j] = oldBalances[j] - dy - dyAdminFee;
// "safeTransfer" which works for KIP7s which return bool or not
rawCall(coins[j], abi.encodeWithSignature("transfer(address,uint256)", msg.sender, dy));
emit TokenExchange(msg.sender, i, dx, j, dy, dyFee);
return dy;
}
/// @notice Withdraw coins from the pool
/// @dev Withdrawal amounts are based on current deposit ratios
/// @param _amount Quantity of LP tokens to burn in the withdrawal
/// @param minAmounts Minimum amounts of underlying coins to receive
/// @return List of amounts of coins that were withdrawn
function removeLiquidity(uint256 _amount, uint256[] memory minAmounts) external override nonReentrant returns (uint256[] memory) {
uint256 totalSupply = IPoolToken(token).totalSupply();
uint256[] memory amounts = new uint256[](N_COINS);
uint256[] memory fees = new uint256[](N_COINS); // Fees are unused but we've got them historically in event
for (uint256 i = 0; i < N_COINS; i++) {
uint256 value = (_storedBalances[i] * _amount) / totalSupply;
require(value >= minAmounts[i], "Withdrawal resulted in fewer coins than expected");
_storedBalances[i] -= value;
amounts[i] = value;
// "safeTransfer" which works for KIP7s which return bool or not
rawCall(coins[i], abi.encodeWithSignature("transfer(address,uint256)", msg.sender, value));
}
IPoolToken(token).burn(msg.sender, _amount); // dev: insufficient funds
emit RemoveLiquidity(msg.sender, amounts, fees, totalSupply - _amount);
return amounts;
}
function removeLiquidityImbalance(uint256[] memory amounts, uint256 maxBurnAmount)
external
override
nonReentrant
whenNotPaused
returns (uint256)
{
uint256 tokenSupply = IPoolToken(token).totalSupply();
require(tokenSupply != 0); // dev: zero total supply
uint256 amp = _A();
uint256[] memory oldBalances = _storedBalances;
uint256[] memory newBalances = arrCopy(oldBalances);
uint256 D0 = getDMem(oldBalances, amp);
for (uint256 i = 0; i < N_COINS; i++) {
newBalances[i] -= amounts[i];
}
uint256 D1 = getDMem(newBalances, amp);
uint256[] memory fees = new uint256[](N_COINS);
{
uint256 _fee = (fee * N_COINS) / (4 * (N_COINS - 1));
uint256 _adminFee = adminFee;
for (uint256 i = 0; i < N_COINS; i++) {
uint256 idealBalance = (D1 * oldBalances[i]) / D0;
uint256 difference = 0;
if (idealBalance > newBalances[i]) {
difference = idealBalance - newBalances[i];
} else {
difference = newBalances[i] - idealBalance;
}
fees[i] = (_fee * difference) / FEE_DENOMINATOR;
_storedBalances[i] = newBalances[i] - ((fees[i] * _adminFee) / FEE_DENOMINATOR);
newBalances[i] -= fees[i];
}
}
uint256 D2 = getDMem(newBalances, amp);
uint256 tokenAmount = ((D0 - D2) * tokenSupply) / D0;
require(tokenAmount != 0); // dev: zero tokens burned
tokenAmount += 1; // In case of rounding errors - make it unfavorable for the "attacker"
require(tokenAmount <= maxBurnAmount, "Slippage screwed you");
IPoolToken(token).burn(msg.sender, tokenAmount); // dev: insufficient funds
for (uint256 i = 0; i < N_COINS; i++) {
if (amounts[i] != 0) {
// "safeTransfer" which works for KIP7s which return bool or not
rawCall(coins[i], abi.encodeWithSignature("transfer(address,uint256)", msg.sender, amounts[i]));
}
}
emit RemoveLiquidityImbalance(msg.sender, amounts, fees, D1, tokenSupply - tokenAmount);
return tokenAmount;
}
function _calcWithdrawOneCoin(
uint256 _tokenAmount,
uint256 i,
bool withoutFee
)
internal
view
returns (
uint256,
uint256,
uint256
)
{
// First, need to calculate
// * Get current D
// * Solve Eqn against y_i for D - _tokenAmount
uint256 amp = _A();
uint256 totalSupply = IPoolToken(token).totalSupply();
uint256[] memory xp = _xp();
uint256 D0 = getD(xp, amp);
uint256 D1 = D0 - (_tokenAmount * D0) / totalSupply;
uint256[] memory xpReduced = arrCopy(xp);
uint256 newY = getYD(amp, i, xp, D1);
uint256 dy0 = (xp[i] - newY) / PRECISION_MUL[i]; // w/o fees, precision depends on coin
{
uint256 _fee = ((withoutFee ? 0 : fee) * N_COINS) / (4 * (N_COINS - 1));
for (uint256 j = 0; j < N_COINS; j++) {
uint256 dxExpected = 0;
if (j == i) {
dxExpected = (xp[j] * D1) / D0 - newY;
} else {
dxExpected = xp[j] - (xp[j] * D1) / D0;
// 10**18
}
xpReduced[j] -= (_fee * dxExpected) / FEE_DENOMINATOR;
}
}
uint256 dy = xpReduced[i] - getYD(amp, i, xpReduced, D1);
dy = (dy - 1) / PRECISION_MUL[i]; // Withdraw less to account for rounding errors
return (dy, dy0 - dy, totalSupply);
}
function calcWithdrawOneCoin(uint256 _tokenAmount, uint256 i) external view override returns (uint256) {
(uint256 result, , ) = _calcWithdrawOneCoin(_tokenAmount, i, false);
return result;
}
function calcWithdrawOneCoinWithoutFee(uint256 _tokenAmount, uint256 i) external view override returns (uint256) {
(uint256 result, , ) = _calcWithdrawOneCoin(_tokenAmount, i, true);
return result;
}
function removeLiquidityOneCoin(
uint256 _tokenAmount,
uint256 i,
uint256 minAmount
) external override nonReentrant whenNotPaused returns (uint256) {
/*
Remove _amount of liquidity all in a form of coin i
*/
(uint256 dy, uint256 dyFee, uint256 totalSupply) = _calcWithdrawOneCoin(_tokenAmount, i, false);
require(dy >= minAmount, "Not enough coins removed");
_storedBalances[i] -= (dy + (dyFee * adminFee) / FEE_DENOMINATOR);
IPoolToken(token).burn(msg.sender, _tokenAmount); // dev: insufficient funds
// "safeTransfer" which works for KIP7s which return bool or not
rawCall(coins[i], abi.encodeWithSignature("transfer(address,uint256)", msg.sender, dy));
uint256[] memory amounts = new uint256[](N_COINS);
uint256[] memory fees = new uint256[](N_COINS);
amounts[i] = dy;
fees[i] = dyFee;
emit RemoveLiquidityOne(msg.sender, _tokenAmount, amounts, fees, totalSupply - _tokenAmount);
return dy;
}
function transferOwnership(address newOwner) public override(IStableSwap, StableSwap) onlyOwner {
super.transferOwnership(newOwner);
}
function adminBalances(uint256 i) public view override(IStableSwap, StableSwap) returns (uint256) {
return IKIP7(coins[i]).balanceOf(address(this)) - _storedBalances[i];
}
function withdrawAdminFees(address recipient) external override onlyOperator {
require(recipient != address(0), "StableSwap::withdrawAdminFee: 0 address");
for (uint256 i = 0; i < N_COINS; i++) {
address c = coins[i];
uint256 value = IKIP7(c).balanceOf(address(this)) - _storedBalances[i];
if (value > 0) {
// "safeTransfer" which works for KIP7s which return bool or not
rawCall(c, abi.encodeWithSignature("transfer(address,uint256)", recipient, value));
}
}
}
function donateAdminFees() external override onlyOwner {
for (uint256 i = 0; i < N_COINS; i++) {
_storedBalances[i] = IKIP7(coins[i]).balanceOf(address(this));
}
}
}
| Withdraw less to account for rounding errors
| dy = (dy - 1) / PRECISION_MUL[i]; | 1,022,090 | [
1,
1190,
9446,
5242,
358,
2236,
364,
13885,
1334,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
7732,
273,
261,
15680,
300,
404,
13,
342,
7071,
26913,
67,
49,
1506,
63,
77,
15533,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.6.6;
// SPDX-License-Identifier: MIT
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view 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
/**
* @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
/**
* _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
// SPDX-License-Identifier: MIT
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
/**
* @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;
}
}
// SPDX-License-Identifier: MIT
/**
* @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);
}
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
/***********************************************************************
Modified @openzeppelin/contracts/token/ERC1155/IERC1155.sol
Allow overriding of some methods and use of some variables
in inherited contract.
----------------------------------------------------------------------*/
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external payable;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external payable;
}
// SPDX-License-Identifier: MIT
/***********************************************************************
Modified @openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol
Allow overriding of some methods and use of some variables
in inherited contract.
----------------------------------------------------------------------*/
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
/***********************************************************************
Modified @openzeppelin/contracts/token/ERC1155/ERC1155.sol
Allow overriding of some methods and use of some variables
in inherited contract.
----------------------------------------------------------------------*/
/**
*
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using SafeMath for uint256;
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) internal _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string internal _uri;
/*
* bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
* bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
* bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
*
* => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
* 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
*/
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
/*
* bytes4(keccak256('uri(uint256)')) == 0x0e89341c
*/
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) public {
_setURI(uri_);
// register the supported interfaces to conform to ERC1155 via ERC165
_registerInterface(_INTERFACE_ID_ERC1155);
// register the supported interfaces to conform to ERC1155MetadataURI via ERC165
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) external view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
require(accounts[i] != address(0), "ERC1155: batch balance query for the zero address");
batchBalances[i] = _balances[ids[i]][accounts[i]];
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public payable virtual override {
require(to != address(0), "ERC1155: transfer to the zero address");
require(from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public payable virtual override {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] = _balances[id][account].add(amount);
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
_balances[id][account] = _balances[id][account].sub(amount, "ERC1155: burn amount exceeds balance");
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(amounts[i], "ERC1155: burn amount exceeds balance");
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
library Strings {
// via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol
function strConcat(
string memory _a,
string memory _b,
string memory _c,
string memory _d,
string memory _e
) internal pure returns (string memory) {
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);
uint256 k = 0;
for (uint256 i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (uint256 i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (uint256 i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (uint256 i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (uint256 i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(
string memory _a,
string memory _b,
string memory _c,
string memory _d
) internal pure returns (string memory) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(
string memory _a,
string memory _b,
string memory _c
) internal pure returns (string memory) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string memory _a, string memory _b) internal pure returns (string memory) {
return strConcat(_a, _b, "", "", "");
}
function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
while (_i != 0) {
bstr[k--] = bytes1(uint8(48 + (_i % 10)));
_i /= 10;
}
return string(bstr);
}
}
// SPDX-License-Identifier: MIT
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping(address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// SPDX-License-Identifier: MIT
/**
* @title WhitelistAdminRole
* @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts.
*/
contract WhitelistAdminRole is Context {
using Roles for Roles.Role;
event WhitelistAdminAdded(address indexed account);
event WhitelistAdminRemoved(address indexed account);
Roles.Role private _whitelistAdmins;
constructor() internal {
_addWhitelistAdmin(_msgSender());
}
modifier onlyWhitelistAdmin() {
require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role");
_;
}
function isWhitelistAdmin(address account) public view returns (bool) {
return _whitelistAdmins.has(account);
}
function addWhitelistAdmin(address account) public onlyWhitelistAdmin {
_addWhitelistAdmin(account);
}
function renounceWhitelistAdmin() public {
_removeWhitelistAdmin(_msgSender());
}
function _addWhitelistAdmin(address account) internal {
_whitelistAdmins.add(account);
emit WhitelistAdminAdded(account);
}
function _removeWhitelistAdmin(address account) internal {
_whitelistAdmins.remove(account);
emit WhitelistAdminRemoved(account);
}
}
// SPDX-License-Identifier: MIT
contract ERC1155Residuals is ERC1155, Ownable, WhitelistAdminRole {
using SafeMath for uint256;
using Address for address;
mapping(uint256 => address) public beneficiary;
mapping(uint256 => uint256) public residualsFee;
mapping(uint256 => bool) public residualsRequired;
uint256 public MAX_RESIDUALS = 10000;
event TransferWithResiduals(
address indexed from,
address indexed to,
uint256 id,
uint256 amount,
uint256 value,
uint256 residuals
);
/*
Not required:
? event TransferBatchWithResiduals(
address indexed from,
address indexed to,
uint256[] ids,
uint256[] amounts,
uint256 value
);
*/
event SetBeneficiary(uint256 indexed id, address indexed beneficiary);
event SetResidualsFee(uint256 indexed id, uint256 residualsFee);
event SetResidualsRequired(uint256 indexed id, bool recidualsRequired);
constructor(string memory uri_) public ERC1155(uri_) {}
function removeWhitelistAdmin(address account) public virtual onlyOwner {
_removeWhitelistAdmin(account);
}
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public payable virtual override {
super.safeTransferFrom(from, to, id, amount, data);
if (_msgSender() != from && residualsRequired[id] && beneficiary[id] != address(0)) {
require(msg.value > 0, "ERC1155: residuals payment is required for this NFT");
}
if (msg.value > 0) {
if (beneficiary[id] != address(0)) {
uint256 residualsFeeValue = msg.value.mul(residualsFee[id]).div(MAX_RESIDUALS);
payable(beneficiary[id]).transfer(residualsFeeValue);
payable(from).transfer(msg.value.sub(residualsFeeValue));
// Emit only if residuals applied
emit TransferWithResiduals(from, to, id, amount, msg.value, residualsFeeValue);
} else {
payable(from).transfer(msg.value);
}
}
}
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public payable virtual override {
super.safeBatchTransferFrom(from, to, ids, amounts, data);
if (_msgSender() != from) {
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
require(
!(residualsRequired[id] && beneficiary[id] != address(0)),
Strings.strConcat("ERC1155: residuals payment is required in batch for token ", Strings.uint2str(id))
);
}
}
if (msg.value > 0) {
payable(from).transfer(msg.value);
}
// not ruquired -> emit TransferBatchWithResiduals(from, to, ids, amounts, msg.value);
}
function safeTransferFromWithResiduals(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public payable virtual {
super.safeTransferFrom(from, to, id, amount, data);
if (beneficiary[id] != address(0)) {
payable(beneficiary[id]).transfer(msg.value);
// Emit only if residuals applied
emit TransferWithResiduals(from, to, id, amount, msg.value, msg.value);
} else {
payable(msg.sender).transfer(msg.value);
}
}
function setBeneficiary(uint256 _id, address _beneficiary) public onlyWhitelistAdmin {
beneficiary[_id] = _beneficiary;
emit SetBeneficiary(_id, _beneficiary);
}
function setResidualsFee(uint256 _id, uint256 _residualsFee) public onlyWhitelistAdmin {
require(_residualsFee <= MAX_RESIDUALS, "ERC1155: to high residuals fee");
residualsFee[_id] = _residualsFee;
emit SetResidualsFee(_id, _residualsFee);
}
function setResidualsRequired(uint256 _id, bool _residualsRequired) public onlyWhitelistAdmin {
residualsRequired[_id] = _residualsRequired;
emit SetResidualsRequired(_id, _residualsRequired);
}
}
// SPDX-License-Identifier: MIT
contract MinterRole is Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor() internal {
_addMinter(_msgSender());
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
// SPDX-License-Identifier: MIT
interface IOwnableDelegateProxy {}
// SPDX-License-Identifier: MIT
contract IProxyRegistry {
mapping(address => IOwnableDelegateProxy) public proxies;
}
// SPDX-License-Identifier: MIT
/**
* @title ERC1155Tradable
* ERC1155Tradable - ERC1155 contract that whitelists an operator address,
* has create and mint functionality, and supports useful standards from OpenZeppelin,
like _exists(), name(), symbol(), and totalSupply()
*/
contract ERC1155Tradable is ERC1155Residuals, MinterRole {
using Strings for string;
address proxyRegistryAddress;
uint256 private _currentTokenID = 0;
mapping(uint256 => address) public creators;
mapping(uint256 => uint256) public tokenSupply;
mapping(uint256 => uint256) public tokenMaxSupply;
// Contract name
string public name;
// Contract symbol
string public symbol;
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress,
string memory uri_
) public ERC1155Residuals(uri_) {
name = _name;
symbol = _symbol;
proxyRegistryAddress = _proxyRegistryAddress;
}
function removeWhitelistAdmin(address account) public override onlyOwner {
_removeWhitelistAdmin(account);
}
function removeMinter(address account) public onlyOwner {
_removeMinter(account);
}
function uri(uint256 _id) public view override returns (string memory) {
require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN");
return Strings.strConcat(_uri, Strings.uint2str(_id), ".json");
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(uint256 _id) public view returns (uint256) {
return tokenSupply[_id];
}
/**
* @dev Returns the max quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function maxSupply(uint256 _id) public view returns (uint256) {
return tokenMaxSupply[_id];
}
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function setBaseMetadataURI(string memory _newBaseMetadataURI) public onlyWhitelistAdmin {
_setURI(_newBaseMetadataURI);
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* @param _maxSupply max supply allowed
* @param _initialSupply Optional amount to supply the first owner
* @param _uri Optional URI for this token type
* @param _data Optional data to pass if receiver is contract
* @return tokenId The newly created token ID
*/
function create(
uint256 _maxSupply,
uint256 _initialSupply,
string calldata _uri,
bytes calldata _data,
address _beneficiary,
uint256 _residualsFee,
bool _residualsRequired
) external onlyWhitelistAdmin returns (uint256 tokenId) {
require(_initialSupply <= _maxSupply, "Initial supply cannot be more than max supply");
require(_residualsFee <= MAX_RESIDUALS, "ERC1155Tradable: to high residuals fee");
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
beneficiary[_id] = _beneficiary;
residualsFee[_id] = _residualsFee;
residualsRequired[_id] = _residualsRequired;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
if (_initialSupply != 0) _mint(msg.sender, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
tokenMaxSupply[_id] = _maxSupply;
return _id;
}
/**
* @dev Mints some amount of tokens to an address
* @param _to Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
* @param _data Data to pass if receiver is contract
*/
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) public onlyMinter {
uint256 tokenId = _id;
require(tokenSupply[tokenId] < tokenMaxSupply[tokenId], "Max supply reached");
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] = tokenSupply[_id].add(_quantity);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) {
// Whitelist OpenSea proxy contract for easy trading.
IProxyRegistry proxyRegistry = IProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 _id) internal view returns (bool) {
return creators[_id] != address(0);
}
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
function _getNextTokenID() private view returns (uint256) {
return _currentTokenID.add(1);
}
/**
* @dev increments the value of _currentTokenID
*/
function _incrementTokenTypeId() private {
_currentTokenID++;
}
/**
* @dev Updates token max supply
* @param id_ uint256 ID of the token to update
* @param maxSupply_ uint256 max supply allowed
*/
function updateTokenMaxSupply(uint256 id_, uint256 maxSupply_) external onlyWhitelistAdmin {
require(_exists(id_), "ERC1155Tradable#updateTokenMaxSupply: NONEXISTENT_TOKEN");
require(tokenSupply[id_] <= maxSupply_, "already minted > new maxSupply");
tokenMaxSupply[id_] = maxSupply_;
}
}
// SPDX-License-Identifier: MIT
/**
* @title RareNft
* RareNft - Collect limited edition NFTs from Rare
*/
contract RareNft is ERC1155Tradable {
string public contractURI;
constructor(
string memory _name, //// "Rare Ltd."
string memory _symbol, //// "$RARE"
address _proxyRegistryAddress,
string memory _baseMetadataURI, //// "https://api.rares.com/rares/"
string memory _contractURI //// "https://api.rares.com/contract/rares-erc1155"
) public ERC1155Tradable(_name, _symbol, _proxyRegistryAddress, _baseMetadataURI) {
contractURI = _contractURI;
}
} | * @dev Implementation of the basic standard multi-token. _Available since v3.1._/ Mapping from token ID to account balances Mapping from account to operator approvals Used as the URI for all token types by relying on ID substitution, e.g. https:token-cdn-domain/{id}.json | contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using SafeMath for uint256;
using Address for address;
mapping(uint256 => mapping(address => uint256)) internal _balances;
mapping(address => mapping(address => bool)) private _operatorApprovals;
string internal _uri;
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
}
Modified @openzeppelin/contracts/token/ERC1155/ERC1155.sol
constructor(string memory uri_) public {
_setURI(uri_);
_registerInterface(_INTERFACE_ID_ERC1155);
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
function uri(uint256) external view virtual override returns (string memory) {
return _uri;
}
function balanceOf(address account, uint256 id) public view override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
require(accounts[i] != address(0), "ERC1155: batch balance query for the zero address");
batchBalances[i] = _balances[ids[i]][accounts[i]];
}
return batchBalances;
}
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
require(accounts[i] != address(0), "ERC1155: batch balance query for the zero address");
batchBalances[i] = _balances[ids[i]][accounts[i]];
}
return batchBalances;
}
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public payable virtual override {
require(to != address(0), "ERC1155: transfer to the zero address");
require(from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public payable virtual override {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public payable virtual override {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] = _balances[id][account].add(amount);
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
_balances[id][account] = _balances[id][account].sub(amount, "ERC1155: burn amount exceeds balance");
emit TransferSingle(operator, account, address(0), id, amount);
}
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(amounts[i], "ERC1155: burn amount exceeds balance");
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(amounts[i], "ERC1155: burn amount exceeds balance");
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
) internal virtual {}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
} catch Error(string memory reason) {
} catch {
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
} catch Error(string memory reason) {
} catch {
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
| 13,849,531 | [
1,
13621,
434,
326,
5337,
4529,
3309,
17,
2316,
18,
389,
5268,
3241,
331,
23,
18,
21,
6315,
19,
9408,
628,
1147,
1599,
358,
2236,
324,
26488,
9408,
628,
2236,
358,
3726,
6617,
4524,
10286,
487,
326,
3699,
364,
777,
1147,
1953,
635,
283,
6291,
603,
1599,
12785,
16,
425,
18,
75,
18,
2333,
30,
2316,
17,
20902,
17,
4308,
4938,
350,
5496,
1977,
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,
16351,
4232,
39,
2499,
2539,
353,
1772,
16,
4232,
39,
28275,
16,
467,
654,
39,
2499,
2539,
16,
467,
654,
39,
2499,
2539,
2277,
3098,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
225,
1450,
5267,
364,
1758,
31,
203,
203,
225,
2874,
12,
11890,
5034,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
2713,
389,
70,
26488,
31,
203,
203,
225,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
1426,
3719,
3238,
389,
9497,
12053,
4524,
31,
203,
203,
225,
533,
2713,
389,
1650,
31,
203,
203,
225,
1731,
24,
3238,
5381,
389,
18865,
67,
734,
67,
654,
39,
2499,
2539,
273,
374,
7669,
29,
70,
9599,
69,
5558,
31,
203,
203,
225,
1731,
24,
3238,
5381,
389,
18865,
67,
734,
67,
654,
39,
2499,
2539,
67,
22746,
67,
3098,
273,
374,
92,
20,
73,
6675,
5026,
21,
71,
31,
203,
203,
97,
203,
225,
21154,
632,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
2316,
19,
654,
39,
2499,
2539,
19,
654,
39,
2499,
2539,
18,
18281,
203,
225,
3885,
12,
1080,
3778,
2003,
67,
13,
1071,
288,
203,
565,
389,
542,
3098,
12,
1650,
67,
1769,
203,
203,
565,
389,
4861,
1358,
24899,
18865,
67,
734,
67,
654,
39,
2499,
2539,
1769,
203,
203,
565,
389,
4861,
1358,
24899,
18865,
67,
734,
67,
654,
39,
2499,
2539,
67,
22746,
67,
3098,
1769,
203,
225,
289,
203,
203,
225,
445,
2003,
12,
11890,
5034,
13,
3903,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
565,
2
]
|
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.6.0;
/**
* @dev The Migrations contract is a standard truffle contract that keeps track of which migrations were done on the current network.
* For eDai, we have updated it and added functionality that enables it as well to work as a deployed contract registry.
*/
contract Migrations {
event Registered(bytes32 name, address addr);
uint public lastCompletedMigration;
string public version;
/// @dev Deployed contract to deployment address
mapping(bytes32 => address) public contracts;
/// @dev Contract name iterator
bytes32[] public names;
constructor (string memory version_) public {
version = version_;
}
/// @dev Amount of registered contracts
function length() public virtual view returns (uint) {
return names.length;
}
/// @dev Register a contract name and address
function register(bytes32 name, address addr ) public {
contracts[name] = addr;
names.push(name);
emit Registered(name, addr);
}
/// @dev Register the index of the last completed migration
function setCompleted(uint completed) public {
lastCompletedMigration = completed;
}
/// @dev Copy the index of the last completed migration to a new version of the Migrations contract
function upgrade(address newAddress) public {
Migrations upgraded = Migrations(newAddress);
upgraded.setCompleted(lastCompletedMigration);
}
}
| @dev Amount of registered contracts | function length() public virtual view returns (uint) {
return names.length;
}
| 12,780,834 | [
1,
6275,
434,
4104,
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,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
769,
1435,
1071,
5024,
1476,
1135,
261,
11890,
13,
288,
203,
3639,
327,
1257,
18,
2469,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x1110F204B1586befbC352882f79872Bc2dE147bF/sources/PrivateBet.sol | Etat 'fermé avec gagnant' requis
| require(bt.state == State.Closed_Winner, "ImproperState"); | 9,365,292 | [
1,
41,
88,
270,
296,
586,
81,
132,
107,
279,
8799,
314,
346,
82,
970,
11,
10780,
291,
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,
3639,
2583,
12,
23602,
18,
2019,
422,
3287,
18,
7395,
67,
59,
7872,
16,
315,
1170,
22754,
1119,
8863,
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
]
|
./partial_match/1/0xB4EFd85c19999D84251304bDA99E90B92300Bd93/sources/RocketPoolToken.sol | @dev Returns the token total currently minted by the sale agent @param _salesAgentAddress The address of the token sale agent contract | function getSaleContractTokensMinted(address _salesAgentAddress) constant isSalesContract(_salesAgentAddress) public returns(uint256) {
return salesAgents[_salesAgentAddress].tokensMinted;
}
| 3,729,963 | [
1,
1356,
326,
1147,
2078,
4551,
312,
474,
329,
635,
326,
272,
5349,
4040,
225,
389,
87,
5408,
3630,
1887,
1021,
1758,
434,
326,
1147,
272,
5349,
4040,
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
]
| [
1,
1,
1,
1,
1,
1,
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,
1322,
5349,
8924,
5157,
49,
474,
329,
12,
2867,
389,
87,
5408,
3630,
1887,
13,
5381,
11604,
5408,
8924,
24899,
87,
5408,
3630,
1887,
13,
1071,
1135,
12,
11890,
5034,
13,
288,
203,
3639,
327,
272,
5408,
23400,
63,
67,
87,
5408,
3630,
1887,
8009,
7860,
49,
474,
329,
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
]
|
./partial_match/1/0xCd73e4322Ee1D0a7d01D2A471eBB464dA90454cc/sources/AzuGoal.sol | airdrop to msg.sender | function claimAirDrops(uint256 tokenId) external onlyEOA nonReentrant {
require(ownerOf(tokenId) == msg.sender, "Only owner");
uint8 value = airDrops[uint16(tokenId)];
if (value == 0) revert("no airdrops found");
aces.mint(msg.sender, value);
airDrops[uint16(tokenId)] = 0;
emit airDropped(msg.sender, tokenId, value);
}
| 4,434,940 | [
1,
1826,
7285,
358,
1234,
18,
15330,
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,
445,
7516,
29752,
40,
16703,
12,
11890,
5034,
1147,
548,
13,
3903,
1338,
41,
28202,
1661,
426,
8230,
970,
288,
203,
3639,
2583,
12,
8443,
951,
12,
2316,
548,
13,
422,
1234,
18,
15330,
16,
315,
3386,
3410,
8863,
203,
3639,
2254,
28,
460,
273,
23350,
40,
16703,
63,
11890,
2313,
12,
2316,
548,
13,
15533,
203,
203,
3639,
309,
261,
1132,
422,
374,
13,
15226,
2932,
2135,
279,
6909,
16703,
1392,
8863,
203,
203,
3639,
279,
764,
18,
81,
474,
12,
3576,
18,
15330,
16,
460,
1769,
203,
3639,
23350,
40,
16703,
63,
11890,
2313,
12,
2316,
548,
25887,
273,
374,
31,
203,
3639,
3626,
23350,
23683,
12,
3576,
18,
15330,
16,
1147,
548,
16,
460,
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
]
|
./full_match/4/0xC7AC8Df0116Aaf785A384EFDCff80a3D4238686F/sources/browser/TickerERC20.sol | * @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 onlyAdminTransfer virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
| 13,341,984 | [
1,
2729,
1375,
8949,
68,
2430,
471,
22698,
2182,
358,
1375,
4631,
9191,
21006,
326,
2078,
14467,
18,
7377,
1282,
279,
288,
5912,
97,
871,
598,
1375,
2080,
68,
444,
358,
326,
3634,
1758,
18,
29076,
300,
1375,
869,
68,
2780,
506,
326,
3634,
1758,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
81,
474,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
2713,
1338,
4446,
5912,
5024,
288,
203,
3639,
2583,
12,
4631,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
312,
474,
358,
326,
3634,
1758,
8863,
203,
203,
3639,
389,
5771,
1345,
5912,
12,
2867,
12,
20,
3631,
2236,
16,
3844,
1769,
203,
203,
3639,
389,
4963,
3088,
1283,
273,
389,
4963,
3088,
1283,
18,
1289,
12,
8949,
1769,
203,
3639,
389,
70,
26488,
63,
4631,
65,
273,
389,
70,
26488,
63,
4631,
8009,
1289,
12,
8949,
1769,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
2236,
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
]
|
/**
*Submitted for verification at Etherscan.io on 2020-11-15
*/
// File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/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.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-ethereum-package/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 OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// File: @openzeppelin/contracts-ethereum-package/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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts-ethereum-package/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: @nomiclabs/buidler/console.sol
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.8.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 logByte(byte p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(byte)", 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: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol
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: contracts/FeeApprover.sol
pragma solidity ^0.6.0;
contract FeeApprover is OwnableUpgradeSafe {
using SafeMath for uint256;
function initialize(
address _COREAddress,
address _WETHAddress,
address _uniswapFactory
) public initializer {
OwnableUpgradeSafe.__Ownable_init();
coreTokenAddress = _COREAddress;
WETHAddress = _WETHAddress;
tokenUniswapPair = IUniswapV2Factory(_uniswapFactory).getPair(WETHAddress,coreTokenAddress);
feePercentX100 = 10;
paused = true; // We start paused until sync post LGE happens.
//_editNoFeeList(0xC5cacb708425961594B63eC171f4df27a9c0d8c9, true); // corevault proxy
_editNoFeeList(tokenUniswapPair, true);
sync();
minFinney = 5000;
}
address tokenUniswapPair;
IUniswapV2Factory public uniswapFactory;
address internal WETHAddress;
address coreTokenAddress;
address coreVaultAddress;
uint8 public feePercentX100; // max 255 = 25.5% artificial clamp
uint256 public lastTotalSupplyOfLPTokens;
bool paused;
uint256 private lastSupplyOfCoreInPair;
uint256 private lastSupplyOfWETHInPair;
mapping (address => bool) public noFeeList;
// CORE token is pausable
function setPaused(bool _pause) public onlyOwner {
paused = _pause;
sync();
}
function setFeeMultiplier(uint8 _feeMultiplier) public onlyOwner {
feePercentX100 = _feeMultiplier;
}
function setCoreVaultAddress(address _coreVaultAddress) public onlyOwner {
coreVaultAddress = _coreVaultAddress;
noFeeList[coreVaultAddress] = true;
}
function editNoFeeList(address _address, bool noFee) public onlyOwner {
_editNoFeeList(_address,noFee);
}
function _editNoFeeList(address _address, bool noFee) internal{
noFeeList[_address] = noFee;
}
uint minFinney; // 2x for $ liq amount
function setMinimumLiquidityToTriggerStop(uint finneyAmnt) public onlyOwner{ // 1000 = 1eth
minFinney = finneyAmnt;
}
function sync() public returns (bool lastIsMint, bool lpTokenBurn) {
// This will update the state of lastIsMint, when called publically
// So we have to sync it before to the last LP token value.
uint256 _LPSupplyOfPairTotal = IERC20(tokenUniswapPair).totalSupply();
lpTokenBurn = lastTotalSupplyOfLPTokens > _LPSupplyOfPairTotal;
lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal;
uint256 _balanceWETH = IERC20(WETHAddress).balanceOf(tokenUniswapPair);
uint256 _balanceCORE = IERC20(coreTokenAddress).balanceOf(tokenUniswapPair);
// Do not block after small liq additions
// you can only withdraw 350$ now with front running
// And cant front run buys with liq add ( adversary drain )
//lastIsMint = _balanceCORE > lastSupplyOfCoreInPair && _balanceWETH > lastSupplyOfWETHInPair.add(minFinney.mul(1 finney));
lastIsMint = _balanceCORE > lastSupplyOfCoreInPair && _balanceWETH > lastSupplyOfWETHInPair;
lastSupplyOfCoreInPair = _balanceCORE;
lastSupplyOfWETHInPair = _balanceWETH;
}
function calculateAmountsAfterFee(
address sender,
address recipient, // unusued maybe use din future
uint256 amount
) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount)
{
require(paused == false, "FEE APPROVER: Transfers Paused");
(bool lastIsMint, bool lpTokenBurn) = sync();
if(sender == tokenUniswapPair) {
// This will block buys that are immidietly after a mint. Before sync is called/
// Deployment of this should only happen after router deployment
// And addition of sync to all CoreVault transactions to remove 99.99% of the cases.
require(lastIsMint == false, "Liquidity withdrawals forbidden");
require(lpTokenBurn == false, "Liquidity withdrawals forbidden");
}
if(noFeeList[sender]) { // Dont have a fee when corevault is sending, or infinite loop
console.log("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it)
transferToFeeDistributorAmount = 0;
transferToAmount = amount;
}
else {
console.log("Normal fee transfer");
transferToFeeDistributorAmount = amount.mul(feePercentX100).div(1000);
transferToAmount = amount.sub(transferToFeeDistributorAmount);
}
}
} | _editNoFeeList(0xC5cacb708425961594B63eC171f4df27a9c0d8c9, true); corevault proxy | ) public initializer {
OwnableUpgradeSafe.__Ownable_init();
coreTokenAddress = _COREAddress;
WETHAddress = _WETHAddress;
tokenUniswapPair = IUniswapV2Factory(_uniswapFactory).getPair(WETHAddress,coreTokenAddress);
feePercentX100 = 10;
_editNoFeeList(tokenUniswapPair, true);
sync();
minFinney = 5000;
}
address tokenUniswapPair;
IUniswapV2Factory public uniswapFactory;
address internal WETHAddress;
address coreTokenAddress;
address coreVaultAddress;
uint256 public lastTotalSupplyOfLPTokens;
bool paused;
uint256 private lastSupplyOfCoreInPair;
uint256 private lastSupplyOfWETHInPair;
mapping (address => bool) public noFeeList;
| 7,749,475 | [
1,
67,
4619,
2279,
14667,
682,
12,
20,
14626,
25,
71,
1077,
70,
7301,
5193,
2947,
10525,
3600,
11290,
38,
4449,
73,
39,
4033,
21,
74,
24,
2180,
5324,
69,
29,
71,
20,
72,
28,
71,
29,
16,
638,
1769,
225,
15152,
3714,
2889,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
262,
1071,
12562,
288,
203,
3639,
14223,
6914,
10784,
9890,
16186,
5460,
429,
67,
2738,
5621,
203,
3639,
2922,
1345,
1887,
273,
389,
15715,
1887,
31,
203,
3639,
678,
1584,
44,
1887,
273,
389,
59,
1584,
44,
1887,
31,
203,
3639,
1147,
984,
291,
91,
438,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
1733,
2934,
588,
4154,
12,
59,
1584,
44,
1887,
16,
3644,
1345,
1887,
1769,
203,
3639,
14036,
8410,
60,
6625,
273,
1728,
31,
203,
3639,
389,
4619,
2279,
14667,
682,
12,
2316,
984,
291,
91,
438,
4154,
16,
638,
1769,
203,
3639,
3792,
5621,
203,
3639,
1131,
6187,
82,
402,
273,
20190,
31,
203,
565,
289,
203,
203,
203,
565,
1758,
1147,
984,
291,
91,
438,
4154,
31,
203,
565,
467,
984,
291,
91,
438,
58,
22,
1733,
1071,
640,
291,
91,
438,
1733,
31,
203,
565,
1758,
2713,
678,
1584,
44,
1887,
31,
203,
565,
1758,
2922,
1345,
1887,
31,
203,
565,
1758,
2922,
12003,
1887,
31,
203,
565,
2254,
5034,
1071,
1142,
5269,
3088,
1283,
951,
48,
1856,
3573,
31,
203,
565,
1426,
17781,
31,
203,
565,
2254,
5034,
3238,
1142,
3088,
1283,
951,
4670,
382,
4154,
31,
203,
565,
2254,
5034,
3238,
1142,
3088,
1283,
951,
59,
1584,
44,
382,
4154,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
1071,
1158,
14667,
682,
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
]
|
/**
*Submitted for verification at Etherscan.io on 2021-09-27
*/
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
contract MerkleHashStorage {
struct MerkleHashData {
bytes32 hash;
uint256 block_timestamp;
}
address public contrat_owner;
mapping (bytes9 => MerkleHashData) public merkleHashDataArray;
/* events */
/* ------ */
event MerkleHashAdded(bytes9 indexed merkle_ref, bytes32 merkle_hash, uint256 block_timestamp);
/* end events */
/* ---------- */
constructor() {
contrat_owner = msg.sender;
}
/* external functions */
/* ------------------ */
function addMerkleHashData(bytes9 merkle_ref, bytes32 merkle_hash) external {
require(merkle_ref != 0, "merkle_ref must be > 0");
require(merkle_hash != 0, "merkle_hash must be > 0");
require(msg.sender == contrat_owner, "only contract owner can call addMerkleHashData");
/* check if merkle_hash has been already added for this merkle_ref */
require(merkleHashDataArray[merkle_ref].hash == 0, "merkle_hash has been already added for this merkle_ref");
/* add new merkleHashData into merkleHashDataArray */
merkleHashDataArray[merkle_ref] = MerkleHashData(merkle_hash, block.timestamp);
emit MerkleHashAdded(merkle_ref, merkle_hash, block.timestamp);
}
/* end external functions */
/* ---------------------- */
/* external view function */
/* ---------------------- */
function getMerkleHashData(bytes9 merkle_ref) external view returns (MerkleHashData memory) {
require(merkle_ref != 0, "merkle_ref must be > 0");
MerkleHashData memory merkleHashData = merkleHashDataArray[merkle_ref];
if (merkleHashData.hash == 0)
return MerkleHashData(0, 0);
return merkleHashData;
}
/* end external view function */
/* -------------------------- */
} | events */ ------ */ | event MerkleHashAdded(bytes9 indexed merkle_ref, bytes32 merkle_hash, uint256 block_timestamp);
| 2,418,425 | [
1,
5989,
342,
31913,
342,
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,
202,
2575,
31827,
2310,
8602,
12,
3890,
29,
8808,
30235,
67,
1734,
16,
1731,
1578,
30235,
67,
2816,
16,
2254,
5034,
1203,
67,
5508,
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
]
|
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity 0.8.4;
import "./mixins/OZ/ERC721Upgradeable.sol";
import "./mixins/roles/WethioAdminRole.sol";
import "./mixins/roles/WethioOperatorRole.sol";
import "./mixins/WethioMarketNode.sol";
import "./mixins/WethioTreasuryNode.sol";
import "./mixins/NFT721Metadata.sol";
import "./mixins/NFT721Mint.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
/**
* @title Wethio NFTs implemented using the ERC-721 standard.
* @dev This top level file holds no data directly to ease future upgrades.
*/
contract WethioNFT is
WethioTreasuryNode,
WethioAdminRole,
WethioOperatorRole,
ERC721Upgradeable,
WethioMarketNode,
NFT721Metadata,
NFT721Mint,
OwnableUpgradeable
{
/**
* @notice Called once to configure the contract after the initial deployment.
* @dev This farms the initialize call out to inherited contracts as needed.
*/
function initialize(
address treasury,
address market,
string memory name,
string memory symbol,
string memory baseURI
) public initializer {
WethioTreasuryNode._initializeWethioTreasuryNode(treasury);
WethioMarketNode._initializeWethioMarketNode(market);
ERC721Upgradeable.__ERC721_init(name, symbol);
NFT721Mint._initializeNFT721Mint();
_updateBaseURI(baseURI);
__Ownable_init();
}
/**
* @notice Allows a Wethio admin to update NFT config variables.
* @dev This must be called right after the initial call to `initialize`.
*/
function adminUpdateConfig(
string memory _baseURI,
address market,
address treasury
) external onlyWethioAdmin {
_updateBaseURI(_baseURI);
_updateWethioMarket(market);
_updateWethioTreasury(treasury);
}
/**
* @dev This is a no-op, just an explicit override to address compile errors due to inheritance.
*/
function _burn(uint256 tokenId)
internal
virtual
override(ERC721Upgradeable, NFT721Metadata, NFT721Mint)
{
super._burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
// solhint-disable
/**
* Copied from the OpenZeppelin repository in order to make `_tokenURIs` internal instead of private.
*/
pragma solidity 0.8.4;
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165StorageUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableMapUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Upgradeable is
Initializable,
ContextUpgradeable,
ERC165StorageUpgradeable,
IERC721Upgradeable,
IERC721MetadataUpgradeable,
IERC721EnumerableUpgradeable
{
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap;
using StringsUpgradeable for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping(address => EnumerableSetUpgradeable.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMapUpgradeable.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) internal _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_)
internal
initializer
{
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_)
internal
initializer
{
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(
owner != address(0),
"ERC721: balance query for the zero address"
);
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return
_tokenOwners.get(
tokenId,
"ERC721: owner query for nonexistent token"
);
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
// If there is no base URI, return the token URI.
if (bytes(_baseURI).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(_baseURI, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
override
returns (uint256)
{
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = 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
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
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 returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
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 Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
);
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal
virtual
{
require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(
abi.encodeWithSelector(
IERC721ReceiverUpgradeable(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
),
"ERC721: transfer to non ERC721Receiver implementer"
);
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[41] private __gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity 0.8.4;
import "../../interfaces/IAdminRole.sol";
import "../WethioTreasuryNode.sol";
/**
* @notice Allows a contract to leverage the admin role defined by the Wethio treasury.
*/
abstract contract WethioAdminRole is WethioTreasuryNode {
// This file uses 0 data slots (other than what's included via WethioTreasuryNode)
modifier onlyWethioAdmin() {
require(
_isWethioAdmin(),
"WethioAdminRole: caller does not have the Admin role"
);
_;
}
function _isWethioAdmin() internal view returns (bool) {
return IAdminRole(getWethioTreasury()).isAdmin(msg.sender);
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity 0.8.4;
import "../../interfaces/IOperatorRole.sol";
import "../WethioTreasuryNode.sol";
/**
* @notice Allows a contract to leverage the operator role defined by the Wethio treasury.
*/
abstract contract WethioOperatorRole is WethioTreasuryNode {
// This file uses 0 data slots (other than what's included via WethioTreasuryNode)
function _isWethioOperator() internal view returns (bool) {
return IOperatorRole(getWethioTreasury()).isOperator(msg.sender);
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity 0.8.4;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
/**
* @notice A mixin that stores a reference to the Wethio market contract.
*/
abstract contract WethioMarketNode is Initializable {
using AddressUpgradeable for address;
address private market;
/**
* @dev Called once after the initial deployment to set the Wethio treasury address.
*/
function _initializeWethioMarketNode(address _market) internal initializer {
require(
_market.isContract(),
"Wethio MarketNode: Address is not a contract"
);
market = _market;
}
/**
* @notice Returns the address of the Wethio market.
*/
function getWethioMarket() public view returns (address) {
return market;
}
/**
* @notice Updates the address of the Wethio treasury.
*/
function _updateWethioMarket(address _market) internal {
require(
_market.isContract(),
"Wethio MarketNode: Address is not a contract"
);
market = _market;
}
uint256[1000] private __gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity 0.8.4;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
/**
* @notice A mixin that stores a reference to the Wethio treasury contract.
*/
abstract contract WethioTreasuryNode is Initializable {
using AddressUpgradeable for address;
address private treasury;
/**
* @dev Called once after the initial deployment to set the Wethio treasury address.
*/
function _initializeWethioTreasuryNode(address _treasury)
internal
initializer
{
require(
_treasury.isContract(),
"WethioTreasuryNode: Address is not a contract"
);
treasury = _treasury;
}
/**
* @notice Returns the address of the Wethio treasury.
*/
function getWethioTreasury() public view returns (address) {
return treasury;
}
/**
* @notice Updates the address of the Wethio treasury.
*/
function _updateWethioTreasury(address _treasury) internal {
require(
_treasury.isContract(),
"WethioTreasuryNode: Address is not a contract"
);
treasury = _treasury;
}
uint256[1000] private __gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity 0.8.4;
import "./OZ/ERC721Upgradeable.sol";
import "./roles/WethioAdminRole.sol";
/**
* @notice A mixin to extend the OpenZeppelin metadata implementation.
*/
abstract contract NFT721Metadata is WethioAdminRole, ERC721Upgradeable {
using StringsUpgradeable for uint256;
/**
* @dev Stores hashes minted by a creator to prevent duplicates.
*/
mapping(address => mapping(string => bool))
private creatorToIPFSHashToMinted;
event BaseURIUpdated(string baseURI);
event TokenUriUpdated(
uint256 indexed tokenId,
string indexed indexedTokenUri,
string tokenPath
);
modifier onlyCreatorAndOwner(uint256 tokenId) {
require(
ownerOf(tokenId) == msg.sender || _isWethioAdmin(),
"NFT721Creator: Caller does not own the NFT or not the admin"
);
_;
}
/**
* @notice Checks if the creator has already minted a given NFT.
*/
function getHasCreatorMintedTokenUri(
address creator,
string memory tokenUri
) external view returns (bool) {
return creatorToIPFSHashToMinted[creator][tokenUri];
}
/**
* @notice Sets the token uri.
*/
function _setTokenUriPath(uint256 tokenId, string memory _tokenIPFSPath)
internal
{
require(
bytes(_tokenIPFSPath).length >= 46,
"NFT721Metadata: Invalid IPFS path"
);
require(
!creatorToIPFSHashToMinted[msg.sender][_tokenIPFSPath],
"NFT721Metadata: NFT was already minted"
);
creatorToIPFSHashToMinted[msg.sender][_tokenIPFSPath] = true;
_setTokenURI(tokenId, _tokenIPFSPath);
}
function _updateBaseURI(string memory _baseURI) internal {
_setBaseURI(_baseURI);
emit BaseURIUpdated(_baseURI);
}
/**
* @notice Allows the creator to burn if they currently own the NFT.
*/
function burn(uint256 tokenId) public onlyCreatorAndOwner(tokenId) {
_burn(tokenId);
}
/**
* @dev Remove the record when burned.
*/
function _burn(uint256 tokenId) internal virtual override {
delete creatorToIPFSHashToMinted[msg.sender][_tokenURIs[tokenId]];
super._burn(tokenId);
}
uint256[1000] private __gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity 0.8.4;
import "./OZ/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "./WethioMarketNode.sol";
import "./NFT721Metadata.sol";
import "./roles/WethioAdminRole.sol";
/**
* @notice Allows creators to mint NFTs.
*/
abstract contract NFT721Mint is
WethioAdminRole,
ERC721Upgradeable,
WethioMarketNode,
NFT721Metadata
{
using AddressUpgradeable for address;
uint256 private nextTokenId;
event Minted(
address indexed creator,
uint256 indexed tokenId,
string tokenUri
);
/**
* @notice Gets the tokenId of the next NFT minted.
*/
function getNextTokenId() public view returns (uint256) {
return nextTokenId;
}
/**
* @dev Called once after the initial deployment to set the initial tokenId.
*/
function _initializeNFT721Mint() internal initializer {
// Use ID 1 for the first NFT tokenId
nextTokenId = 0;
}
/**
* @notice Allows a creator to mint an NFT.
*/
function mintAndApproveMarket(string memory tokenPath)
public
returns (uint256 tokenId)
{
tokenId = nextTokenId++;
_mint(address(msg.sender), tokenId);
_setTokenUriPath(tokenId, tokenPath);
setApprovalForAll(getWethioMarket(), true);
emit Minted(msg.sender, tokenId, tokenPath);
}
/**
* @dev Explicit override to address compile errors.
*/
function _burn(uint256 tokenId)
internal
virtual
override(ERC721Upgradeable, NFT721Metadata)
{
super._burn(tokenId);
}
uint256[1000] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @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 (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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165Storage.sol)
pragma solidity ^0.8.0;
import "./ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Storage based implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165StorageUpgradeable is Initializable, ERC165Upgradeable {
function __ERC165Storage_init() internal onlyInitializing {
__ERC165_init_unchained();
__ERC165Storage_init_unchained();
}
function __ERC165Storage_init_unchained() internal onlyInitializing {
}
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return super.supportsInterface(interfaceId) || _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
uint256[49] private __gap;
}
// 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 SafeMathUpgradeable {
/**
* @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/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableMap.sol)
pragma solidity ^0.8.0;
import "./EnumerableSetUpgradeable.sol";
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMapUpgradeable {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.Bytes32Set;
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct Map {
// Storage of keys
EnumerableSetUpgradeable.Bytes32Set _keys;
mapping(bytes32 => bytes32) _values;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
map._values[key] = value;
return map._keys.add(key);
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
delete map._values[key];
return map._keys.remove(key);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._keys.contains(key);
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._keys.length();
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
bytes32 key = map._keys.at(index);
return (key, map._values[key]);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
bytes32 value = map._values[key];
if (value == bytes32(0)) {
return (_contains(map, key), bytes32(0));
} else {
return (true, value);
}
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key");
return value;
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), errorMessage);
return value;
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
UintToAddressMap storage map,
uint256 key,
address value
) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
UintToAddressMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
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;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity 0.8.4;
/**
* @notice Interface for AdminRole which wraps the default admin role from
* OpenZeppelin's AccessControl for easy integration.
*/
interface IAdminRole {
function isAdmin(address account) external view returns (bool);
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity 0.8.4;
/**
* @notice Interface for OperatorRole which wraps a role from
* OpenZeppelin's AccessControl for easy integration.
*/
interface IOperatorRole {
function isOperator(address account) external view returns (bool);
} | * @notice Sets the token uri./ | function _setTokenUriPath(uint256 tokenId, string memory _tokenIPFSPath)
internal
{
require(
bytes(_tokenIPFSPath).length >= 46,
"NFT721Metadata: Invalid IPFS path"
);
require(
!creatorToIPFSHashToMinted[msg.sender][_tokenIPFSPath],
"NFT721Metadata: NFT was already minted"
);
creatorToIPFSHashToMinted[msg.sender][_tokenIPFSPath] = true;
_setTokenURI(tokenId, _tokenIPFSPath);
}
| 268,787 | [
1,
2785,
326,
1147,
2003,
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,
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,
445,
389,
542,
1345,
3006,
743,
12,
11890,
5034,
1147,
548,
16,
533,
3778,
389,
2316,
2579,
4931,
743,
13,
203,
3639,
2713,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
1731,
24899,
2316,
2579,
4931,
743,
2934,
2469,
1545,
17077,
16,
203,
5411,
315,
50,
4464,
27,
5340,
2277,
30,
1962,
2971,
4931,
589,
6,
203,
3639,
11272,
203,
203,
3639,
2583,
12,
203,
5411,
401,
20394,
774,
2579,
4931,
2310,
774,
49,
474,
329,
63,
3576,
18,
15330,
6362,
67,
2316,
2579,
4931,
743,
6487,
203,
5411,
315,
50,
4464,
27,
5340,
2277,
30,
423,
4464,
1703,
1818,
312,
474,
329,
6,
203,
3639,
11272,
203,
203,
3639,
11784,
774,
2579,
4931,
2310,
774,
49,
474,
329,
63,
3576,
18,
15330,
6362,
67,
2316,
2579,
4931,
743,
65,
273,
638,
31,
203,
3639,
389,
542,
1345,
3098,
12,
2316,
548,
16,
389,
2316,
2579,
4931,
743,
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
]
|
./partial_match/3/0x83A969cB59ADdF7fB277C2f66117E6B7bDbd70B0/sources/TokenSale.sol | 2020-12-12 10:00 UTC
| uint256 public closingTime = 1608543645; | 5,332,822 | [
1,
18212,
20,
17,
2138,
17,
2138,
1728,
30,
713,
9951,
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,
5034,
1071,
225,
7647,
950,
273,
2872,
6840,
6564,
23,
1105,
25,
31,
1171,
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/295/0x0000000000000000000000000000000000233233/sources/HederaResponseCodes.sol | An operation was assigned to more than one throttle group in a given bucket
| int32 internal constant OPERATION_REPEATED_IN_BUCKET_GROUPS = 215; | 4,664,315 | [
1,
979,
1674,
1703,
6958,
358,
1898,
2353,
1245,
18304,
1041,
316,
279,
864,
2783,
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,
509,
1578,
2713,
5381,
31294,
67,
862,
1423,
6344,
67,
706,
67,
28888,
67,
28977,
273,
576,
3600,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*******************************************************************************
*
* Copyright (c) 2018-2022 Modenero Corp.
* Released under the MIT License.
*
* ServiceName - Service description.
*
* Version YY.MM.DD
*
* https://modenero.com
* [email protected]
*/
/*******************************************************************************
*
* SafeMath
*/
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
/*******************************************************************************
*
* ECRecovery
*
* Contract function to validate signature of pre-approved token transfers.
* (borrowed from LavaWallet)
*/
interface ECRecovery {
function recover(bytes32 hash, bytes memory sig) external pure returns (address);
}
/*******************************************************************************
*
* ERC Token Standard #20 Interface
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
*/
interface ERC20Interface {
function totalSupply() external view returns (uint);
function balanceOf(address tokenOwner) external view returns (uint balance);
function allowance(address tokenOwner, address spender) external view returns (uint remaining);
function transfer(address to, uint tokens) external returns (bool success);
function approve(address spender, uint tokens) external returns (bool success);
function transferFrom(address from, address to, uint tokens) external returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
/*******************************************************************************
*
* ApproveAndCallFallBack
*
* Contract function to receive approval and execute function in one call
* (borrowed from MiniMeToken)
*/
interface ApproveAndCallFallBack {
function approveAndCall(address spender, uint tokens, bytes memory data) external;
function receiveApproval(address from, uint256 tokens, address token, bytes memory data) external;
}
/*******************************************************************************
*
* Owned contract
*/
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() {
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);
}
}
/*******************************************************************************
*
* ModeneroDb Interface
*/
interface ModeneroDbInterface {
/* Interface getters. */
function getAddress(bytes32 _key) external view returns (address);
function getBool(bytes32 _key) external view returns (bool);
function getBytes(bytes32 _key) external view returns (bytes memory);
function getInt(bytes32 _key) external view returns (int);
function getString(bytes32 _key) external view returns (string memory);
function getUint(bytes32 _key) external view returns (uint);
/* Interface setters. */
function setAddress(bytes32 _key, address _value) external;
function setBool(bytes32 _key, bool _value) external;
function setBytes(bytes32 _key, bytes calldata _value) external;
function setInt(bytes32 _key, int _value) external;
function setString(bytes32 _key, string calldata _value) external;
function setUint(bytes32 _key, uint _value) external;
/* Interface deletes. */
function deleteAddress(bytes32 _key) external;
function deleteBool(bytes32 _key) external;
function deleteBytes(bytes32 _key) external;
function deleteInt(bytes32 _key) external;
function deleteString(bytes32 _key) external;
function deleteUint(bytes32 _key) external;
}
/*******************************************************************************
*
* @notice Service Name
*
* @dev Developer details.
*/
contract ServiceName is Owned {
using SafeMath for uint;
/* Initialize predecessor contract. */
address private _predecessor;
/* Initialize successor contract. */
address private _successor;
/* Initialize revision number. */
uint private _revision;
/* Initialize Modenero Db contract. */
ModeneroDbInterface private _modeneroDb;
/**
* @dev
*
* Set Namespace
*
* Provides a "unique" name for generating "unique" data identifiers,
* most commonly used as database "key-value" keys.
*
* NOTE: Use of `namespace` is REQUIRED when generating ANY & ALL
* ModeneroDb keys; in order to prevent ANY accidental or
* malicious SQL-injection vulnerabilities / attacks.
*/
string private _namespace = 'SERVICE_NAME_HERE';
event Broadcast(
address indexed primary,
address secondary,
bytes data
);
/***************************************************************************
*
* Constructor
*/
constructor() {
/* Initialize ModeneroDb (eternal) storage database contract. */
// NOTE We hard-code the address here, since it should never change.
// _modeneroDb = ModeneroDbInterface(0x68133E0A4996D0103c2135dcD8E2084450DF66D5); // Avalanche | AVAX
// _modeneroDb = ModeneroDbInterface(0x7AaCEC83e10D8F8DfDfaa4858d55b0cC29eE4795); // Binance Smart Chain | BSC
// _modeneroDb = ModeneroDbInterface(0x0B79d476DaC963Bf4D342233AB129Ab833077627); // Ethereum | ETH
// _modeneroDb = ModeneroDbInterface(0x7AaCEC83e10D8F8DfDfaa4858d55b0cC29eE4795); // Fantom | FTM
// _modeneroDb = ModeneroDbInterface(0xeF54AE01D55ADeCac852cBe3e6F16b0D1bf38dE0); // Polygon | MATIC
/* Initialize (aname) hash. */
bytes32 hash = keccak256(abi.encodePacked('aname.', _namespace));
/* Set predecessor address. */
_predecessor = _modeneroDb.getAddress(hash);
/* Verify predecessor address. */
if (_predecessor != address(0x0)) {
/* Make address payable. */
address payable predecessor = payable(address(uint160(_predecessor)));
/* Retrieve the last revision number (if available). */
uint lastRevision = ServiceName(predecessor).getRevision();
/* Set (current) revision number. */
_revision = lastRevision + 1;
}
}
/**
* @dev Only allow access to an authorized Modenero administrator.
*/
modifier onlyAuthByModenero() {
/* Verify write access is only permitted to authorized accounts. */
require(_modeneroDb.getBool(keccak256(
abi.encodePacked(msg.sender, '.has.auth.for.', _namespace))) == true);
_; // function code is inserted here
}
/**
* THIS CONTRACT DOES NOT ACCEPT DIRECT PAYMENTS
*/
fallback () external payable {
/* Cancel this transaction. */
revert('Oops! Direct payments are NOT permitted here.');
}
receive () external payable {
/* Cancel this transaction. */
revert('Oops! Direct payments are NOT permitted here.');
}
/***************************************************************************
*
* ACTIONS
*
*/
function firstAction() public pure returns(bool) {
// TODO
/* Return success. */
return true;
}
/***************************************************************************
*
* GETTERS
*
*/
/**
* Get Revision (Number)
*/
function getRevision() public view returns (uint) {
return _revision;
}
/**
* Get Predecessor (Address)
*/
function getPredecessor() public view returns (address) {
return _predecessor;
}
/**
* Get Successor (Address)
*/
function getSuccessor() public view returns (address) {
return _successor;
}
/***************************************************************************
*
* SETTERS
*
*/
/**
* Set Successor
*
* This is the contract address that replaced this current instnace.
*/
function setSuccessor(
address _newSuccessor
) onlyAuthByModenero external returns (bool success) {
/* Set successor contract. */
_successor = _newSuccessor;
/* Return success. */
return true;
}
/***************************************************************************
*
* INTERFACES
*
*/
/**
* Supports Interface (EIP-165)
*
* (see: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md)
*
* NOTE: Must support the following conditions:
* 1. (true) when interfaceID is 0x01ffc9a7 (EIP165 interface)
* 2. (false) when interfaceID is 0xffffffff
* 3. (true) for any other interfaceID this contract implements
* 4. (false) for any other interfaceID
*/
function supportsInterface(
bytes4 _interfaceID
) external pure returns (bool) {
/* Initialize constants. */
bytes4 InvalidId = 0xffffffff;
bytes4 ERC165Id = 0x01ffc9a7;
/* Validate condition #2. */
if (_interfaceID == InvalidId) {
return false;
}
/* Validate condition #1. */
if (_interfaceID == ERC165Id) {
return true;
}
// TODO Add additional interfaces here.
/* Return false (for condition #4). */
return false;
}
/**
* ECRecovery Interface
*/
function _ecRecovery() private view returns (
ECRecovery ecrecovery
) {
/* Initialize hash. */
bytes32 hash = keccak256('aname.ecrecovery');
/* Retrieve value from Modenero Db. */
address aname = _modeneroDb.getAddress(hash);
/* Initialize interface. */
ecrecovery = ECRecovery(aname);
}
/***************************************************************************
*
* UTILITIES
*
*/
/**
* Is (Owner) Contract
*
* Tests if a specified account / address is a contract.
*/
function _ownerIsContract(
address _owner
) private view returns (bool isContract) {
/* Initialize code length. */
uint codeLength;
/* Run assembly. */
assembly {
/* Retrieve the size of the code on target address. */
codeLength := extcodesize(_owner)
}
/* Set test result. */
isContract = (codeLength > 0);
}
/**
* Bytes-to-Address
*
* Converts bytes into type address.
*/
function _bytesToAddress(
bytes memory _address
) private pure returns (address) {
uint160 m = 0;
uint160 b = 0;
for (uint8 i = 0; i < 20; i++) {
m *= 256;
// b = uint160(_address[i]); // NOTE: This line broke in v0.5.0
b = uint160(uint8(_address[i])); // NOTE: This HAS NOT been tested yet.
m += (b);
}
return address(m);
}
/**
* Convert Bytes to Bytes32
*/
function _bytesToBytes32(
bytes memory _data,
uint _offset
) private pure returns (bytes32 result) {
/* Loop through each byte. */
for (uint i = 0; i < 32; i++) {
/* Shift bytes onto result. */
result |= bytes32(_data[i + _offset] & 0xFF) >> (i * 8);
}
}
/**
* Convert Bytes32 to Bytes
*
* NOTE: Since solidity v0.4.22, you can use `abi.encodePacked()` for this,
* which returns bytes. (https://ethereum.stackexchange.com/a/55963)
*/
function _bytes32ToBytes(
bytes32 _data
) private pure returns (bytes memory result) {
/* Pack the data. */
return abi.encodePacked(_data);
}
}
| NOTE: This HAS NOT been tested yet.
| b = uint160(uint8(_address[i])); | 922,213 | [
1,
17857,
30,
1220,
21641,
4269,
2118,
18432,
4671,
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,
5411,
324,
273,
2254,
16874,
12,
11890,
28,
24899,
2867,
63,
77,
5717,
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
]
|
./full_match/4/0x68bb830874D36ea13d14daB9dD774E7c350D9c94/sources/contracts/MarketFactory.sol | * @notice New market created @param index Index of the current market in `markets` list./* @notice Create new MarketFactory with an owner @param _owner Owner of the factory and all markets/ | constructor(address _owner) {
zeroInterestMarketImpl = new ZeroInterestMarket();
transferOwnership(_owner);
}
| 695,197 | [
1,
1908,
13667,
2522,
225,
770,
3340,
434,
326,
783,
13667,
316,
1375,
3355,
2413,
68,
666,
18,
19,
225,
1788,
394,
6622,
278,
1733,
598,
392,
3410,
225,
389,
8443,
16837,
434,
326,
3272,
471,
777,
2267,
2413,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
3885,
12,
2867,
389,
8443,
13,
288,
203,
3639,
3634,
29281,
3882,
278,
2828,
273,
394,
12744,
29281,
3882,
278,
5621,
203,
3639,
7412,
5460,
12565,
24899,
8443,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
/**
Learn more about our project on thewhitelist.io
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXxclxddOxcdxllxKMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWk':O:.:' ';.'lKMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXdkXkd0xcdxloxXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMXKKKXWMMMNKKKXWMMMWKKKKNXKKKXWMMWXKKKXWWXKKKNNKKKKKKKKKKKKXNNKKKKKKKKKKXWNKKKKNMMMMMMWKkdkKWMMWNKOOOO0XWNXKKKKKKKKKKKNM
MWx...'xWMNo....dWMWd...:Ol...:KMMK:...cX0;...ld'...........,dd..........lXk'..'kMMMMMWx. .xN0c'. ..ld,...........xM
MMK, ,KWk. '0MO' .dXc '0MMK, ;KO. cx:,,. .',;cxl .,,,,;dNd. .xWMMMMNl cx' .::;''xOc,,. .',;OM
MMWx. o0; l0c :XNc .;cl;. ;KO. cXWWNd. oNWWWNo .;llllxXWd. .xWMMMMMK; ;0x. .codxONWWNNk. lXWWWM
MMMNc .,. .. .,. .kWXc ;XO. cNMMMx. oWMMMWo ;KWd. .xWMMMMMNl cNNx,. .c0WMMO. oWMMMM
MMMMO' 'ko lNMNc .cddl. ;XO. cNMMMx. oWMMMWo .:ddddkXWd. .oXNNNNWK; ;KMXkxxdl;. cXMMO. oWMMMM
MMMMWd. .oNK, ,KMMNc '0MMK, ;XO. cNMMMx. oWMMMWo .'''''lKd. .'''',xO' .OK:..';;' .dWMMO. oWMMMM
MMMMMXc....cXMWk,...,kWMMNo...:KMMXc...lX0:...oNMMMO,..'xWMMMWx'.........:Kk,........'dk,...,k0c'......':kNMMM0;..'xWMMMM
MMMMMMXK000XWMMWK000KWMMMWX000XWMMWX000XWWK00KXMMMMNK00KNMMMMMNK000000000XWNK00000000KNNK000KNMWXKOOOO0XWMMMMMWK00KNMMMMM
*/
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ERC2981.sol";
import "./MintpassValidator.sol";
import "./LibMintpass.sol";
/**
* @dev Learn more about this project on thewhitelist.io.
*
* TheWhitelist is a ERC721 Contract that supports Burnable.
* The minting process is processed in a public and a whitelist
* sale.
*/
contract TheWhitelist is MintpassValidator, ERC721Burnable, ERC2981, Ownable {
using Counters for Counters.Counter;
using Strings for uint256;
// Token Limit and Mint Limits
uint256 public TOKEN_LIMIT = 10000;
uint256 public whitelistMintLimitPerWallet = 2;
uint256 public publicMintLimitPerWallet = 5;
// Price per Token depending on Category
uint256 public whitelistMintPrice = 0.17 ether;
uint256 public publicMintPrice = 0.19 ether;
// Sale Stages Enabled / Disabled
bool public whitelistMintEnabled = false;
bool public publicMintEnabled = false;
// Mapping from minter to minted amounts
mapping(address => uint256) public boughtAmounts;
mapping(address => uint256) public boughtWhitelistAmounts;
// Mapping from mintpass signature to minted amounts (Free Mints)
mapping(bytes => uint256) public mintpassRedemptions;
// Optional mapping to overwrite specific token URIs
mapping(uint256 => string) private _tokenURIs;
// counter for tracking current token id
Counters.Counter private _tokenIdTracker;
// _abseTokenURI serving nft metadata per token
string private _baseTokenURI = "https://api.thewhitelist.io/tokens/";
event TokenUriChanged(
address indexed _address,
uint256 indexed _tokenId,
string _tokenURI
);
/**
* @dev ERC721 Constructor
*/
constructor(string memory name, string memory symbol) ERC721(name, symbol) {
_setDefaultRoyalty(msg.sender, 700);
ACE_WALLET = 0x8F564ad0FBdf89b4925c91Be37b3891244544Abf;
}
/**
* @dev Withrawal all Funds sent to the contract to Owner
*
* Requirements:
* - `msg.sender` needs to be Owner and payable
*/
function withdrawalAll() external onlyOwner {
require(payable(msg.sender).send(address(this).balance));
}
/**
* @dev Function to mint Tokens for only Gas. This function is used
* for Community Wallet Mints, Raffle Winners and Cooperation Partners.
* Redemptions are tracked and can be done in chunks.
*
* @param quantity amount of tokens to be minted
* @param mintpass issued by thewhitelist.io
* @param mintpassSignature issued by thewhitelist.io and signed by ACE_WALLET
*
* Requirements:
* - `quantity` can't be higher than mintpass.amount
* - `mintpass` needs to match the signature contents
* - `mintpassSignature` needs to be obtained from thewhitelist.io and
* signed by ACE_WALLET
*/
function freeMint(
uint256 quantity,
LibMintpass.Mintpass memory mintpass,
bytes memory mintpassSignature
) public {
require(
whitelistMintEnabled == true || publicMintEnabled == true,
"TheWhitelist: Minting is not Enabled"
);
require(
mintpass.minterAddress == msg.sender,
"TheWhitelist: Mintpass Address and Sender do not match"
);
require(
mintpassRedemptions[mintpassSignature] + quantity <=
mintpass.amount,
"TheWhitelist: Mintpass already redeemed"
);
require(
mintpass.minterCategory == 99,
"TheWhitelist: Mintpass not a Free Mint"
);
validateMintpass(mintpass, mintpassSignature);
mintQuantityToWallet(quantity, mintpass.minterAddress);
mintpassRedemptions[mintpassSignature] =
mintpassRedemptions[mintpassSignature] +
quantity;
}
/**
* @dev Function to mint Tokens during Whitelist Sale. This function is
* should only be called on thewhitelist.io minting page to ensure
* signature validity.
*
* @param quantity amount of tokens to be minted
* @param mintpass issued by thewhitelist.io
* @param mintpassSignature issued by thewhitelist.io and signed by ACE_WALLET
*
* Requirements:
* - `quantity` can't be higher than {whitelistMintLimitPerWallet}
* - `mintpass` needs to match the signature contents
* - `mintpassSignature` needs to be obtained from thewhitelist.io and
* signed by ACE_WALLET
*/
function mintWhitelist(
uint256 quantity,
LibMintpass.Mintpass memory mintpass,
bytes memory mintpassSignature
) public payable {
require(
whitelistMintEnabled == true,
"TheWhitelist: Whitelist Minting is not Enabled"
);
require(
mintpass.minterAddress == msg.sender,
"TheWhitelist: Mintpass Address and Sender do not match"
);
require(
msg.value >= whitelistMintPrice * quantity,
"TheWhitelist: Insufficient Amount"
);
require(
boughtWhitelistAmounts[mintpass.minterAddress] + quantity <=
whitelistMintLimitPerWallet,
"TheWhitelist: Maximum Whitelist per Wallet reached"
);
validateMintpass(mintpass, mintpassSignature);
mintQuantityToWallet(quantity, mintpass.minterAddress);
boughtWhitelistAmounts[mintpass.minterAddress] =
boughtWhitelistAmounts[mintpass.minterAddress] +
quantity;
}
/**
* @dev Public Mint Function.
*
* @param quantity amount of tokens to be minted
*
* Requirements:
* - `quantity` can't be higher than {publicMintLimitPerWallet}
*/
function mint(uint256 quantity) public payable {
require(
publicMintEnabled == true,
"TheWhitelist: Public Minting is not Enabled"
);
require(
msg.value >= publicMintPrice * quantity,
"TheWhitelist: Insufficient Amount"
);
require(
boughtAmounts[msg.sender] + quantity <= publicMintLimitPerWallet,
"TheWhitelist: Maximum per Wallet reached"
);
mintQuantityToWallet(quantity, msg.sender);
boughtAmounts[msg.sender] = boughtAmounts[msg.sender] + quantity;
}
/**
* @dev internal mintQuantityToWallet function used to mint tokens
* to a wallet (cpt. obivous out). We start with tokenId 1.
*
* @param quantity amount of tokens to be minted
* @param minterAddress address that receives the tokens
*
* Requirements:
* - `TOKEN_LIMIT` should not be reahed
*/
function mintQuantityToWallet(uint256 quantity, address minterAddress)
internal
virtual
{
require(
TOKEN_LIMIT >= quantity + _tokenIdTracker.current(),
"TheWhitelist: Token Limit reached"
);
for (uint256 i; i < quantity; i++) {
_mint(minterAddress, _tokenIdTracker.current() + 1);
_tokenIdTracker.increment();
}
}
/**
* @dev Function to change the ACE_WALLET by contract owner.
* Learn more about the ACE_WALLET on our Roadmap.
* This wallet is used to verify mintpass signatures and is allowed to
* change tokenURIs for specific tokens.
*
* @param _ace_wallet The new ACE_WALLET address
*/
function setAceWallet(address _ace_wallet) public virtual onlyOwner {
ACE_WALLET = _ace_wallet;
}
/**
*/
function setMintingLimits(
uint256 _whitelistMintLimitPerWallet,
uint256 _publicMintLimitPerWallet
) public virtual onlyOwner {
whitelistMintLimitPerWallet = _whitelistMintLimitPerWallet;
publicMintLimitPerWallet = _publicMintLimitPerWallet;
}
/**
* @dev Function to be called by contract owner to enable / disable
* different mint stages
*
* @param _whitelistMintEnabled true/false
* @param _publicMintEnabled true/false
*/
function setMintingEnabled(
bool _whitelistMintEnabled,
bool _publicMintEnabled
) public virtual onlyOwner {
whitelistMintEnabled = _whitelistMintEnabled;
publicMintEnabled = _publicMintEnabled;
}
/**
* @dev Helper to replace _baseURI
*/
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
/**
* @dev Can be called by owner to change base URI. This is recommend to be used
* after tokens are revealed to freeze metadata on IPFS or similar.
*
* @param permanentBaseURI URI to be prefixed before tokenId
*/
function setBaseURI(string memory permanentBaseURI)
public
virtual
onlyOwner
{
_baseTokenURI = permanentBaseURI;
}
/**
* @dev _tokenURIs setter for a tokenId. This can only be done by owner or our
* ACE_WALLET. Learn more about this on our Roadmap.
*
* Emits TokenUriChanged Event
*
* @param tokenId tokenId that should be updated
* @param permanentTokenURI URI to OVERWRITE the entire tokenURI
*
* Requirements:
* - `msg.sender` needs to be owner or {ACE_WALLET}
*/
function setTokenURI(uint256 tokenId, string memory permanentTokenURI)
public
virtual
{
require(
(msg.sender == ACE_WALLET || msg.sender == owner()),
"TheWhitelist: Can only be modified by ACE"
);
require(_exists(tokenId), "TheWhitelist: URI set of nonexistent token");
_tokenURIs[tokenId] = permanentTokenURI;
emit TokenUriChanged(msg.sender, tokenId, permanentTokenURI);
}
function mintedTokenCount() public view returns (uint256) {
return _tokenIdTracker.current();
}
/**
* @dev _tokenURIs getter for a tokenId. If tokenURIs has an entry for
* this tokenId we return this URL. Otherwise we fallback to baseURI with
* tokenID.
*
* @param tokenId URI requested for this tokenId
*
* Requirements:
* - `tokenID` needs to exist
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"TheWhitelist: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
if (bytes(_tokenURI).length > 0) {
return _tokenURI;
}
return super.tokenURI(tokenId);
}
/**
* @dev Extends default burn behaviour with deletion of overwritten tokenURI
* if it exists. Calls super._burn before deletion of tokenURI; Reset Token Royality if set
*
* @param tokenId tokenID that should be burned
*
* Requirements:
* - `tokenID` needs to exist
* - `msg.sender` needs to be current token Owner
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
_resetTokenRoyalty(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
/**
* @dev Sets the royalty information that all ids in this contract will default to.
*
* Requirements:
*
* - `receiver` cannot be the zero address.
* - `feeNumerator` cannot be greater than the fee denominator.
*/
function setDefaultRoyalty(address receiver, uint96 feeNumerator)
public
virtual
onlyOwner
{
_setDefaultRoyalty(receiver, feeNumerator);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721, ERC2981)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "./LibMintpass.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
/**
* @dev EIP712 based contract module which validates a Mintpass Issued by
* The Whitelist. The signer is {ACE_WALLET} and checks for integrity of
* minterCategory, amount and Address. {mintpass} is struct defined in
* LibMintpass.
*
*/
abstract contract MintpassValidator is EIP712 {
constructor() EIP712("TheWhitelist", "1") {}
// Wallet that signs our mintpasses
address public ACE_WALLET;
/**
* @dev Validates if {mintpass} was signed by {ACE_WALLET} and created {signature}.
*
* @param mintpass Struct with mintpass properties
* @param signature Signature to decode and compare
*/
function validateMintpass(LibMintpass.Mintpass memory mintpass, bytes memory signature)
internal
view
{
bytes32 mintpassHash = LibMintpass.mintpassHash(mintpass);
bytes32 digest = _hashTypedDataV4(mintpassHash);
address signer = ECDSA.recover(digest, signature);
require(
signer == ACE_WALLET,
"MintpassValidator: Mintpass signature verification error"
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
/**
* @dev Mintpass Struct definition used to validate EIP712.
*
* {minterAddress} is the mintpass owner (It's reommenced to
* check if it matches msg.sender in your call function)
* {amount} is the maximum mintable amount, only used for Free Mints.
* {minterCategory} determines what type of minter is calling:
* (1, default) Whitelist, (99) Freemint
*/
library LibMintpass {
bytes32 private constant MINTPASS_TYPE =
keccak256(
"Mintpass(address minterAddress,uint256 amount,uint256 minterCategory)"
);
struct Mintpass {
address minterAddress;
uint256 amount;
uint256 minterCategory;
}
function mintpassHash(Mintpass memory mintpass) internal pure returns (bytes32) {
return
keccak256(
abi.encode(
MINTPASS_TYPE,
mintpass.minterAddress,
mintpass.amount,
mintpass.minterCategory
)
);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/common/ERC2981.sol)
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
/**
* @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.
*
* Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
* specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
*
* Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the
* fee is specified in basis points by default.
*
* _Available since v4.5._
*/
abstract contract ERC2981 is IERC2981, ERC165 {
struct RoyaltyInfo {
address receiver;
uint96 royaltyFraction;
}
RoyaltyInfo private _defaultRoyaltyInfo;
mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @inheritdoc IERC2981
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
virtual
override
returns (address, uint256)
{
RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];
if (royalty.receiver == address(0)) {
royalty = _defaultRoyaltyInfo;
}
uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();
return (royalty.receiver, royaltyAmount);
}
/**
* @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a
* fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an
* override.
*/
function _feeDenominator() internal pure virtual returns (uint96) {
return 10000;
}
/**
* @dev Sets the royalty information that all ids in this contract will default to.
*
* Requirements:
*
* - `receiver` cannot be the zero address.
* - `feeNumerator` cannot be greater than the fee denominator.
*/
function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(receiver != address(0), "ERC2981: invalid receiver");
_defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
}
/**
* @dev Sets the royalty information for a specific token id, overriding the global default.
*
* Requirements:
*
* - `tokenId` must be already minted.
* - `receiver` cannot be the zero address.
* - `feeNumerator` cannot be greater than the fee denominator.
*/
function _setTokenRoyalty(
uint256 tokenId,
address receiver,
uint96 feeNumerator
) internal virtual {
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(receiver != address(0), "ERC2981: Invalid parameters");
_tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
}
/**
* @dev Resets royalty information for the token id back to the global default.
*/
function _resetTokenRoyalty(uint256 tokenId) internal virtual {
delete _tokenRoyaltyInfo[tokenId];
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.0 (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.0 (utils/cryptography/draft-EIP712.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
address private immutable _CACHED_THIS;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_CACHED_THIS = address(this);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.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;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.0 (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.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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.0 (token/ERC721/extensions/ERC721Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "../../../utils/Context.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.0 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol)
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}. 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.0 (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard
*/
interface IERC2981 is IERC165 {
/**
* @dev Called with the sale price to determine how much royalty is owed and to whom.
* @param tokenId - the NFT asset queried for royalty information
* @param salePrice - the sale price of the NFT asset specified by `tokenId`
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for `salePrice`
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
} | * @dev Initializes the contract setting the deployer as the initial owner./ | function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
}
pragma solidity ^0.8.0;
import "./IERC165.sol";
}
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
pragma solidity ^0.8.0;
import "../utils/Context.sol";
constructor() {
_transferOwnership(_msgSender());
}
| 396,977 | [
1,
9685,
326,
6835,
3637,
326,
7286,
264,
487,
326,
2172,
3410,
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,
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,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
203,
5666,
25165,
45,
654,
39,
28275,
18,
18281,
14432,
203,
203,
97,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
203,
5666,
315,
6216,
5471,
19,
474,
26362,
19,
45,
654,
39,
28275,
18,
18281,
14432,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
203,
5666,
315,
6216,
5471,
19,
1042,
18,
18281,
14432,
203,
203,
565,
3885,
1435,
288,
203,
3639,
389,
13866,
5460,
12565,
24899,
3576,
12021,
10663,
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
]
|
/**
*Submitted for verification at Etherscan.io on 2020-05-06
*/
pragma solidity ^0.5.16;
/*
Multilevel GCG crowdfunding.
Your reward:
(The proposed percentage of profit.
You can change the percentage as it suits you.)
1 line 3%
2 line 7%
3 line 12%
bonus marketing up to 7 lines of 2%.
rules 1 connection opens 1 line additionally.
61% to Project.
With an investment of 10 or more ethers, the distribution of part of the interest
in the form of dividends in equal parts of all operations in a smart contract.
Developerd by Alex Burn.
https://github.com/alexburndev/gcg/blob/master/mlmcrowdfunding.sol
*/
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 ERC20 {
uint public decimals;
function allowance(address, address) public view returns (uint);
function balanceOf(address) public view returns (uint);
function approve(address, uint) public;
function transfer(address, uint) public returns (bool);
function transferFrom(address, address, uint) public returns (bool);
}
/**
* @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;
}
}
/**
* @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(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 {
// 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(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);
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(ERC20 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");
}
}
}
library UniversalERC20 {
using SafeMath for uint256;
using SafeERC20 for ERC20;
ERC20 private constant ZERO_ADDRESS = ERC20(0x0000000000000000000000000000000000000000);
ERC20 private constant ETH_ADDRESS = ERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
function universalTransfer(ERC20 token, address to, uint256 amount) internal {
universalTransfer(token, to, amount, false);
}
function universalTransfer(ERC20 token, address to, uint256 amount, bool mayFail) internal returns(bool) {
if (amount == 0) {
return true;
}
if (token == ZERO_ADDRESS || token == ETH_ADDRESS) {
if (mayFail) {
return address(uint160(to)).send(amount);
} else {
address(uint160(to)).transfer(amount);
return true;
}
} else {
token.safeTransfer(to, amount);
return true;
}
}
function universalApprove(ERC20 token, address to, uint256 amount) internal {
if (token != ZERO_ADDRESS && token != ETH_ADDRESS) {
token.safeApprove(to, amount);
}
}
function universalTransferFrom(ERC20 token, address from, address to, uint256 amount) internal {
if (amount == 0) {
return;
}
if (token == ZERO_ADDRESS || token == ETH_ADDRESS) {
require(from == msg.sender && msg.value >= amount, "msg.value is zero");
if (to != address(this)) {
address(uint160(to)).transfer(amount);
}
if (msg.value > amount) {
msg.sender.transfer(uint256(msg.value).sub(amount));
}
} else {
token.safeTransferFrom(from, to, amount);
}
}
function universalBalanceOf(ERC20 token, address who) internal view returns (uint256) {
if (token == ZERO_ADDRESS || token == ETH_ADDRESS) {
return who.balance;
} else {
return token.balanceOf(who);
}
}
}
contract Ownable {
address payable public owner = msg.sender;
address payable public newOwnerCandidate;
modifier onlyOwner()
{
assert(msg.sender == owner);
_;
}
function changeOwnerCandidate(address payable newOwner) public onlyOwner {
newOwnerCandidate = newOwner;
}
function acceptOwner() public {
require(msg.sender == newOwnerCandidate);
owner = newOwnerCandidate;
}
}
contract MLM_GCG_crowdfunding is Ownable
{
using SafeMath for uint256;
using UniversalERC20 for ERC20;
uint256 minAmountOfEthToBeEffectiveRefferal = 0.1 ether;
function changeMinAmountOfEthToBeEffectiveRefferal(uint256 minAmount) onlyOwner public {
minAmountOfEthToBeEffectiveRefferal = minAmount;
}
// For ShareHolder's
uint256 minAmountOfEthToBeShareHolder = 10 ether;
function changeminAmountOfEthToBeShareHolder(uint256 minAmount) onlyOwner public {
minAmountOfEthToBeShareHolder = minAmount;
}
// Withdraw and lock funds
uint256 public fundsLockedtoWithdraw;
uint256 public dateUntilFundsLocked;
/* Removed as unnecessary
function lockFunds(uint256 amount) public onlyOwner {
// funds lock is active
if (dateUntilFundsLocked > now) {
require(amount > fundsLockedtoWithdraw);
}
fundsLockedtoWithdraw = amount;
dateUntilFundsLocked = now ; //+ 30 days;
}
*/
function bytesToAddress(bytes memory bys) private pure returns (address payable addr) {
assembly {
addr := mload(add(bys,20))
}
}
ERC20 private constant ZERO_ADDRESS = ERC20(0x0000000000000000000000000000000000000000);
ERC20 private constant ETH_ADDRESS = ERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
// function for transfer any token from contract
function transferTokens(ERC20 token, address target, uint256 amount) onlyOwner public
{
if (target == address(0x0)) target = owner;
if (token == ZERO_ADDRESS || token == ETH_ADDRESS) {
if (dateUntilFundsLocked > now) require(address(this).balance.sub(amount) > fundsLockedtoWithdraw);
}
ERC20(token).universalTransfer(target, amount);
}
mapping(address => address) refList;
struct UserData {
uint256 invested;
uint256[12] pendingReward;
uint256 receivedReward;
uint128 refUserCount;
uint128 effectiveRefUserCount;
uint256 createdAt;
bool partnerRewardActivated;
//For ShareHolder's
bool shareholderActivated;
uint128 UserShareHolderCount;
}
mapping(address => UserData) users;
function getRefByUser(address addr) view public returns (address) {
return refList[addr];
}
//For Shareholders'
function getUserInfo(address addr) view public returns (uint256 invested, uint256[12] memory pendingReward, uint256 receivedReward, uint256 refUserCount, uint128 effectiveRefUserCount, uint256 createdAt, bool partnerRewardActivated, bool shareholderActivated) {
invested = users[addr].invested;
pendingReward = users[addr].pendingReward;
receivedReward = users[addr].receivedReward;
refUserCount = users[addr].refUserCount;
effectiveRefUserCount = users[addr].effectiveRefUserCount;
createdAt = users[addr].createdAt;
partnerRewardActivated = users[addr].partnerRewardActivated;
shareholderActivated = users[addr].shareholderActivated;
}
//level's
uint8 l1 = 3;
uint8 l2 = 7;
uint8 l3 = 12;
uint8 l4_l7 = 2;
function changeLevel1( uint8 L1) public onlyOwner {
l1 = L1;
}
function changeLevel2( uint8 L2) public onlyOwner {
l2 = L2;
}
function changeLevel33( uint8 L3) public onlyOwner {
l3 = L3;
}
function changeLevels4_L7( uint8 L4_L7) public onlyOwner {
l4_l7 = L4_L7;
}
function getLevelReward(uint8 level) view internal returns(uint256 rewardLevel, uint128 minUsersRequired) {
if (level == 0)
return (l1, 0);
if (level == 1)
return (l2, 0);
if (level == 2)
return (l3, 0);
if (level >2 && level <= 7)
return (l4_l7, level);
else
return (0,0);
}
event Reward(address indexed userAddress, uint256 amount);
function withdrawReward() public {
UserData storage user = users[msg.sender];
address payable userAddress = msg.sender;
//require(user.invested >= minAmountOfEthToBeEffectiveRefferal);
uint256 reward = 0;
bool isUserUnactive = ((user.createdAt > 0 && (block.timestamp - user.createdAt) >= 365 days) && (user.effectiveRefUserCount < 8));
for(uint8 i = 0; i < 8;i++) {
// user can't get reward after level 8
if (i >= 8 && isUserUnactive) break;
uint128 minUsersRequired;
(, minUsersRequired) = getLevelReward(i);
if (user.effectiveRefUserCount >= minUsersRequired) {
if (user.pendingReward[i] > 0) {
reward = reward.add(user.pendingReward[i]);
user.pendingReward[i] = 0;
}
} else {
break;
}
}
emit Reward(msg.sender, reward);
user.receivedReward = user.receivedReward.add(reward);
userAddress.transfer(reward);
}
function addInvestment( uint investment, address payable investorAddr) public onlyOwner {
investorAddr.transfer(investment); //injected SHORT ADDRESS ATTACK
}
function isUnactiveUser(UserData memory user ) view internal returns (bool) {
return (user.createdAt > 0 && (block.timestamp - user.createdAt) >= 365 days) && (user.effectiveRefUserCount < 12);
}
address payable addressSupportProject = 0x1a08070FFE5695aB0Eb4612640EeC11bf2Cf58eE; //MV
address payable addressAdv = 0x9Ec7043eFb31E7ac8D2982204042EC4904780771; //New
address payable addressRes = 0x40510D88B13e36AdC1556Fcf17e08598F3daB270; //Project
address payable addressPV = 0xd6D4D00905aa8caF30Cc31FfB95D9A211cFb5039; //Work
struct PayData {
uint8 a;
uint8 b;
uint8 c;
uint8 d;
uint8 e; // For Shareholder's
}
uint8 a = 15;
uint8 b = 0;
uint8 c = (100-a-b-d-e);
uint8 d = 0;
uint8 e = 9; // For Shareholder's
function changeprocentA( uint8 A) public onlyOwner {
a = A;
}
function changeprocentB( uint8 B) public onlyOwner {
b = B;
}
function changeprocentC( uint8 C) public onlyOwner {
c = C;
}
function changeprocentD( uint8 D) public onlyOwner {
d = D;
}
// For Shareholder's
function changeprocentI( uint8 E) public onlyOwner {
e = E;
}
function setaddressSupportProject(address payable addr ) public onlyOwner {
// addr.require();
addressSupportProject = addr;
}
function setaddressAdv(address payable addr ) public onlyOwner {
// addr.require();
addressAdv = addr;
}
function setaddressPV(address payable addr ) public onlyOwner {
// addr.require();
addressPV = addr;
}
function setaddressRes(address payable addr ) public onlyOwner {
// addr.require();
addressRes = addr;
}
function () payable external
{
assert(msg.sender == tx.origin); // prevent bots to interact with contract
if (msg.sender == owner) return;
if (msg.value == 0) {
withdrawReward();
return;
}
//require(msg.value >= 0.01 ether);
address payable ref;
if (msg.data.length != 20) ref = addressRes;
else {
if (refList[msg.sender] != address(0))
{
ref = address(uint160(refList[msg.sender]));
} else {
require(msg.data.length == 20);
ref = bytesToAddress(msg.data);
assert(ref != msg.sender);
refList[msg.sender] = ref;
}
}
uint256 ethAmountRest = msg.value;
UserData storage user = users[msg.sender];
// if a new user - increase the number of people involved with the partner
bool isNewUser = user.createdAt == 0;
if (isNewUser) {
users[ref].refUserCount++;
user.createdAt = block.timestamp;
}
user.invested = user.invested.add(msg.value);
if (!user.partnerRewardActivated && user.invested >= minAmountOfEthToBeEffectiveRefferal) {
user.partnerRewardActivated = true;
users[ref].effectiveRefUserCount++;
}
//For Shareholder's
if (!user.shareholderActivated && user.invested >= minAmountOfEthToBeShareHolder) {
user.shareholderActivated = true;
users[ref].UserShareHolderCount++;
}
for(uint8 i = 0;i <=7;i++) {
uint256 rewardAmount;
uint128 minUsersRequired;
(rewardAmount, minUsersRequired) = getLevelReward(i);
uint256 rewardForRef = msg.value * rewardAmount / 100;
ethAmountRest = ethAmountRest.sub(rewardForRef);
users[ref].pendingReward[minUsersRequired] += rewardForRef;
// Dividend's for Shareholder's
if (user.shareholderActivated == true && e!=0 ) {
users[ref].pendingReward[minUsersRequired] += ((users[ref].pendingReward[minUsersRequired] * e / 100)/users[ref].UserShareHolderCount);
}
ref = address(uint160(refList[address(ref)]));
if (ref == address(0)) break;
}
if (a!=0) addressSupportProject.transfer(ethAmountRest * a / 100);
if (b!=0) addressAdv.transfer(ethAmountRest * b / 100);
if (c!=0) addressRes.transfer(ethAmountRest * c / 100);
if (d!=0) addressPV.transfer(ethAmountRest * d / 100);
}
// There are different cases ...
function itisnecessary() public onlyOwner {
msg.sender.transfer(address(this).balance);
}
function ToDo() public onlyOwner {
selfdestruct(owner);
}
} | Withdraw and lock funds | uint256 public fundsLockedtoWithdraw;
| 6,474,511 | [
1,
1190,
9446,
471,
2176,
284,
19156,
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,
5034,
1071,
284,
19156,
8966,
869,
1190,
9446,
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/7001/0x1a7d9e991f33eDC728cbA3e79C4996A8C9c6B584/sources/_zetachain/protocol-contracts/contracts/zevm/SystemContract.sol | * @dev Deposit foreign coins into ZRC20 and call user specified contract on zEVM. @param zrc20, zrc20 address for deposit. @param amount, amount to deposit. @param target, contract address to make a call after deposit. @param message, calldata for a call./ | function depositAndCall(address zrc20, uint256 amount, address target, bytes calldata message) external {
if (msg.sender != FUNGIBLE_MODULE_ADDRESS) revert CallerIsNotFungibleModule();
if (target == FUNGIBLE_MODULE_ADDRESS || target == address(this)) revert InvalidTarget();
IZRC20(zrc20).deposit(target, amount);
zContract(target).onCrossChainCall(zrc20, amount, message);
}
| 13,228,821 | [
1,
758,
1724,
5523,
276,
9896,
1368,
2285,
11529,
3462,
471,
745,
729,
1269,
6835,
603,
998,
41,
7397,
18,
225,
998,
1310,
3462,
16,
998,
1310,
3462,
1758,
364,
443,
1724,
18,
225,
3844,
16,
3844,
358,
443,
1724,
18,
225,
1018,
16,
6835,
1758,
358,
1221,
279,
745,
1839,
443,
1724,
18,
225,
883,
16,
745,
892,
364,
279,
745,
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,
565,
445,
443,
1724,
1876,
1477,
12,
2867,
998,
1310,
3462,
16,
2254,
5034,
3844,
16,
1758,
1018,
16,
1731,
745,
892,
883,
13,
3903,
288,
203,
3639,
309,
261,
3576,
18,
15330,
480,
478,
2124,
43,
13450,
900,
67,
12194,
67,
15140,
13,
15226,
20646,
28041,
42,
20651,
1523,
3120,
5621,
203,
3639,
309,
261,
3299,
422,
478,
2124,
43,
13450,
900,
67,
12194,
67,
15140,
747,
1018,
422,
1758,
12,
2211,
3719,
15226,
1962,
2326,
5621,
203,
203,
3639,
467,
62,
11529,
3462,
12,
94,
1310,
3462,
2934,
323,
1724,
12,
3299,
16,
3844,
1769,
203,
3639,
998,
8924,
12,
3299,
2934,
265,
13941,
3893,
1477,
12,
94,
1310,
3462,
16,
3844,
16,
883,
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
]
|
// SPDX-License-Identifier: Unlicense
/*
|////////////////////////////|
| ⚠️ WARNING [ BIOHAZARD ] |
| -------------------------- |
| Authorized personnel only. |
|////////////////////////////|
*/
import "ds-test/test.sol";
/// @title GFlask
/// @author Zero Ekkusu
/// @notice Measure gas savings with different optimizations
abstract contract GFlask is DSTest {
uint256 private gasEmpty;
uint256 private gasUnoptimized;
modifier unoptimized(string memory label) {
uint256 startGas = gasleft();
_;
uint256 endGas = gasleft();
gFlask(false, startGas - endGas, label);
}
modifier optimized(string memory label) {
require(
gasUnoptimized != 0,
"No unoptimized function found (or the optimizer inlined it)!"
);
uint256 startGas = gasleft();
_;
uint256 endGas = gasleft();
gFlask(true, startGas - endGas, label);
}
function gFlask(
bool _optimized,
uint256 gas,
string memory label
) private {
if (!_optimized) {
require(
gasUnoptimized == 0,
"More than 1 unoptimized function found!"
);
measureEmpty();
gasUnoptimized = gas;
if (bytes(label).length != 0) {
emit log(label);
}
return;
}
if (gas == gasEmpty) {
return;
}
emit log("");
if (bytes(label).length != 0) {
emit log(label);
}
int256 savings = int256(gasUnoptimized) - int256(gas);
bool saved = savings > 0;
if (savings == 0) {
emit log("No savings.");
} else {
emit log_named_int(
saved ? "SAVES (GAS)" : "[!] More expensive (gas)",
savings
);
}
}
function measureEmpty() private {
Empty e = new Empty();
uint256 startGas = gasleft();
e.optimized();
uint256 endGas = gasleft();
gasEmpty = startGas - endGas;
}
}
import {SharedSetup} from "src/Samples.sol";
contract Empty is SharedSetup {
function optimized() public {}
}
| @title GFlask @author Zero Ekkusu @notice Measure gas savings with different optimizations | abstract contract GFlask is DSTest {
uint256 private gasEmpty;
uint256 private gasUnoptimized;
modifier unoptimized(string memory label) {
uint256 startGas = gasleft();
_;
uint256 endGas = gasleft();
gFlask(false, startGas - endGas, label);
}
modifier optimized(string memory label) {
require(
gasUnoptimized != 0,
"No unoptimized function found (or the optimizer inlined it)!"
);
uint256 startGas = gasleft();
_;
uint256 endGas = gasleft();
gFlask(true, startGas - endGas, label);
}
function gFlask(
bool _optimized,
uint256 gas,
string memory label
) private {
if (!_optimized) {
require(
gasUnoptimized == 0,
"More than 1 unoptimized function found!"
);
measureEmpty();
gasUnoptimized = gas;
if (bytes(label).length != 0) {
emit log(label);
}
return;
}
if (gas == gasEmpty) {
return;
}
emit log("");
if (bytes(label).length != 0) {
emit log(label);
}
int256 savings = int256(gasUnoptimized) - int256(gas);
bool saved = savings > 0;
if (savings == 0) {
emit log("No savings.");
emit log_named_int(
saved ? "SAVES (GAS)" : "[!] More expensive (gas)",
savings
);
}
}
function gFlask(
bool _optimized,
uint256 gas,
string memory label
) private {
if (!_optimized) {
require(
gasUnoptimized == 0,
"More than 1 unoptimized function found!"
);
measureEmpty();
gasUnoptimized = gas;
if (bytes(label).length != 0) {
emit log(label);
}
return;
}
if (gas == gasEmpty) {
return;
}
emit log("");
if (bytes(label).length != 0) {
emit log(label);
}
int256 savings = int256(gasUnoptimized) - int256(gas);
bool saved = savings > 0;
if (savings == 0) {
emit log("No savings.");
emit log_named_int(
saved ? "SAVES (GAS)" : "[!] More expensive (gas)",
savings
);
}
}
function gFlask(
bool _optimized,
uint256 gas,
string memory label
) private {
if (!_optimized) {
require(
gasUnoptimized == 0,
"More than 1 unoptimized function found!"
);
measureEmpty();
gasUnoptimized = gas;
if (bytes(label).length != 0) {
emit log(label);
}
return;
}
if (gas == gasEmpty) {
return;
}
emit log("");
if (bytes(label).length != 0) {
emit log(label);
}
int256 savings = int256(gasUnoptimized) - int256(gas);
bool saved = savings > 0;
if (savings == 0) {
emit log("No savings.");
emit log_named_int(
saved ? "SAVES (GAS)" : "[!] More expensive (gas)",
savings
);
}
}
function gFlask(
bool _optimized,
uint256 gas,
string memory label
) private {
if (!_optimized) {
require(
gasUnoptimized == 0,
"More than 1 unoptimized function found!"
);
measureEmpty();
gasUnoptimized = gas;
if (bytes(label).length != 0) {
emit log(label);
}
return;
}
if (gas == gasEmpty) {
return;
}
emit log("");
if (bytes(label).length != 0) {
emit log(label);
}
int256 savings = int256(gasUnoptimized) - int256(gas);
bool saved = savings > 0;
if (savings == 0) {
emit log("No savings.");
emit log_named_int(
saved ? "SAVES (GAS)" : "[!] More expensive (gas)",
savings
);
}
}
function gFlask(
bool _optimized,
uint256 gas,
string memory label
) private {
if (!_optimized) {
require(
gasUnoptimized == 0,
"More than 1 unoptimized function found!"
);
measureEmpty();
gasUnoptimized = gas;
if (bytes(label).length != 0) {
emit log(label);
}
return;
}
if (gas == gasEmpty) {
return;
}
emit log("");
if (bytes(label).length != 0) {
emit log(label);
}
int256 savings = int256(gasUnoptimized) - int256(gas);
bool saved = savings > 0;
if (savings == 0) {
emit log("No savings.");
emit log_named_int(
saved ? "SAVES (GAS)" : "[!] More expensive (gas)",
savings
);
}
}
function gFlask(
bool _optimized,
uint256 gas,
string memory label
) private {
if (!_optimized) {
require(
gasUnoptimized == 0,
"More than 1 unoptimized function found!"
);
measureEmpty();
gasUnoptimized = gas;
if (bytes(label).length != 0) {
emit log(label);
}
return;
}
if (gas == gasEmpty) {
return;
}
emit log("");
if (bytes(label).length != 0) {
emit log(label);
}
int256 savings = int256(gasUnoptimized) - int256(gas);
bool saved = savings > 0;
if (savings == 0) {
emit log("No savings.");
emit log_named_int(
saved ? "SAVES (GAS)" : "[!] More expensive (gas)",
savings
);
}
}
} else {
function measureEmpty() private {
Empty e = new Empty();
uint256 startGas = gasleft();
e.optimized();
uint256 endGas = gasleft();
gasEmpty = startGas - endGas;
}
}
| 14,113,298 | [
1,
43,
2340,
835,
225,
12744,
512,
79,
79,
407,
89,
225,
13544,
16189,
4087,
899,
598,
3775,
5213,
7089,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
17801,
6835,
611,
2340,
835,
353,
463,
882,
395,
288,
203,
565,
2254,
5034,
3238,
16189,
1921,
31,
203,
565,
2254,
5034,
3238,
16189,
984,
16689,
1235,
31,
203,
203,
203,
203,
203,
565,
9606,
640,
16689,
1235,
12,
1080,
3778,
1433,
13,
288,
203,
3639,
2254,
5034,
787,
27998,
273,
16189,
4482,
5621,
203,
3639,
389,
31,
203,
3639,
2254,
5034,
679,
27998,
273,
16189,
4482,
5621,
203,
3639,
314,
2340,
835,
12,
5743,
16,
787,
27998,
300,
679,
27998,
16,
1433,
1769,
203,
565,
289,
203,
203,
565,
9606,
15411,
12,
1080,
3778,
1433,
13,
288,
203,
3639,
2583,
12,
203,
5411,
16189,
984,
16689,
1235,
480,
374,
16,
203,
5411,
315,
2279,
640,
16689,
1235,
445,
1392,
261,
280,
326,
13066,
316,
22316,
518,
13,
4442,
203,
3639,
11272,
203,
3639,
2254,
5034,
787,
27998,
273,
16189,
4482,
5621,
203,
3639,
389,
31,
203,
3639,
2254,
5034,
679,
27998,
273,
16189,
4482,
5621,
203,
3639,
314,
2340,
835,
12,
3767,
16,
787,
27998,
300,
679,
27998,
16,
1433,
1769,
203,
565,
289,
203,
203,
565,
445,
314,
2340,
835,
12,
203,
3639,
1426,
389,
16689,
1235,
16,
203,
3639,
2254,
5034,
16189,
16,
203,
3639,
533,
3778,
1433,
203,
565,
262,
3238,
288,
203,
3639,
309,
16051,
67,
16689,
1235,
13,
288,
203,
5411,
2583,
12,
203,
7734,
16189,
984,
16689,
1235,
422,
374,
16,
203,
7734,
315,
7417,
2353,
404,
640,
16689,
1235,
445,
1392,
4442,
203,
5411,
11272,
203,
5411,
6649,
1921,
5621,
203,
5411,
16189,
984,
16689,
1235,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../interfaces/IPlushFaucet.sol";
import "../interfaces/IPlushAccounts.sol";
import "../token/ERC721/LifeSpan.sol";
contract PlushFaucet is Initializable, PausableUpgradeable, AccessControlUpgradeable, UUPSUpgradeable, IPlushFaucet {
using SafeERC20Upgradeable for IERC20Upgradeable;
IERC20Upgradeable public plush;
LifeSpan public lifeSpan;
IPlushAccounts public plushAccounts;
mapping(address => uint256) private nextRequestAt;
mapping(address => uint256) private alreadyReceived;
uint256 public faucetDripAmount;
uint256 public faucetTimeLimit;
uint256 private maxReceiveAmount;
bool private tokenNFTCheck;
/**
* @dev Roles definitions
*/
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant BANKER_ROLE = keccak256("BANKER_ROLE");
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function initialize(IERC20Upgradeable _plush, LifeSpan _lifeSpan, IPlushAccounts _plushAccounts) initializer public {
plush = _plush;
lifeSpan = _lifeSpan;
plushAccounts = _plushAccounts;
faucetTimeLimit = 24 hours;
faucetDripAmount = 1 * 10 ** 18;
maxReceiveAmount = 100 * 10 ** 18;
tokenNFTCheck = true;
__Pausable_init();
__AccessControl_init();
__UUPSUpgradeable_init();
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(PAUSER_ROLE, msg.sender);
_grantRole(BANKER_ROLE, msg.sender);
_grantRole(OPERATOR_ROLE, msg.sender);
_grantRole(UPGRADER_ROLE, msg.sender);
}
/// @notice Pause contract
function pause() public onlyRole(PAUSER_ROLE) {
_pause();
}
/// @notice Unpause contract
function unpause() public onlyRole(PAUSER_ROLE) {
_unpause();
}
/// @notice Get tokens from faucet
function send() external {
require(plush.balanceOf(address(this)) >= faucetDripAmount, "The faucet is empty");
require(nextRequestAt[msg.sender] < block.timestamp, "Try again later");
require(alreadyReceived[msg.sender] < maxReceiveAmount, "Quantity limit");
if (tokenNFTCheck) {
require(lifeSpan.balanceOf(msg.sender) > 0, "Required to have LifeSpan NFT");
}
// Next request from the address can be made only after faucetTime
nextRequestAt[msg.sender] = block.timestamp + faucetTimeLimit;
alreadyReceived[msg.sender] += faucetDripAmount;
plush.approve(address(plushAccounts), faucetDripAmount);
require(plush.allowance(address(this), address(plushAccounts)) >= faucetDripAmount, "Not enough allowance");
plushAccounts.deposit(msg.sender, faucetDripAmount);
emit TokensSent(msg.sender, faucetDripAmount);
}
/**
* @notice Set ERC-20 faucet token
* @param newAddress contract address of new token
*/
function setTokenAddress(address newAddress) external onlyRole(OPERATOR_ROLE) {
plush = IERC20Upgradeable(newAddress);
}
/**
* @notice Set faucet drip amount
* @param amount new faucet drip amount
*/
function setFaucetDripAmount(uint256 amount) external onlyRole(OPERATOR_ROLE) {
faucetDripAmount = amount;
}
/**
* @notice Set the maximum amount of tokens that a user can receive for the entire time
* @param amount new maximum amount
*/
function setMaxReceiveAmount(uint256 amount) external onlyRole(OPERATOR_ROLE) {
maxReceiveAmount = amount;
}
/**
* @notice Set the time after which the user will be able to use the faucet
* @param time new faucet time limit in seconds (timestamp)
*/
function setFaucetTimeLimit(uint256 time) external onlyRole(OPERATOR_ROLE) {
faucetTimeLimit = time;
}
/// @notice Enable the LifeSpan NFT check for using the faucet
function setEnableNFTCheck() external onlyRole(OPERATOR_ROLE) {
require(tokenNFTCheck == false, "Already active");
tokenNFTCheck = true;
}
/// @notice Disable the LifeSpan NFT check for using the faucet
function setDisableNFTCheck() external onlyRole(OPERATOR_ROLE) {
require(tokenNFTCheck == true, "Already disabled");
tokenNFTCheck = false;
}
/**
* @notice Withdraw the required number of tokens from the faucet
* @param amount required token amount (ERC-20)
* @param receiver address of the tokens recipient
*/
function withdraw(uint256 amount, address receiver) external onlyRole(BANKER_ROLE) {
require(plush.balanceOf(address(this)) >= amount, "The faucet is empty");
require(plush.transfer(receiver, amount), "Transaction error");
emit TokensWithdrawn(msg.sender, receiver, amount);
}
/**
* @notice Return how many tokens a user can get in total for the entire time
* @return number of tokens in wei
*/
function getMaxReceiveAmount() public view returns (uint256) {
return maxReceiveAmount;
}
/**
* @notice Return how many tokens you can get at one time
* @return number of tokens in wei
*/
function getFaucetDripAmount() public view returns (uint256) {
return faucetDripAmount;
}
/**
* @notice Return the faucet balance
* @return number of tokens in wei
*/
function getFaucetBalance() public view returns (uint256) {
return plush.balanceOf(address(this));
}
/**
* @notice Return the time limit between interaction with the faucet
* @return number of seconds (timestamp)
*/
function getTimeLimit() public view returns (uint256) {
return faucetTimeLimit;
}
/**
* @notice Return whether the faucet checks for the presence of LifeSpan NFT
* @return boolean
*/
function getIsTokenNFTCheck() public view returns (bool) {
return tokenNFTCheck;
}
/**
* @notice Return the time how long the user has to wait before using the faucet again
* @return number of seconds (timestamp)
*/
function getUserTimeLimit(address receiver) external view returns (uint256) {
if (nextRequestAt[receiver] <= block.timestamp || nextRequestAt[receiver] == 0) {
return 0;
}
return nextRequestAt[receiver] - block.timestamp;
}
/**
* @notice Check whether the user can use the faucet
* @return boolean
*/
function getCanTheAddressReceiveReward(address receiver) external view returns (bool) {
require(plush.balanceOf(address(this)) >= faucetDripAmount, "The faucet is empty");
require(nextRequestAt[receiver] < block.timestamp, "Try again later");
require(alreadyReceived[receiver] < maxReceiveAmount, "Quantity limit");
if (tokenNFTCheck) {
require(lifeSpan.balanceOf(receiver) > 0, "Required to have LifeSpan NFT");
}
return true;
}
function _authorizeUpgrade(address newImplementation)
internal
onlyRole(UPGRADER_ROLE)
override
{}
} | * @notice Set the maximum amount of tokens that a user can receive for the entire time @param amount new maximum amount/ | function setMaxReceiveAmount(uint256 amount) external onlyRole(OPERATOR_ROLE) {
maxReceiveAmount = amount;
}
| 13,121,745 | [
1,
694,
326,
4207,
3844,
434,
2430,
716,
279,
729,
848,
6798,
364,
326,
7278,
813,
225,
3844,
394,
4207,
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,
0,
0,
0,
0,
0,
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,
10851,
11323,
6275,
12,
11890,
5034,
3844,
13,
3903,
1338,
2996,
12,
26110,
67,
16256,
13,
288,
203,
3639,
943,
11323,
6275,
273,
3844,
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
]
|
./partial_match/1/0xF6DBad1123b638bd3bE811f6dd084a2488429405/sources/BaboonVC.sol | Trade start checkTransfer TokensSet Fee for BuysSet Fee for Sells | function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (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(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)) {
_VentureFee = _VentureFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_VentureFee = _VentureFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
| 16,146,234 | [
1,
22583,
787,
866,
5912,
13899,
694,
30174,
364,
605,
89,
1900,
694,
30174,
364,
348,
1165,
87,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3238,
288,
203,
3639,
2583,
12,
2080,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
5912,
3844,
1297,
506,
6802,
2353,
3634,
8863,
203,
203,
3639,
309,
261,
2080,
480,
3410,
1435,
597,
358,
480,
3410,
10756,
288,
203,
203,
5411,
309,
16051,
313,
14968,
3678,
13,
288,
203,
7734,
2583,
12,
2080,
422,
3410,
9334,
315,
8412,
30,
1220,
2236,
2780,
1366,
2430,
3180,
1284,
7459,
353,
3696,
8863,
203,
5411,
289,
203,
203,
5411,
2583,
12,
8949,
1648,
389,
1896,
4188,
6275,
16,
315,
8412,
30,
4238,
5947,
7214,
8863,
203,
5411,
2583,
12,
5,
4819,
87,
63,
2080,
65,
597,
401,
4819,
87,
63,
869,
6487,
315,
8412,
30,
20471,
2236,
353,
25350,
4442,
1769,
203,
203,
5411,
309,
12,
869,
480,
640,
291,
91,
438,
58,
22,
4154,
13,
288,
203,
7734,
2583,
12,
12296,
951,
12,
869,
13,
397,
3844,
411,
389,
1896,
16936,
1225,
16,
315,
8412,
30,
30918,
14399,
9230,
963,
4442,
1769,
203,
5411,
289,
203,
203,
5411,
2254,
5034,
6835,
1345,
13937,
273,
11013,
951,
12,
2867,
12,
2211,
10019,
203,
5411,
1426,
848,
12521,
273,
6835,
1345,
13937,
1545,
389,
22270,
5157,
861,
2
]
|
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
contract NFTLocker {
event ERC721Released(address indexed nft);
uint256 private _released;
address private immutable _beneficiary;
uint64 private immutable _start;
uint64 private immutable _duration;
address private _nft;
uint256 private immutable _tokenId;
IERC721 private NFT;
constructor(
address beneficiaryAddress,
// uint64 startTimestamp,
uint64 durationSeconds,
address nft,
uint256 tokenId
){
_beneficiary = beneficiaryAddress;
// _start = startTimestamp;
_start = uint64(block.timestamp);
_duration = durationSeconds;
_nft = nft;
NFT = IERC721(_nft);
_tokenId =tokenId;
}
function start() public view virtual returns (uint256) {
return _start;
}
function duration() public view virtual returns (uint256) {
return _duration;
}
/**
* @dev Release the NFT if it has vested.
*/
function release() public {
bool releasable = _isVested(block.timestamp);
require(releasable == true, "NFT has not vested yet.");
NFT.transferFrom(address(this), _beneficiary, _tokenId);
emit ERC721Released(_nft);
}
function _isVested(uint256 timestamp) internal view virtual returns (bool vested) {
if (timestamp > start() + duration()) {
return true;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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);
} | * @dev Release the NFT if it has vested./ | function release() public {
bool releasable = _isVested(block.timestamp);
require(releasable == true, "NFT has not vested yet.");
NFT.transferFrom(address(this), _beneficiary, _tokenId);
emit ERC721Released(_nft);
}
| 14,485,779 | [
1,
7391,
326,
423,
4464,
309,
518,
711,
331,
3149,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
3992,
1435,
1071,
288,
203,
3639,
1426,
6707,
345,
429,
273,
389,
291,
58,
3149,
12,
2629,
18,
5508,
1769,
203,
3639,
2583,
12,
16599,
345,
429,
422,
638,
16,
315,
50,
4464,
711,
486,
331,
3149,
4671,
1199,
1769,
203,
203,
3639,
423,
4464,
18,
13866,
1265,
12,
2867,
12,
2211,
3631,
389,
70,
4009,
74,
14463,
814,
16,
389,
2316,
548,
1769,
203,
3639,
3626,
4232,
39,
27,
5340,
26363,
24899,
82,
1222,
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
]
|
./full_match/1/0xb6ac852b4aF99d5ED4775964BB359bf68e9ECB85/sources/node_modules/@sablier/v2-core/src/types/DataTypes.sol | @notice Lockup Linear stream. @dev The fields are arranged like this to save gas via tight variable packing. @param sender The address streaming the assets, with the ability to cancel the stream. @param startTime The Unix timestamp indicating the stream's start. @param cliffTime The Unix timestamp indicating the cliff period's end. @param isCancelable Boolean indicating if the stream is cancelable. @param wasCanceled Boolean indicating if the stream was canceled. @param asset The contract address of the ERC-20 asset used for streaming. @param endTime The Unix timestamp indicating the stream's end. @param isDepleted Boolean indicating if the stream is depleted. @param isStream Boolean indicating if the struct entity exists. @param amounts Struct containing the deposit, withdrawn, and refunded amounts, all denoted in units of the asset's decimals. slot 0 slot 1 slot 2 and 3 | struct Stream {
address sender;
uint40 startTime;
uint40 cliffTime;
bool isCancelable;
bool wasCanceled;
IERC20 asset;
uint40 endTime;
bool isDepleted;
bool isStream;
Lockup.Amounts amounts;
}
| 2,997,787 | [
1,
2531,
416,
13921,
1407,
18,
225,
1021,
1466,
854,
2454,
2330,
3007,
333,
358,
1923,
16189,
3970,
26066,
2190,
2298,
310,
18,
225,
5793,
1021,
1758,
12833,
326,
7176,
16,
598,
326,
7123,
358,
3755,
326,
1407,
18,
225,
8657,
1021,
9480,
2858,
11193,
326,
1407,
1807,
787,
18,
225,
927,
3048,
950,
1021,
9480,
2858,
11193,
326,
927,
3048,
3879,
1807,
679,
18,
225,
353,
6691,
429,
3411,
11193,
309,
326,
1407,
353,
3755,
429,
18,
225,
1703,
23163,
3411,
11193,
309,
326,
1407,
1703,
17271,
18,
225,
3310,
1021,
6835,
1758,
434,
326,
4232,
39,
17,
3462,
3310,
1399,
364,
12833,
18,
225,
13859,
1021,
9480,
2858,
11193,
326,
1407,
1807,
679,
18,
225,
353,
758,
1469,
329,
3411,
11193,
309,
326,
1407,
353,
443,
1469,
329,
18,
225,
353,
1228,
3411,
11193,
309,
326,
1958,
1522,
1704,
18,
225,
30980,
7362,
4191,
326,
443,
1724,
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,
1958,
3961,
288,
203,
3639,
1758,
5793,
31,
203,
3639,
2254,
7132,
8657,
31,
203,
3639,
2254,
7132,
927,
3048,
950,
31,
203,
3639,
1426,
353,
6691,
429,
31,
203,
3639,
1426,
1703,
23163,
31,
203,
3639,
467,
654,
39,
3462,
3310,
31,
203,
3639,
2254,
7132,
13859,
31,
203,
3639,
1426,
353,
758,
1469,
329,
31,
203,
3639,
1426,
353,
1228,
31,
203,
3639,
3488,
416,
18,
6275,
87,
30980,
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
]
|
./partial_match/1/0x63f73B69D9DC00308021D2a1b33cEb1Adc6bE4f9/sources/CLICrowdsale.sol | @notice allows to do signed contributions | function contribute(
uint8 _v,
bytes32 _r,
bytes32 _s
)
external
payable
{
address recoveredAddress = verify(
msg.sender,
_v,
_r,
_s
);
require(hasPermission(recoveredAddress, SIGNERS), ERROR_ACCESS_DENIED);
internalContribution(
msg.sender,
PricingStrategy(management.contractRegistry(CONTRACT_PRICING)).getCurrencyAmount(msg.value)
);
}
| 16,064,300 | [
1,
5965,
87,
358,
741,
6726,
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,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
356,
887,
12,
203,
3639,
2254,
28,
389,
90,
16,
203,
3639,
1731,
1578,
389,
86,
16,
203,
3639,
1731,
1578,
389,
87,
203,
565,
262,
203,
3639,
3903,
203,
3639,
8843,
429,
203,
565,
288,
203,
3639,
1758,
24616,
1887,
273,
3929,
12,
203,
5411,
1234,
18,
15330,
16,
203,
5411,
389,
90,
16,
203,
5411,
389,
86,
16,
203,
5411,
389,
87,
203,
3639,
11272,
203,
203,
3639,
2583,
12,
5332,
5041,
12,
266,
16810,
1887,
16,
12057,
11367,
3631,
5475,
67,
13204,
67,
13296,
29229,
1769,
203,
3639,
2713,
442,
4027,
12,
203,
5411,
1234,
18,
15330,
16,
203,
5411,
453,
1512,
25866,
12,
17381,
18,
16351,
4243,
12,
6067,
2849,
1268,
67,
7698,
39,
1360,
13,
2934,
588,
7623,
6275,
12,
3576,
18,
1132,
13,
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,
-100,
-100,
-100,
-100,
-100,
-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.3;
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/*
* @title BARIS ATALAY
* @dev Set & change owner
*
* @IMPORTANT Reward tokens to be distributed to the stakers must be deposited into the contract.
*
*/
contract DynamicAssetStake is Context, Ownable{
event Stake(address indexed from, uint256 amount);
event UnStake(address indexed from, uint256 amount);
event YieldWithdraw(address indexed to);
struct PendingRewardResponse{ // Model of showing pending awards
bytes32 name; // Byte equivalent of the name of the pool token
uint256 amount; // TODO...
uint id; // Id of Reward
}
struct RewardDef{
address tokenAddress; // Contract Address of Reward token
uint256 rewardPerSecond; // Accepted reward per second
bytes32 name; // Byte equivalent of the name of the pool token
uint8 feeRate; // Fee Rate for Reward Harvest
uint id; // Id of Reward
}
struct PoolDef{
address tokenAddress; // Contract Address of Pool token
uint rewardCount; // Amount of the reward to be won from the pool
uint id; // Id of pool
bool active; // Pool active status
}
struct PoolDefExt{
uint256 expiryTime; // The pool remains active until the set time
uint256 createTime; // Pool creation time
bytes32 name; // Byte equivalent of the name of the pool token
}
struct PoolVariable{ // Only owner can edit
uint256 balanceFee; // Withdraw Fee for contract Owner;
uint256 lastRewardTimeStamp; // Last date reward was calculated
uint8 feeRate; // Fee Rate for UnStake
}
struct PoolRewardVariable{
uint256 accTokenPerShare; // Token share to be distributed to users
uint256 balance; // Pool Contract Token Balance
}
// Info of each user
struct UserDef{
address id; // Wallet Address of staker
uint256 stakingBalance; // Amount of current staking balance
uint256 startTime; // Staking start time
}
struct UserRewardInfo{
uint256 rewardBalance;
}
uint private stakeIDCounter;
//Pool ID => PoolDef
mapping(uint => PoolDef) public poolList;
//Pool ID => Underused Pool information
mapping(uint => PoolDefExt) public poolListExtras;
//Pool ID => Pool Variable info
mapping(uint => PoolVariable) public poolVariable;
//Pool ID => (RewardIndex => RewardDef)
mapping(uint => mapping(uint => RewardDef)) public poolRewardList;
//Pool ID => (RewardIndex => PoolRewardVariable)
mapping(uint => mapping(uint => PoolRewardVariable)) public poolRewardVariableInfo;
//Pool ID => (RewardIndex => Amount of distributed reward to staker)
mapping(uint => mapping(uint => uint)) public poolPaidOut;
//Pool ID => Amount of Stake from User
mapping(uint => uint) public poolTotalStake;
//Pool ID => (User ID => User Info)
mapping(uint => mapping(address => UserDef)) poolUserInfo;
//Pool ID => (User ID => (Reward Id => Reward Info))
mapping (uint => mapping(address => mapping(uint => UserRewardInfo))) poolUserRewardInfo;
using SafeMath for uint;
using SafeERC20 for IERC20;
constructor(){
stakeIDCounter = 0;
}
/// @notice Updates the deserved rewards in the pool
/// @param _stakeID Id of the stake pool
function UpdatePoolRewardShare(uint _stakeID) internal virtual {
uint256 lastTimeStamp = block.timestamp;
PoolVariable storage selectedPoolVariable = poolVariable[_stakeID];
if (lastTimeStamp <= selectedPoolVariable.lastRewardTimeStamp) {
lastTimeStamp = selectedPoolVariable.lastRewardTimeStamp;
}
if (poolTotalStake[_stakeID] == 0) {
selectedPoolVariable.lastRewardTimeStamp = block.timestamp;
return;
}
uint256 timeDiff = lastTimeStamp.sub(selectedPoolVariable.lastRewardTimeStamp);
//..:: Calculating the reward shares of the pool ::..
uint rewardCount = poolList[_stakeID].rewardCount;
for (uint i=0; i<rewardCount; i++) {
uint256 currentReward = timeDiff.mul(poolRewardList[_stakeID][i].rewardPerSecond);
poolRewardVariableInfo[_stakeID][i].accTokenPerShare = poolRewardVariableInfo[_stakeID][i].accTokenPerShare.add(currentReward.mul(1e36).div(poolTotalStake[_stakeID]));
}
//..:: Calculating the reward shares of the pool ::..
selectedPoolVariable.lastRewardTimeStamp = block.timestamp;
}
/// @notice Lists the rewards of the transacting user in the pool
/// @param _stakeID Id of the stake pool
/// @return Reward model list
function showPendingReward(uint _stakeID) public virtual view returns(PendingRewardResponse[] memory) {
UserDef memory user = poolUserInfo[_stakeID][_msgSender()];
uint256 lastTimeStamp = block.timestamp;
uint rewardCount = poolList[_stakeID].rewardCount;
PendingRewardResponse[] memory result = new PendingRewardResponse[](rewardCount);
for (uint RewardIndex=0; RewardIndex<rewardCount; RewardIndex++) {
uint _accTokenPerShare = poolRewardVariableInfo[_stakeID][RewardIndex].accTokenPerShare;
if (lastTimeStamp > poolVariable[_stakeID].lastRewardTimeStamp && poolTotalStake[_stakeID] != 0) {
uint256 timeDiff = lastTimeStamp.sub(poolVariable[_stakeID].lastRewardTimeStamp);
uint256 currentReward = timeDiff.mul(poolRewardList[_stakeID][RewardIndex].rewardPerSecond);
_accTokenPerShare = _accTokenPerShare.add(currentReward.mul(1e36).div(poolTotalStake[_stakeID]));
}
result[RewardIndex] = PendingRewardResponse({
id: RewardIndex,
name: poolRewardList[_stakeID][RewardIndex].name,
amount: user.stakingBalance
.mul(_accTokenPerShare)
.div(1e36)
.sub(poolUserRewardInfo[_stakeID][_msgSender()][RewardIndex].rewardBalance)
});
}
return result;
}
/// @notice Withdraw assets by pool id
/// @param _stakeID Id of the stake pool
/// @param _amount Amount of withdraw asset
function unStake(uint _stakeID, uint256 _amount) public {
require(_msgSender() != address(0), "Stake: Staker address not specified!");
//IERC20 selectedToken = getStakeContract(_stakeID);
UserDef storage user = poolUserInfo[_stakeID][_msgSender()];
require(user.stakingBalance > 0, "Stake: does not have staking balance");
// Amount leak control
if (_amount > user.stakingBalance) _amount = user.stakingBalance;
// "_amount" removed to Total staked value by Pool ID
if (_amount > 0)
poolTotalStake[_stakeID] = poolTotalStake[_stakeID].sub(_amount);
UpdatePoolRewardShare(_stakeID);
sendPendingReward(_stakeID, user, true);
uint256 unStakeFee;
if (poolVariable[_stakeID].feeRate > 0)
unStakeFee = _amount
.mul(poolVariable[_stakeID].feeRate)
.div(100);
// Calculated unStake amount after commission deducted
uint256 finalUnStakeAmount = _amount.sub(unStakeFee);
// ..:: Updated last user info ::..
user.startTime = block.timestamp;
user.stakingBalance = user.stakingBalance.sub(_amount);
// ..:: Updated last user info ::..
if (finalUnStakeAmount > 0)
getStakeContract(_stakeID).safeTransfer(_msgSender(), finalUnStakeAmount);
emit UnStake(_msgSender(), _amount);
}
/// @notice Structure that calculates rewards to be distributed for users
/// @param _stakeID Id of the stake pool
/// @param _user Staker info
/// @param _subtractFee If the value is true, the commission is subtracted when calculating the reward.
function sendPendingReward(uint _stakeID, UserDef memory _user, bool _subtractFee) private {
// ..:: Pending reward will be calculate and add to transferAmount, before transfer unStake amount ::..
uint rewardCount = poolList[_stakeID].rewardCount;
for (uint RewardIndex=0; RewardIndex<rewardCount; RewardIndex++) {
uint256 userRewardedBalance = poolUserRewardInfo[_stakeID][_msgSender()][RewardIndex].rewardBalance;
uint pendingAmount = _user.stakingBalance
.mul(poolRewardVariableInfo[_stakeID][RewardIndex].accTokenPerShare)
.div(1e36)
.sub(userRewardedBalance);
if (pendingAmount > 0) {
uint256 finalRewardAmount = pendingAmount;
if (_subtractFee){
uint256 pendingRewardFee;
if (poolRewardList[_stakeID][RewardIndex].feeRate > 0)
pendingRewardFee = pendingAmount
.mul(poolRewardList[_stakeID][RewardIndex].feeRate)
.div(100);
// Commission fees received are recorded for reporting
poolVariable[_stakeID].balanceFee = poolVariable[_stakeID].balanceFee.add(pendingRewardFee);
// Calculated reward after commission deducted
finalRewardAmount = pendingAmount.sub(pendingRewardFee);
}
//Reward distribution
getRewardTokenContract(_stakeID, RewardIndex).safeTransfer(_msgSender(), finalRewardAmount);
// Updating balance pending to be distributed from contract to users
poolRewardVariableInfo[_stakeID][RewardIndex].balance = poolRewardVariableInfo[_stakeID][RewardIndex].balance.sub(pendingAmount);
// The amount distributed to users is reported
poolPaidOut[_stakeID][RewardIndex] = poolPaidOut[_stakeID][RewardIndex].add(pendingAmount);
}
}
}
/// @notice Deposits assets by pool id
/// @param _stakeID Id of the stake pool
/// @param _amount Amount of deposit asset
function stake(uint _stakeID, uint256 _amount) public{
IERC20 selectedToken = getStakeContract(_stakeID);
require(selectedToken.allowance(_msgSender(), address(this)) > 0, "Stake: No balance allocated for Allowance!");
require(_amount > 0 && selectedToken.balanceOf(_msgSender()) >= _amount, "Stake: You cannot stake zero tokens");
UserDef storage user = poolUserInfo[_stakeID][_msgSender()];
// Amount leak control
if (_amount > selectedToken.balanceOf(_msgSender()))
_amount = selectedToken.balanceOf(_msgSender());
// Amount transfer to address(this)
selectedToken.safeTransferFrom(_msgSender(), address(this), _amount);
UpdatePoolRewardShare(_stakeID);
if (user.stakingBalance > 0)
sendPendingReward(_stakeID, user, false);
// "_amount" added to Total staked value by Pool ID
poolTotalStake[_stakeID] = poolTotalStake[_stakeID].add(_amount);
// "_amount" added to USER Total staked value by Pool ID
user.stakingBalance = user.stakingBalance.add(_amount);
// ..:: Calculating the rewards user pool deserve ::..
uint rewardCount = poolList[_stakeID].rewardCount;
for (uint i=0; i<rewardCount; i++) {
poolUserRewardInfo[_stakeID][_msgSender()][i].rewardBalance = user.stakingBalance.mul(poolRewardVariableInfo[_stakeID][i].accTokenPerShare).div(1e36);
}
// ..:: Calculating the rewards user pool deserve ::..
emit Stake(_msgSender(), _amount);
}
/// @notice Returns staked token balance by pool id
/// @param _stakeID Id of the stake pool
/// @param _account Address of the staker
/// @return Count of staked balance
function balanceOf(uint _stakeID, address _account) public view returns (uint256) {
return poolUserInfo[_stakeID][_account].stakingBalance;
}
/// @notice Returns Stake Poll Contract casted IERC20 interface by pool id
/// @param _stakeID Id of the stake pool
function getStakeContract(uint _stakeID) internal view returns(IERC20){
require(poolListExtras[_stakeID].name!="", "Stake: Selected contract is not valid");
require(poolList[_stakeID].active,"Stake: Selected contract is not active");
return IERC20(poolList[_stakeID].tokenAddress);
}
/// @notice Returns rewarded token address
/// @param _stakeID Id of the stake pool
/// @param _rewardID Id of the reward
/// @return Token contract
function getRewardTokenContract(uint _stakeID, uint _rewardID) internal view returns(IERC20){
return IERC20(poolRewardList[_stakeID][_rewardID].tokenAddress);
}
/// @notice Checks the address has a stake
/// @param _stakeID Id of the stake pool
/// @param _user Address of the staker
/// @return Value of stake status
function isStaking(uint _stakeID, address _user) view public returns(bool){
return poolUserInfo[_stakeID][_user].stakingBalance > 0;
}
/// @notice Returns stake asset list of active
function getPoolList() public view returns(PoolDef[] memory, PoolDefExt[] memory){
uint length = stakeIDCounter;
PoolDef[] memory result = new PoolDef[](length);
PoolDefExt[] memory resultExt = new PoolDefExt[](length);
for (uint i=0; i<length; i++) {
result[i] = poolList[i];
resultExt[i] = poolListExtras[i];
}
return (result, resultExt);
}
/// @notice Returns the pool's reward definition information
/// @param _stakeID Id of the stake pool
/// @return List of pool's reward definition
function getPoolRewardDefList(uint _stakeID) public view returns(RewardDef[] memory){
uint length = poolList[_stakeID].rewardCount;
RewardDef[] memory result = new RewardDef[](length);
for (uint i=0; i<length; i++) {
result[i] = poolRewardList[_stakeID][i];
}
return result;
}
/// @notice Returns the pool's reward definition information by pool id
/// @param _stakeID Id of the stake pool
/// @param _rewardID Id of the reward
/// @return pool's reward definition
function getPoolRewardDef(uint _stakeID, uint _rewardID) public view returns(RewardDef memory, PoolRewardVariable memory){
return (poolRewardList[_stakeID][_rewardID], poolRewardVariableInfo[_stakeID][_rewardID]);
}
/// @notice Returns stake pool
/// @param _stakeID Id of the stake pool
/// @return Definition of pool
function getPoolDefByID(uint _stakeID) public view returns(PoolDef memory){
require(poolListExtras[_stakeID].name!="", "Stake: Stake Asset is not valid");
return poolList[_stakeID];
}
/// @notice Adds new stake def to the pool
/// @param _poolAddress Address of the token pool
/// @param _poolName Name of the token pool
/// @param _rewards Rewards for the stakers
function addNewStakePool(address _poolAddress, bytes32 _poolName, RewardDef[] memory _rewards) onlyOwner public returns(uint){
require(_poolAddress != address(0), "Stake: New Staking Pool address not valid");
require(_poolName != "", "Stake: New Staking Pool name not valid");
uint length = _rewards.length;
for (uint i=0; i<length; i++) {
_rewards[i].id = i;
poolRewardList[stakeIDCounter][i] = _rewards[i];
}
poolList[stakeIDCounter] = PoolDef(_poolAddress, length, stakeIDCounter, false);
poolListExtras[stakeIDCounter] = PoolDefExt(block.timestamp, 0, _poolName);
poolVariable[stakeIDCounter] = PoolVariable(0, 0, 0);
stakeIDCounter++;
return stakeIDCounter.sub(1);
}
/// @notice Disables stake pool for user
/// @param _stakeID Id of the stake pool
function disableStakePool(uint _stakeID) public onlyOwner{
require(poolListExtras[_stakeID].name!="", "Stake: Contract is not valid");
require(poolList[_stakeID].active,"Stake: Contract is already disabled");
poolList[_stakeID].active = false;
}
/// @notice Enables stake pool for user
/// @param _stakeID Id of the stake pool
function enableStakePool(uint _stakeID) public onlyOwner{
require(poolListExtras[_stakeID].name!="", "Stake: Contract is not valid");
require(poolList[_stakeID].active==false,"Stake: Contract is already enabled");
poolList[_stakeID].active = true;
}
/// @notice Returns pool list count
/// @return Count of pool list
function getPoolCount() public view returns(uint){
return stakeIDCounter;
}
/// @notice The contract owner adds the reward she shared with the users here
/// @param _stakeID Id of the stake pool
/// @param _rewardID Id of the reward
/// @param _amount Amount of deposit to reward
function depositToRewardByPoolID(uint _stakeID, uint _rewardID, uint256 _amount) public onlyOwner returns(bool){
IERC20 selectedToken = getRewardTokenContract(_stakeID, _rewardID);
require(selectedToken.allowance(owner(), address(this)) > 0, "Stake: No balance allocated for Allowance!");
require(_amount > 0, "Stake: You cannot stake zero tokens");
require(address(this) != address(0), "Stake: Storage address did not set");
// Amount leak control
if (_amount > selectedToken.balanceOf(_msgSender()))
_amount = selectedToken.balanceOf(_msgSender());
// Amount transfer to address(this)
selectedToken.safeTransferFrom(_msgSender(), address(this), _amount);
poolRewardVariableInfo[_stakeID][_rewardID].balance = poolRewardVariableInfo[_stakeID][_rewardID].balance.add(_amount);
return true;
}
/// @notice The contract owner takes back the reward shared with the users here
/// @param _stakeID Id of the stake pool
/// @param _rewardID Id of the reward
/// @param _amount Amount of deposit to reward
function withdrawRewardByPoolID(uint _stakeID, uint _rewardID, uint256 _amount) public onlyOwner returns(bool){
poolRewardVariableInfo[_stakeID][_rewardID].balance = poolRewardVariableInfo[_stakeID][_rewardID].balance.sub(_amount);
IERC20 selectedToken = getRewardTokenContract(_stakeID, _rewardID);
selectedToken.safeTransfer(_msgSender(), _amount);
return true;
}
/// @notice ...
/// @param _stakeID Id of the stake pool
/// @param _rewardID Id of the reward
/// @param _rewardPerSecond New staking reward per second
function updateRewardPerSecond(uint _stakeID, uint _rewardID, uint256 _rewardPerSecond) public onlyOwner returns(bool){
RewardDef storage reward = poolRewardList[_stakeID][_rewardID];
require(reward.rewardPerSecond != _rewardPerSecond, "Reward per Second no change! Because it is same.");
reward.rewardPerSecond = _rewardPerSecond;
return true;
}
/// @return Returns number of reward to be distributed per second by pool id
function getRewardPerSecond(uint _stakeID, uint _rewardID) public view returns(uint256){
return poolRewardList[_stakeID][_rewardID].rewardPerSecond;
}
/// @notice ...
/// @param _stakeID Id of the stake pool
/// @param _rewardID Id of the reward
/// @param _feeRate New reward harvest fee
function updateRewardFeeRate(uint _stakeID, uint _rewardID, uint8 _feeRate) public onlyOwner returns(bool){
RewardDef storage reward = poolRewardList[_stakeID][_rewardID];
require(reward.feeRate != _feeRate, "FeeRate no change! Because it is same.");
reward.feeRate = _feeRate;
return true;
}
/// @notice ...
/// @param _stakeID Id of the stake pool
/// @param _feeRate New unStake fee
function updateUnStakeFeeRate(uint _stakeID, uint8 _feeRate) public onlyOwner returns(bool){
PoolVariable storage def = poolVariable[_stakeID];
require(def.feeRate != _feeRate, "UnStake FeeRate no change! Because it is same.");
def.feeRate = _feeRate;
return true;
}
/// @return Returns commission rate for Unstake transaction
function getUnStakeFeeRate(uint _stakeID)public view returns(uint8){
return poolVariable[_stakeID].feeRate;
}
/// @return Returns blockchain time
function getTime() public view returns(uint256){
return block.timestamp;
}
} | Byte equivalent of the name of the pool token
| bytes32 name; | 13,084,348 | [
1,
3216,
7680,
434,
326,
508,
434,
326,
2845,
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
]
| [
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,
1731,
1578,
508,
31,
13491,
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
]
|
/* Copyright (C) 2021 Soteria.fund
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.17;
import "../../abstract/Iupgradable.sol";
import "../../libraries/SafeMath.sol";
import "../cover/Quotation.sol";
import "./Pool2.sol";
contract Pool1 is Iupgradable {
using SafeMath for uint;
Quotation internal q2;
SOTEToken internal tk;
TokenController internal tc;
TokenFunctions internal tf;
Pool2 internal p2;
PoolData internal pd;
MCR internal m1;
Claims public c1;
TokenData internal td;
bool internal locked;
uint internal constant DECIMAL1E18 = uint(10) ** 18;
uint public pumpMo;
address public pumpAddress;
// uint internal constant PRICE_STEP = uint(1000) * DECIMAL1E18;
event Apiresult(address indexed sender, string msg, bytes32 myid);
event Payout(address indexed to, uint coverId, uint tokens);
modifier noReentrancy() {
require(!locked, "Reentrant call.");
locked = true;
_;
locked = false;
}
constructor(address _pumpAddress,uint _pumpMo) public {
pumpAddress = _pumpAddress;
pumpMo = _pumpMo;
}
function () external payable {} //solhint-disable-line
/**
* @dev Pays out the sum assured in case a claim is accepted
* @param coverid Cover Id.
* @param claimid Claim Id.
* @return succ true if payout is successful, false otherwise.
*/
function sendClaimPayout(
uint coverid,
uint claimid,
uint sumAssured,
address payable coverHolder,
bytes4 coverCurr
)
external
onlyInternal
noReentrancy
returns(bool succ)
{
uint sa = sumAssured.div(DECIMAL1E18);
bool check;
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr));
//Payout
if (coverCurr == "BNB" && address(this).balance >= sumAssured) {
// check = _transferCurrencyAsset(coverCurr, coverHolder, sumAssured);
coverHolder.transfer(sumAssured);
check = true;
} else if (coverCurr == "DAI" && erc20.balanceOf(address(this)) >= sumAssured) {
erc20.transfer(coverHolder, sumAssured);
check = true;
}
if (check == true) {
q2.removeSAFromCSA(coverid, sa);
pd.changeCurrencyAssetVarMin(coverCurr,
pd.getCurrencyAssetVarMin(coverCurr).sub(sumAssured));
emit Payout(coverHolder, coverid, sumAssured);
succ = true;
} else {
c1.setClaimStatus(claimid, 12);
}
_triggerExternalLiquidityTrade();
// p2.internalLiquiditySwap(coverCurr);
tf.burnStakerLockedToken(coverid, coverCurr, sumAssured);
}
/**
* @dev to trigger external liquidity trade
*/
function triggerExternalLiquidityTrade() external onlyInternal {
_triggerExternalLiquidityTrade();
}
///@dev Oraclize call to close emergency pause.
function closeEmergencyPause(uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery();
_saveApiDetails(myid, "EP", 0);
}
/// @dev Calls the Oraclize Query to close a given Claim after a given period of time.
/// @param id Claim Id to be closed
/// @param time Time (in seconds) after which Claims assessment voting needs to be closed
function closeClaimsOraclise(uint id, uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery();
_saveApiDetails(myid, "CLA", id);
}
/// @dev Calls Oraclize Query to expire a given Cover after a given period of time.
/// @param id Quote Id to be expired
/// @param time Time (in seconds) after which the cover should be expired
function closeCoverOraclise(uint id, uint64 time) external onlyInternal {
bytes32 myid = _oraclizeQuery();
_saveApiDetails(myid, "COV", id);
}
/// @dev Calls the Oraclize Query to initiate MCR calculation.
/// @param time Time (in milliseconds) after which the next MCR calculation should be initiated
function mcrOraclise(uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery();
_saveApiDetails(myid, "MCR", 0);
}
/// @dev Calls the Oraclize Query in case MCR calculation fails.
/// @param time Time (in seconds) after which the next MCR calculation should be initiated
function mcrOracliseFail(uint id, uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery();
_saveApiDetails(myid, "MCRF", id);
}
/// @dev Oraclize call to update investment asset rates.
function saveIADetailsOracalise(uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery();
_saveApiDetails(myid, "IARB", 0);
}
/**
* @dev Transfers all assest (i.e BNB balance, Currency Assest) from old Pool to new Pool
* @param newPoolAddress Address of the new Pool
*/
function upgradeCapitalPool(address payable newPoolAddress) external noReentrancy onlyInternal {
// for (uint64 i = 1; i < pd.getAllCurrenciesLen(); i++) {
// bytes4 caName = pd.getCurrenciesByIndex(i);
// _upgradeCapitalPool(caName, newPoolAddress);
// }
if (address(this).balance > 0) {
Pool1 newP1 = Pool1(newPoolAddress);
newP1.sendEther.value(address(this).balance)();
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public {
m1 = MCR(ms.getLatestAddress("MC"));
tk = SOTEToken(ms.tokenAddress());
tf = TokenFunctions(ms.getLatestAddress("TF"));
tc = TokenController(ms.getLatestAddress("TC"));
pd = PoolData(ms.getLatestAddress("PD"));
q2 = Quotation(ms.getLatestAddress("QT"));
p2 = Pool2(ms.getLatestAddress("P2"));
c1 = Claims(ms.getLatestAddress("CL"));
td = TokenData(ms.getLatestAddress("TD"));
}
function sendEther() public payable {
}
/**
* @dev transfers currency asset to an address
* @param curr is the currency of currency asset to transfer
* @param amount is amount of currency asset to transfer
* @return boolean to represent success or failure
*/
function transferCurrencyAsset(
bytes4 curr,
uint amount
)
public
onlyInternal
noReentrancy
returns(bool)
{
return _transferCurrencyAsset(curr, amount);
}
/// @dev Handles callback of external oracle query.
function __callback(bytes32 myid, string memory result) public {
result; //silence compiler warning
// owner will be removed from production build
ms.delegateCallBack(myid);
}
/// @dev Enables user to purchase cover with funding in BNB.
/// @param smartCAdd Smart Contract Address
function makeCoverBegin(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
isMember
checkPause
payable
{
require(msg.value == coverDetails[1]);
q2.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
isMember
checkPause
{
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr));
require(erc20.transferFrom(msg.sender, address(this), coverDetails[1]), "Transfer failed");
q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
/// @dev Enables user to purchase SOTE at the current token price.
function buyToken() public payable isMember checkPause returns(bool success) {
require(msg.value > 0);
uint tokenPurchased = _getToken(address(this).balance, msg.value);
tc.mint(msg.sender, tokenPurchased);
tc.mint(pumpAddress,tokenPurchased.div(100).mul(pumpMo));
success = true;
}
function _changePumpMo(uint val) internal onlyInternal{
pumpMo = val;
}
function _changePumpAddress (address _newOwnerAddress) internal onlyInternal {
pumpAddress = _newOwnerAddress;
}
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "PUMPMO") {
val = pumpMo;
}
}
/**
* @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 == "PUMPMO") {
_changePumpMo(val);
}
}
function getOwnerParameters(bytes8 code) external view returns (bytes8 codeVal, address val) {
codeVal = code;
if (code == "PUMPAD") {
val = pumpAddress;
}
}
/**
* @dev to update the owner parameters
* @param code is the associated code
* @param val is value to be set
*/
function updateAddressParameters(bytes8 code, address payable val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "PUMPAD") {
_changePumpAddress(val);
}
}
/// @dev Sends a given amount of Ether to a given address.
/// @param amount amount (in wei) to send.
/// @param _add Receiver's address.
/// @return succ True if transfer is a success, otherwise False.
function transferEther(uint amount, address payable _add) public noReentrancy checkPause returns(bool succ) {
require(ms.checkIsAuthToGoverned(msg.sender), "Not authorized to Govern");
succ = _add.send(amount);
}
/**
* @dev Allows selling of SOTE for ether.
* Seller first needs to give this contract allowance to
* transfer/burn tokens in the SOTEToken contract
* @param _amount Amount of SOTE to sell
* @return success returns true on successfull sale
*/
function sellSOTETokens(uint _amount) public isMember noReentrancy checkPause returns(bool success) {
require(tk.balanceOf(msg.sender) >= _amount, "Not enough balance");
require(!tf.isLockedForMemberVote(msg.sender), "Member voted");
require(_amount <= m1.getMaxSellTokens(), "exceeds maximum token sell limit");
uint sellingPrice = _getWei(_amount);
tc.burnFrom(msg.sender, _amount);
msg.sender.transfer(sellingPrice);
success = true;
}
/**
* @dev gives the investment asset balance
* @return investment asset balance
*/
function getInvestmentAssetBalance() public view returns (uint balance) {
IERC20 erc20;
uint currTokens;
for (uint i = 1; i < pd.getInvestmentCurrencyLen(); i++) {
bytes4 currency = pd.getInvestmentCurrencyByIndex(i);
erc20 = IERC20(pd.getInvestmentAssetAddress(currency));
currTokens = erc20.balanceOf(address(p2));
if (pd.getIAAvgRate(currency) > 0)
balance = balance.add((currTokens.mul(100)).div(pd.getIAAvgRate(currency)));
}
balance = balance.add(address(p2).balance);
}
/**
* @dev Returns the amount of wei a seller will get for selling SOTE
* @param amount Amount of SOTE to sell
* @return weiToPay Amount of wei the seller will get
*/
function getWei(uint amount) public view returns(uint weiToPay) {
return _getWei(amount);
}
/**
* @dev Returns the amount of token a buyer will get for corresponding wei
* @param weiPaid Amount of wei
* @return tokenToGet Amount of tokens the buyer will get
*/
function getToken(uint weiPaid) public view returns(uint tokenToGet) {
return _getToken((address(this).balance).add(weiPaid), weiPaid);
}
/**
* @dev to trigger external liquidity trade
*/
function _triggerExternalLiquidityTrade() internal {
if (now > pd.lastLiquidityTradeTrigger().add(pd.liquidityTradeCallbackTime())) {
pd.setLastLiquidityTradeTrigger();
}
}
/**
* @dev Returns the amount of wei a seller will get for selling SOTE
* @param _amount Amount of SOTE to sell
* @return weiToPay Amount of wei the seller will get
*/
function _getWei(uint _amount) internal view returns(uint weiToPay) {
uint tokenPrice;
uint weiPaid;
uint tokenSupply = tk.totalSupply();
uint vtp;
uint mcrFullperc;
uint vFull;
uint mcrtp;
(mcrFullperc, , vFull, ) = pd.getLastMCR();
(vtp, ) = m1.calVtpAndMCRtp();
while (_amount > 0) {
mcrtp = (mcrFullperc.mul(vtp)).div(vFull);
tokenPrice = m1.calculateStepTokenPrice("BNB", mcrtp);
tokenPrice = (tokenPrice.mul(975)).div(1000); //97.5%
if (_amount <= td.priceStep().mul(DECIMAL1E18)) {
weiToPay = weiToPay.add((tokenPrice.mul(_amount)).div(DECIMAL1E18));
break;
} else {
_amount = _amount.sub(td.priceStep().mul(DECIMAL1E18));
tokenSupply = tokenSupply.sub(td.priceStep().mul(DECIMAL1E18));
weiPaid = (tokenPrice.mul(td.priceStep().mul(DECIMAL1E18))).div(DECIMAL1E18);
vtp = vtp.sub(weiPaid);
weiToPay = weiToPay.add(weiPaid);
}
}
}
/**
* @dev gives the token
* @param _poolBalance is the pool balance
* @param _weiPaid is the amount paid in wei
* @return the token to get
*/
function _getToken(uint _poolBalance, uint _weiPaid) internal view returns(uint tokenToGet) {
uint tokenPrice;
uint superWeiLeft = (_weiPaid).mul(DECIMAL1E18);
uint tempTokens;
uint superWeiSpent;
uint tokenSupply = tk.totalSupply();
uint vtp;
uint mcrFullperc;
uint vFull;
uint mcrtp;
(mcrFullperc, , vFull, ) = pd.getLastMCR();
(vtp, ) = m1.calculateVtpAndMCRtp((_poolBalance).sub(_weiPaid));
require(m1.calculateTokenPrice("BNB") > 0, "Token price can not be zero");
while (superWeiLeft > 0) {
mcrtp = (mcrFullperc.mul(vtp)).div(vFull);
tokenPrice = m1.calculateStepTokenPrice("BNB", mcrtp);
tempTokens = superWeiLeft.div(tokenPrice);
if (tempTokens <= td.priceStep().mul(DECIMAL1E18)) {
tokenToGet = tokenToGet.add(tempTokens);
break;
} else {
tokenToGet = tokenToGet.add(td.priceStep().mul(DECIMAL1E18));
tokenSupply = tokenSupply.add(td.priceStep().mul(DECIMAL1E18));
superWeiSpent = td.priceStep().mul(DECIMAL1E18).mul(tokenPrice);
superWeiLeft = superWeiLeft.sub(superWeiSpent);
vtp = vtp.add((td.priceStep().mul(DECIMAL1E18).mul(tokenPrice)).div(DECIMAL1E18));
}
}
}
/**
* @dev Save the details of the Oraclize API.
* @param myid Id return by the oraclize query.
* @param _typeof type of the query for which oraclize call is made.
* @param id ID of the proposal, quote, cover etc. for which oraclize call is made.
*/
function _saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) internal {
pd.saveApiDetails(myid, _typeof, id);
pd.addInAllApiCall(myid);
}
/**
* @dev transfers currency asset
* @param _curr is currency of asset to transfer
* @param _amount is the amount to be transferred
* @return boolean representing the success of transfer
*/
function _transferCurrencyAsset(bytes4 _curr, uint _amount) internal returns(bool succ) {
if (_curr == "BNB") {
if (address(this).balance < _amount)
_amount = address(this).balance;
p2.sendEther.value(_amount)();
succ = true;
} else {
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); //solhint-disable-line
if (erc20.balanceOf(address(this)) < _amount)
_amount = erc20.balanceOf(address(this));
require(erc20.transfer(address(p2), _amount));
succ = true;
}
}
/**
* @dev Transfers ERC20 Currency asset from this Pool to another Pool on upgrade.
*/
function _upgradeCapitalPool(
bytes4 _curr,
address _newPoolAddress
)
internal
{
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr));
if (erc20.balanceOf(address(this)) > 0)
require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this))));
}
// step for ApiId
uint256 public reqc;
/**
* @dev oraclize query
* @return id of oraclize query
*/
function _oraclizeQuery()
internal
returns (bytes32 id)
{
id = keccak256(abi.encodePacked(this, msg.sender, reqc));
reqc++;
}
}
| @dev Enables user to purchase cover with funding in BNB. @param smartCAdd Smart Contract Address | function makeCoverBegin(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
isMember
checkPause
payable
{
require(msg.value == coverDetails[1]);
q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
| 6,484,396 | [
1,
25924,
729,
358,
23701,
5590,
598,
22058,
316,
605,
20626,
18,
225,
13706,
39,
986,
19656,
13456,
5267,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1221,
8084,
8149,
12,
203,
3639,
1758,
13706,
39,
986,
16,
203,
3639,
1731,
24,
5590,
20143,
16,
203,
3639,
2254,
8526,
3778,
5590,
3790,
16,
203,
3639,
2254,
2313,
5590,
5027,
16,
203,
3639,
2254,
28,
389,
90,
16,
203,
3639,
1731,
1578,
389,
86,
16,
203,
3639,
1731,
1578,
389,
87,
203,
565,
262,
203,
3639,
1071,
203,
3639,
353,
4419,
203,
3639,
866,
19205,
203,
3639,
8843,
429,
203,
565,
288,
203,
3639,
2583,
12,
3576,
18,
1132,
422,
5590,
3790,
63,
21,
19226,
203,
3639,
1043,
22,
18,
8705,
8084,
3790,
12,
3576,
18,
15330,
16,
13706,
39,
986,
16,
5590,
20143,
16,
5590,
3790,
16,
5590,
5027,
16,
389,
90,
16,
389,
86,
16,
389,
87,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.10;
library SafeMath {
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);
}
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
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);
}
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
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 (bytes32 );
function symbol() external pure returns (bytes32 );
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;
}
// IVC (Internal Virtual Chain)
// (c) Kaiba DeFi DAO 2021
// This source code is distributed under the CC-BY-ND-4.0 License https://spdx.org/licenses/CC-BY-ND-4.0.html#licenseText
interface ERC20 {
function totalSupply() external view returns (uint);
function balanceOf(address tokenOwner) external view returns (uint balance);
function allowance(address tokenOwner, address spender) external view returns (uint remaining);
function transfer(address to, uint tokens) external returns (bool success);
function approve(address spender, uint tokens) external returns (bool success);
function transferFrom(address from, address to, uint tokens) external returns (bool success);
function symbol() external view returns (bytes32 );
function name() external view returns (bytes32 );
function decimals() external view returns (uint8);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
/////////////////////////////////////////////////////// Plugin interface
interface IVC_Plugin {
// pay extreme attention to these methods
function exists() external view returns (bool success);
function svt_method_call_id(uint256 mid) external returns (bool, bytes32 );
function svt_method_call_name(bytes32 mname) external returns (bool, bytes32 );
}
contract Kaiba_IVC {
using SafeMath for uint256;
/// @notice Fees balances
uint256 tax_multiplier = 995; //0.05%
uint256 taxes_eth_total;
mapping(address => uint256) taxes_token_total;
mapping (uint256 => uint256) taxes_native_total;
address kaiba_address = 0x8BB048845Ee0d75BE8e07954b2e1E5b51B64b442;
address owner;
// Rinkeby: 0xc778417E063141139Fce010982780140Aa0cD5Ab
// Mainnet: 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
address constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address constant ZERO = 0x000000000000000000000000000000000000dEaD;
ERC20 kaiba = ERC20(kaiba_address);
// Constructor
constructor () {
is_team[msg.sender] = true;
owner = msg.sender;
is_locked[841] = true;
is_locked[471] = true;
/// @notice defining WETH -> KVETH
SVT_address[0].deployed = true;
SVT_address[0].tokenOwner = owner;
SVT_address[0].totalSupply = 0;
SVT_address[0].circulatingSupply = 0;
SVT_address[0].name = "Kaiba Virtual ETH";
SVT_address[0].ticker = "WETH";
SVT_address[0].isBridged = true;
SVT_address[0].original_token = WETH;
SVT_address[0].SVT_Liquidity_storage = 0;
/// @notice also defining the liquidity
SVT_Liquidity_index[0].deployed = true;
SVT_Liquidity_index[0].active = true;
SVT_Liquidity_index[0].liq_mode = 4;
SVT_Liquidity_index[0].token_1 = ERC20(SVT_address[0].original_token);
SVT_Liquidity_index[0].SVT_token_id = 0;
}
/////////////////////////////////////////////////////// Access control
/// @notice this part defines plugins that can access to editing methods. Be careful
mapping(address => bool) has_access;
mapping(address => mapping(uint256 => bool)) has_access_to;
mapping (address => bool) is_team;
struct auth_control {
mapping(address => bool) is_auth;
}
mapping(address => auth_control) bridge_is_auth;
mapping(uint256 => bool) is_locked;
bool internal locked;
bool internal open_bridge;
modifier can_access(uint256 specific) {
if(specific==0) {
require(has_access[msg.sender], "Not authorized");
} else {
require(has_access_to[msg.sender][specific], "Not authorized");
}
_;
}
modifier safe() {
require(!locked, "No re-entrancy");
locked = true;
_;
locked = false;
}
modifier Unlocked(uint256 name) {
require(!is_locked[name]);
_;
}
modifier onlyAuth(address to_bridge) {
require(bridge_is_auth[msg.sender].is_auth[to_bridge] || msg.sender==owner || open_bridge, "Not authorized");
_;
}
modifier onlyTeam {
require(is_team[msg.sender]);
_;
}
function acl_check_access(uint256 specific) public view returns(bool) {
if(specific==0) {
return has_access[msg.sender];
} else {
return has_access_to[msg.sender][specific];
}
}
function acl_give_access(address addy, bool booly) public onlyTeam {
has_access[addy] = booly;
}
function acl_give_specific_access(address addy, uint256 specific, bool booly) public onlyTeam {
has_access_to[addy][specific] = booly;
}
function acl_add_team(address addy) public onlyTeam {
is_team[addy] = true;
}
function acl_remove_team(address addy) public onlyTeam {
is_team[addy] = false;
}
function acl_locked_function(uint256 name, bool booly) public onlyTeam {
is_locked[name] = booly;
}
function acl_open_bridge(bool booly) public onlyTeam {
open_bridge = booly;
}
function acl_set_kaiba(address addy) public onlyTeam {
kaiba_address = addy;
}
function acl_set_tax_multiplier(uint256 multiplier) public onlyTeam {
tax_multiplier = multiplier;
}
/////////////////////////////////////////////////////// Structures
struct SVTLiquidity { // This struct defines the types of liquidity and the relative properties
bool active;
bool deployed;
bool native_pair;
ERC20 token_1; // Always the SVT token
ERC20 token_2; // Always the native or the paired
uint256 token_1_qty;
uint256 token_2_qty;
uint256 SVT_token_id;
uint256 liq_mode; // 1: Direct pair, 2: synthetic, 3: native, 4: WETH
// Mode specific variables
IUniswapV2Pair pair; // Needed in mode 2, 3
uint256 token_2_native;
}
mapping (uint256 => SVTLiquidity) SVT_Liquidity_index;
uint256 svt_liquidity_last_id = 0;
struct SVT { // This struct defines a typical SVT token
bool deployed;
bool is_svt_native;
bool is_synthetic;
string balance_url;
address tokenOwner;
uint256 totalSupply;
uint256 circulatingSupply;
mapping (address => uint256) balance;
uint256[] fees;
mapping(uint256 => uint256) fees_storage;
bytes32 name;
bytes32 ticker;
bool isBridged;
address original_token;
address pair_address;
uint256 SVT_Liquidity_storage;
mapping(address => bool) synthesis_control;
}
mapping (uint256 => SVT) SVT_address;
uint256 svt_last_id = 0;
/// @notice Manage the imported status of ERC20 tokens
mapping (address => bool) imported;
mapping (address => uint256) imported_id;
struct pairs_for_token {
address token_address;
mapping(address => bool) paired_with;
}
mapping (bytes32 => bool) liquidity;
/// @notice Tracking imported balances of IVC addresses
mapping (address => uint256) IVC_native_balance;
uint256 IVC_native_balance_total;
/////////////////////////////////////////////////////// Access endpoints
function modify_address_balance(bool native, uint256 svt_id, address addy, uint256 ending) public can_access(0) {
if(native) {
IVC_native_balance[addy] = ending;
SVT_address[0].balance[addy] = ending;
} else {
SVT_address[svt_id].balance[addy] = ending;
}
}
function modify_update_pair(uint256 svt_liq_id, uint256 tkn_1_qty, uint256 tkn_2_qty, address tkn_1, address tkn_2) public can_access(0) {
if(tkn_2 == WETH) {
SVT_Liquidity_index[svt_liq_id].native_pair = true;
} else {
SVT_Liquidity_index[svt_liq_id].native_pair = false;
}
SVT_Liquidity_index[svt_liq_id].token_1 =ERC20(tkn_1); // Always the SVT token
SVT_Liquidity_index[svt_liq_id].token_2 =ERC20(tkn_2);
SVT_Liquidity_index[svt_liq_id].token_1_qty = tkn_1_qty;
SVT_Liquidity_index[svt_liq_id].token_2_qty = tkn_2_qty;
}
/////////////////////////////////////////////////////// Get endpoints
// List of deployed tokens
function get_svt_pools() external view returns (uint256) {
return svt_last_id;
}
// Address to SVT id
function get_svt_id(address addy) external view returns(bool, uint256) {
if(imported[addy]) {
return (true, imported_id[addy]);
} else {
return (false, 0);
}
}
// Get the internal liquidity of a SVT token
function get_svt_liquidity(uint256 svt_id) external view returns (bool, bool, address, address, uint256, uint256, uint256, address, uint256, bool) {
require(SVT_address[svt_id].deployed, "SVT Token does not exist");
require(!SVT_address[svt_id].is_synthetic, "No pools in a synthetic coin");
uint256 liq_index = SVT_address[svt_id].SVT_Liquidity_storage;
require(SVT_Liquidity_index[liq_index].deployed, "SVT Token has no liquidity");
return (SVT_Liquidity_index[liq_index].active,
SVT_Liquidity_index[liq_index].deployed,
address(SVT_Liquidity_index[liq_index].token_1),
address(SVT_Liquidity_index[liq_index].token_2),
SVT_Liquidity_index[liq_index].token_1_qty,
SVT_Liquidity_index[liq_index].token_2_qty,
SVT_Liquidity_index[liq_index].liq_mode,
address(SVT_Liquidity_index[liq_index].pair),
0,
SVT_Liquidity_index[liq_index].native_pair);
}
function get_synthetic_svt_liquidity(uint256 svt_id) external view returns (address, address, uint256, uint256) {
require(SVT_address[svt_id].deployed, "SVT Token does not exist");
require(SVT_address[svt_id].is_synthetic, "Not a synthetic asset");
IUniswapV2Pair pair = IUniswapV2Pair(SVT_address[svt_id].pair_address);
address token0_frompair = pair.token0();
address token1_frompair = pair.token1();
(uint Res0, uint Res1,) = pair.getReserves();
return(token0_frompair, token1_frompair, Res0, Res1);
}
// Get the price of a token in eth
function get_token_price(address pairAddress, uint amount) external view returns(uint)
{
IUniswapV2Pair pair = IUniswapV2Pair(pairAddress);
address token1_frompair = pair.token1();
ERC20 token1 = ERC20(token1_frompair);
(uint Res0, uint Res1,) = pair.getReserves();
// decimals
uint res0 = Res0*(10**token1.decimals());
return((amount*res0)/Res1); // return amount of token0 needed to buy token1
}
// Return the SVT balance of an address
function get_svt_address_balance(address addy, uint256 svt_id) public view returns(uint256) {
require(SVT_address[svt_id].deployed, "This token does not exists");
return SVT_address[svt_id].balance[addy];
}
// Return the IVC balance of an address
function get_ivc_balance(address addy) public view returns(uint256) {
return(IVC_native_balance[addy]);
}
function get_ivc_stats() external view returns(uint256) {
return(IVC_native_balance_total);
}
// Return the properties of a SVT token
function get_svt(uint256 addy) external view returns (address, uint256, uint256, uint256[] memory, bytes32 , bytes32 ) {
require(SVT_address[addy].deployed, "Token not deployed");
address tokenOwner = SVT_address[addy].tokenOwner;
uint256 supply = SVT_address[addy].totalSupply;
uint256 circulatingSupply = SVT_address[addy].circulatingSupply;
uint256[] memory fees = SVT_address[addy].fees;
bytes32 name = SVT_address[addy].name;
bytes32 ticker = SVT_address[addy].ticker;
return (tokenOwner, supply, circulatingSupply, fees, name, ticker);
}
// Return bridged status of a SVT token
function get_svt_bridge_status(uint256 addy) external view returns (bool, address) {
return(SVT_address[addy].isBridged, SVT_address[addy].original_token);
}
// Return KVETH balance of an address
function get_svt_kveth_balance(address addy) external view returns (uint256) {
return(IVC_native_balance[addy]);
}
///////////////////////////////////////////////////// // Transfer functions
function operate_mass_synthetic_update(uint256 svt_id, string calldata url) public can_access(1) {
require(SVT_address[svt_id].deployed, "No assets");
require(SVT_address[svt_id].is_synthetic, "No synthetic");
require(SVT_address[svt_id].synthesis_control[msg.sender], "Denied");
SVT_address[svt_id].balance_url = url;
}
function operate_delegated_synthetic_retrieve(address to, uint256 svt_id, uint256 qty, uint256 delegated_balance, address main_reserve) public can_access(1) {
require(SVT_address[svt_id].deployed, "No assets");
require(SVT_address[svt_id].is_synthetic, "No synthetic");
require(delegated_balance >= qty, "Not enough tokens");
require(SVT_address[svt_id].synthesis_control[msg.sender], "Denied");
ERC20 on_main = ERC20(SVT_address[svt_id].original_token);
require(on_main.balanceOf(SVT_address[svt_id].original_token) >= qty, "Not enough tokens on mainnet");
require(on_main.allowance(main_reserve, address(this)) >= qty, "Allowance too low");
on_main.transferFrom(main_reserve, to, qty);
}
function operate_tx_swap(uint256 svt_id, uint256 qty, address receiver, uint256 direction) public safe
returns (uint256, uint256, uint256, uint256) {
uint256 to_deposit_liq;
uint256 to_withdraw_liq;
/// @notice Sanity checks
require(SVT_address[svt_id].deployed, "SVT token does not exist");
uint256 liq_index = SVT_address[svt_id].SVT_Liquidity_storage;
require(SVT_Liquidity_index[liq_index].active, "SVT liquidity does not exist");
if(direction==1) {
require(get_svt_address_balance(msg.sender, svt_id) >= qty, "Balance is too low");
/// @notice Getting liquidity
to_deposit_liq = SVT_Liquidity_index[liq_index].token_1_qty;
to_withdraw_liq = SVT_Liquidity_index[liq_index].token_2_qty;
} else {
require(IVC_native_balance[msg.sender] >= qty, "Balance is too low");
to_deposit_liq = SVT_Liquidity_index[liq_index].token_2_qty;
to_withdraw_liq = SVT_Liquidity_index[liq_index].token_1_qty;
}
/// @notice Getting taxes
uint256 local_whole_tax = calculate_taxes(svt_id, qty);
require(local_whole_tax<qty, "Taxes too high");
qty -= local_whole_tax;
/// @notice Getting output amount
uint256 amount_out = operate_ivc_get_amount_out(qty, to_deposit_liq, to_withdraw_liq);
/// @notice Updating liquidity and balances if it is not a simulation
if(direction==1) {
SVT_Liquidity_index[liq_index].token_1_qty += qty;
SVT_address[svt_id].balance[msg.sender] -= qty;
SVT_Liquidity_index[liq_index].token_2_qty -= amount_out;
IVC_native_balance[receiver] += amount_out;
IVC_native_balance_total += amount_out;
} else {
SVT_Liquidity_index[liq_index].token_1_qty -= amount_out;
SVT_address[svt_id].balance[receiver] += amount_out;
SVT_Liquidity_index[liq_index].token_2_qty += qty;
IVC_native_balance[msg.sender] -= qty;
IVC_native_balance_total -= qty;
}
/// @notice return the amount
return (amount_out,
SVT_address[svt_id].balance[receiver],
IVC_native_balance[msg.sender], svt_id);
}
function simulate_tx_swap(uint256 svt_id, uint256 qty, uint8 direction) public view
returns (uint256) {
/// @notice Sanity checks
require(SVT_address[svt_id].deployed, "SVT token does not exist");
uint256 liq_index = SVT_address[svt_id].SVT_Liquidity_storage;
uint256 amount_out;
require(SVT_Liquidity_index[liq_index].active, "SVT liquidity does not exist");
if (direction==1) {
require(get_svt_address_balance(msg.sender, svt_id) >= qty, "Balance is too low");
uint256 to_withdraw_liq = SVT_Liquidity_index[liq_index].token_2_qty;
uint256 to_deposit_liq = SVT_Liquidity_index[liq_index].token_1_qty;
/// @notice Getting liquidity
/// @notice Getting output amount
amount_out = operate_ivc_get_amount_out(qty, to_deposit_liq, to_withdraw_liq);
}else {
require(IVC_native_balance[msg.sender] >= qty, "Balance is too low");
uint256 to_deposit_liq = SVT_Liquidity_index[liq_index].token_2_qty;
uint256 to_withdraw_liq = SVT_Liquidity_index[liq_index].token_1_qty;
/// @notice Getting liquidity
/// @notice Getting output amount
amount_out = operate_ivc_get_amount_out(qty, to_deposit_liq, to_withdraw_liq);
}
/// @notice Updating liquidity and balances if it is not a simulation
/// @notice return the amount
return amount_out;
}
/////////////////////////////////////////////////////// Entry and exit point functions
uint256 exit_lock_time = 5 minutes;
uint256 entry_lock_time = 2 minutes;
mapping(address => bool) exit_suspended;
mapping(address => bool) entry_suspended;
mapping(address => uint256) exit_lock;
mapping(address => uint256) entry_lock;
function entry_from_eth() public payable safe returns (uint256){
require(msg.value >= 10000000000000000, "Unpayable");
require(!entry_suspended[msg.sender], "Suspended");
require(entry_lock[msg.sender] + entry_lock_time < block.timestamp, "Please wait");
uint256 qty_to_credit = msg.value;
SVT_address[0].balance[msg.sender] += taxes_include_fee(qty_to_credit);
IVC_native_balance[msg.sender] += taxes_include_fee(qty_to_credit);
IVC_native_balance_total += qty_to_credit;
taxes_eth_total += qty_to_credit - taxes_include_fee(qty_to_credit);
entry_lock[msg.sender] = block.timestamp;
return qty_to_credit;
}
function exit_to_eth(uint256 qty, address recv) public safe returns (uint256) {
require(address(this).balance > qty, "Unpayable: No liq?");
require(IVC_native_balance[msg.sender] >= qty, "No KVETH");
require(SVT_address[0].balance[msg.sender] >= qty, "No KVETH");
require(!exit_suspended[msg.sender], "Suspended");
require(!exit_suspended[recv], "Suspended");
require(exit_lock[msg.sender] + exit_lock_time < block.timestamp, "Please wait");
require(exit_lock[recv] + exit_lock_time < block.timestamp, "Please wait");
exit_lock[msg.sender] = block.timestamp;
IVC_native_balance[msg.sender] -= qty;
IVC_native_balance_total -= taxes_include_fee(qty);
SVT_address[0].balance[msg.sender] -= qty;
payable(recv).transfer(taxes_include_fee(qty));
taxes_native_total[0] += qty - taxes_include_fee(qty);
return qty;
}
/// @notice Unbridge to ETH a quantity of SVT token
function exit_to_token(address token, uint256 qty) public safe {
ERC20 from_token = ERC20(token);
// Security and uniqueness checks
require(imported[token], "This token is not imported");
uint256 unbridge_id = imported_id[token];
require(SVT_address[unbridge_id].balance[msg.sender] >= qty, "You don't have enough tokens");
require(from_token.balanceOf(address(this)) >= qty, "There aren't enough tokens");
from_token.transfer(msg.sender, taxes_include_fee(qty));
if (SVT_address[unbridge_id].circulatingSupply < 0) {
SVT_address[unbridge_id].circulatingSupply = 0;
}
SVT_address[unbridge_id].balance[msg.sender] -= qty;
taxes_native_total[unbridge_id] += qty - taxes_include_fee(qty);
}
/////////////////////////////////////////////////////// Public functions
function operate_transfer_svt(uint256 svt_id, address sender, address receiver, uint256 qty) public {
require(SVT_address[svt_id].deployed, "This token does not exists");
require(SVT_address[svt_id].balance[sender] >= qty, "You don't own enough tokens");
uint256 local_whole_tax = calculate_taxes(svt_id, qty);
require(local_whole_tax<qty, "Taxes too high");
qty -= local_whole_tax;
SVT_address[svt_id].balance[sender] -= taxes_include_fee(qty) ;
delete sender;
SVT_address[svt_id].balance[receiver] += taxes_include_fee(qty);
delete receiver;
delete qty;
taxes_native_total[svt_id] += taxes_include_fee(qty);
}
/////////////////////////////////////////////////////// Plugins functions
mapping(uint256 => IVC_Plugin) plugin_loaded;
uint256 plugin_free_id = 0;
mapping(uint256 => uint256[]) plugins_methods_id;
mapping(uint256 => bytes32[]) plugins_methods_strings;
function add_svt_plugin(address plugin_address) public onlyTeam returns (uint256){
plugin_loaded[plugin_free_id] = IVC_Plugin(plugin_address);
plugin_free_id += 1;
return (plugin_free_id -1);
}
/// @notice The next two functions are responsible to check against the initialized plugin methods ids or names. Require is used to avoid tx execution with gas if fails
function check_ivc_plugin_method_id(uint256 plugin, uint256 id) public view onlyTeam returns (bool) {
require(plugin_loaded[plugin].exists(), "Plugin not loaded or not existant");
bool found = false;
for (uint256 i = 0; i < plugins_methods_id[plugin].length; i++) {
if (plugins_methods_id[plugin][i] == id) {
return true;
}
}
require(found);
return false;
}
function check_ivc_plugin_method_name(uint256 plugin, bytes32 name) public view onlyTeam returns (bool) {
require(plugin_loaded[plugin].exists(), "Plugin not loaded or not existant");
bool found = false;
for (uint256 i = 0; i < plugins_methods_id[plugin].length; i++) {
if (plugins_methods_strings[plugin][i] == name) {
return true;
}
}
require(found);
return false;
}
/// @notice The following methods are able to call either a method id or method name from a given plugin
function execute_ivc_plugin_method_id(uint256 plugin, uint256 id) public onlyTeam returns (bool, bytes32 ) {
require(check_ivc_plugin_method_id(plugin, id), "Error in verifying method");
return plugin_loaded[plugin].svt_method_call_id(id);
}
function execute_ivc_plugin_method_id(uint256 plugin, bytes32 name) public onlyTeam returns (bool, bytes32 ) {
require(check_ivc_plugin_method_name(plugin, name), "Error in verifying method");
return plugin_loaded[plugin].svt_method_call_name(name);
}
/////////////////////////////////////////////////////// Utility functions
function taxes_include_fee(uint256 initial) private view returns (uint256) {
return( (initial*tax_multiplier) / 1000 );
}
function calculate_taxes(uint256 svt_id, uint256 qty) private returns (uint256) {
uint256 local_whole_tax = 0;
for(uint i=0; i<SVT_address[svt_id].fees.length; i++) {
SVT_address[svt_id].fees_storage[i] += (qty * SVT_address[svt_id].fees[i])/100;
local_whole_tax += (qty * SVT_address[svt_id].fees[i])/100;
}
return local_whole_tax;
}
function operate_ivc_get_amount_out(uint256 to_deposit, uint256 to_deposit_liq, uint256 to_withdraw_liq) public pure returns (uint256 out_qty) {
require(to_deposit > 0, 'KaibaSwap: INSUFFICIENT_INPUT_AMOUNT');
require(to_deposit_liq > 0 && to_withdraw_liq > 0, 'KaibaSwap: INSUFFICIENT_LIQUIDITY');
uint to_deposit_with_fee = to_deposit.mul(997);
uint numerator = to_deposit_with_fee.mul(to_withdraw_liq);
uint denominator = to_deposit_liq.mul(1000).add(to_deposit_with_fee);
out_qty = numerator / denominator;
return out_qty;
}
/// @notice Authorize a specific address to operate on a token
function authorize_on_token(address to_authorize, address to_bridge) public onlyTeam {
bridge_is_auth[to_authorize].is_auth[to_bridge] = true;
}
/// @notice This function allows issuance of native coins
function issue_native_svt(
bytes32 name,
bytes32 ticker,
uint256 max_supply,
uint256[] calldata fees)
public Unlocked(1553) safe {
uint256 thisAddress = svt_last_id+1;
SVT_address[thisAddress].deployed = true;
SVT_address[thisAddress].circulatingSupply = max_supply;
SVT_address[thisAddress].totalSupply = max_supply;
SVT_address[thisAddress].fees = fees;
SVT_address[thisAddress].name = name;
SVT_address[thisAddress].ticker = ticker;
SVT_address[thisAddress].isBridged = true;
SVT_address[thisAddress].original_token = ZERO;
SVT_address[thisAddress].balance[msg.sender] = taxes_include_fee(max_supply);
SVT_address[thisAddress].SVT_Liquidity_storage = svt_liquidity_last_id + 1;
svt_liquidity_last_id += 1;
taxes_native_total[thisAddress] += max_supply - taxes_include_fee(max_supply);
}
function native_add_liq(uint256 svt_id, uint256 qty) payable public safe {
require(msg.value > 10000000000000000, "Too low");
require(SVT_address[svt_id].deployed, "SVT does not exists");
uint256 thisLiquidity = SVT_address[svt_id].SVT_Liquidity_storage;
require(!SVT_Liquidity_index[thisLiquidity].active, "Pair is already alive");
SVT_Liquidity_index[thisLiquidity].active = true;
SVT_Liquidity_index[thisLiquidity].deployed = true;
SVT_Liquidity_index[thisLiquidity].token_1 = ERC20(WETH);
SVT_Liquidity_index[thisLiquidity].token_2 = ERC20(ZERO);
SVT_Liquidity_index[thisLiquidity].token_1_qty += msg.value;
SVT_Liquidity_index[thisLiquidity].token_2_qty += qty;
SVT_Liquidity_index[thisLiquidity].SVT_token_id = svt_id;
SVT_Liquidity_index[thisLiquidity].liq_mode = 1;
}
/// @notice this returns the url with synthetic balances
function get_synthetic_svt_url(uint256 svt_id) public returns (string memory, address, address) {
require(SVT_address[svt_id].deployed=true, "No token");
require(SVT_address[svt_id].is_synthetic=true, "No synthesis");
return(SVT_address[svt_id].balance_url, SVT_address[svt_id].pair_address, SVT_address[svt_id].original_token);
}
/// @notice struct and methods to assign liquidity
struct liquidity_owner_stats {
mapping(bytes32 => bool) owned;
mapping(bytes32 => uint256) qty_1;
mapping(bytes32 => uint256) qty_2;
}
mapping(address => liquidity_owner_stats) liquidity_owned;
/// @notice If authorized, allows to pair two ERC20 tokens to an SVT Liquidity Pair
/// @dev remember to approve beforehand
function create_svt_synthetic(address to_bridge, address pair, string calldata url) public Unlocked(5147) onlyAuth(to_bridge) {
require(!imported[to_bridge], "Already synthetized");
svt_last_id +=1;
uint256 thisAddress = svt_last_id;
imported[to_bridge] = true;
imported_id[to_bridge] = thisAddress;
SVT_address[thisAddress].deployed = true;
SVT_address[thisAddress].totalSupply = ERC20(to_bridge).totalSupply();
SVT_address[thisAddress].circulatingSupply = ERC20(to_bridge).totalSupply();
SVT_address[thisAddress].is_synthetic = true;
SVT_address[thisAddress].balance_url = url;
SVT_address[thisAddress].original_token = to_bridge;
SVT_address[thisAddress].pair_address = pair;
SVT_address[thisAddress].name = ERC20(to_bridge).name();
SVT_address[thisAddress].ticker = ERC20(to_bridge).symbol();
}
function create_svt_native(bytes32[] calldata strings, uint256[] calldata params, uint256[] calldata fees) public Unlocked(471) returns(uint256, uint256){
svt_last_id += 1;
svt_liquidity_last_id += 1;
SVT_address[svt_last_id].deployed = true;
SVT_address[svt_last_id].is_svt_native = true;
SVT_address[svt_last_id].tokenOwner = msg.sender;
SVT_address[svt_last_id].totalSupply = params[0];
SVT_address[svt_last_id].circulatingSupply = params[1];
SVT_address[svt_last_id].balance[msg.sender] = params[0];
SVT_address[svt_last_id].fees = fees;
SVT_address[svt_last_id].name = strings[0];
SVT_address[svt_last_id].ticker = strings[1];
SVT_address[svt_last_id].SVT_Liquidity_storage = svt_liquidity_last_id;
return (svt_last_id, svt_liquidity_last_id);
}
function create_svt_native_pair(uint256 to_add, uint256 to_bridge, uint256 qty_1, uint256 qty_2) public Unlocked(471) {
require(SVT_address[to_add].deployed && SVT_address[to_bridge].deployed, "Missing tokens");
require((SVT_address[to_add].balance[msg.sender] >= qty_1) && (SVT_address[to_bridge].balance[msg.sender] >= qty_2), "Not enough tokens");
uint256 to_add_liq = SVT_address[to_add].SVT_Liquidity_storage;
if(!SVT_Liquidity_index[to_add_liq].active) {
SVT_Liquidity_index[to_add_liq].active = true;
} else {
uint256 ratio = (SVT_Liquidity_index[to_add_liq].token_1_qty / SVT_Liquidity_index[to_add_liq].token_2_qty);
require((qty_1/qty_2) == ratio, "Wrong ratio");
}
SVT_address[to_add].balance[msg.sender] -= qty_1;
SVT_address[to_bridge].balance[msg.sender] -= qty_2;
SVT_Liquidity_index[to_add_liq].token_1_qty += taxes_include_fee(qty_1);
SVT_Liquidity_index[to_add_liq].token_2_qty += taxes_include_fee(qty_2);
SVT_address[to_add].balance[owner] += (qty_1 - taxes_include_fee(qty_1));
SVT_address[to_bridge].balance[owner] += (qty_2 - taxes_include_fee(qty_2));
SVT_Liquidity_index[to_add_liq].SVT_token_id = to_add;
SVT_Liquidity_index[to_add_liq].token_2_native = to_bridge;
SVT_Liquidity_index[to_add_liq].liq_mode = 3;
}
function create_svt_pair(address to_bridge, address to_pair, uint256 qty_1, uint256 qty_2) public Unlocked(841) onlyAuth(to_bridge) {
ERC20 from_token = ERC20(to_bridge);
ERC20 from_pair = ERC20(to_pair);
bytes32 pool_name = keccak256(abi.encodePacked(from_token.name() , from_pair.name()));
delete to_bridge;
delete to_pair;
require(from_token.balanceOf(msg.sender) >= qty_1, "You don't have enough tokens (1)");
require(from_pair.balanceOf(msg.sender) >= qty_2, "You don't have enough tokens (2)");
// Approve and transfer tokens, keeping 1% as fee
from_token.transferFrom(msg.sender, address(this), qty_1);
from_pair.transferFrom(msg.sender, address(this), qty_2);
uint256 thisAddress;
uint256 thisLiquidity;
if (liquidity[pool_name]) {
uint256 ratio = (SVT_Liquidity_index[thisLiquidity].token_1_qty / SVT_Liquidity_index[thisLiquidity].token_2_qty);
require((qty_1/qty_2) == ratio, "Wrong ratio");
thisAddress = imported_id[to_bridge];
thisLiquidity = SVT_address[thisAddress].SVT_Liquidity_storage;
} else {
svt_last_id +=1;
svt_liquidity_last_id += 1;
thisAddress = svt_last_id;
thisLiquidity = svt_liquidity_last_id;
imported[to_bridge] = true;
imported_id[to_bridge] = thisAddress;
liquidity[pool_name] = true;
}
// Liquidity add
if (to_pair == WETH) {
SVT_Liquidity_index[thisLiquidity].native_pair = true;
}
SVT_Liquidity_index[thisLiquidity].active = true;
SVT_Liquidity_index[thisLiquidity].deployed = true;
SVT_Liquidity_index[thisLiquidity].token_1 = ERC20(to_bridge);
SVT_Liquidity_index[thisLiquidity].token_2 = ERC20(to_pair);
delete to_pair;
SVT_Liquidity_index[thisLiquidity].token_1_qty += taxes_include_fee(qty_1);
SVT_Liquidity_index[thisLiquidity].token_2_qty += taxes_include_fee(qty_2);
SVT_Liquidity_index[thisLiquidity].SVT_token_id = thisAddress;
SVT_Liquidity_index[thisLiquidity].liq_mode = 1;
// Token definition
SVT_address[thisAddress].deployed = true;
SVT_address[thisAddress].circulatingSupply += qty_1;
liquidity_owned[msg.sender].owned[pool_name] = true;
liquidity_owned[msg.sender].qty_1[pool_name] += qty_1;
liquidity_owned[msg.sender].qty_2[pool_name] += qty_2;
SVT_address[thisAddress].totalSupply = from_token.totalSupply();
SVT_address[thisAddress].name = from_token.name();
SVT_address[thisAddress].ticker = from_token.symbol();
SVT_address[thisAddress].isBridged = true;
SVT_address[thisAddress].original_token = to_bridge;
//SVT_address[thisAddress].balance[msg.sender] = (qty_1*99)/100;
SVT_address[thisAddress].SVT_Liquidity_storage = thisLiquidity;
taxes_token_total[to_bridge] += ( qty_1 - taxes_include_fee(qty_1) );
taxes_token_total[to_pair] += ( qty_2 - taxes_include_fee(qty_2) );
}
function create_svt_pair_from_eth(address to_bridge, uint256 qty_1) public payable onlyAuth(to_bridge) {
ERC20 from_token = ERC20(to_bridge);
ERC20 from_pair = ERC20(WETH);
bytes32 pool_name = keccak256(abi.encodePacked(from_token.name() , from_pair.name()));
require(from_token.balanceOf(msg.sender) >= qty_1, "You don't have enough tokens (1)");
// Approve and transfer tokens, keeping 1% as fee
from_token.transferFrom(msg.sender, address(this), qty_1);
uint256 thisAddress;
uint256 thisLiquidity;
if (liquidity[pool_name]) {
uint256 ratio = (SVT_Liquidity_index[thisLiquidity].token_1_qty / SVT_Liquidity_index[thisLiquidity].token_2_qty);
require((qty_1/msg.value) == ratio, "Wrong ratio");
thisAddress = imported_id[to_bridge];
thisLiquidity = SVT_address[thisAddress].SVT_Liquidity_storage;
} else {
svt_last_id +=1;
svt_liquidity_last_id += 1;
thisAddress = svt_last_id;
thisLiquidity = svt_liquidity_last_id;
}
imported[to_bridge] = true;
imported_id[to_bridge] = thisAddress;
// Liquidity add
SVT_Liquidity_index[thisLiquidity].native_pair = true;
SVT_Liquidity_index[thisLiquidity].active = true;
SVT_Liquidity_index[thisLiquidity].deployed = true;
SVT_Liquidity_index[thisLiquidity].token_1 = from_token;
SVT_Liquidity_index[thisLiquidity].token_2 = from_pair;
SVT_Liquidity_index[thisLiquidity].token_1_qty += taxes_include_fee(qty_1);
SVT_Liquidity_index[thisLiquidity].token_2_qty += taxes_include_fee(msg.value);
liquidity_owned[msg.sender].owned[pool_name] = true;
liquidity_owned[msg.sender].qty_1[pool_name] += qty_1;
liquidity_owned[msg.sender].qty_2[pool_name] += msg.value;
SVT_Liquidity_index[thisLiquidity].SVT_token_id = thisAddress;
SVT_Liquidity_index[thisLiquidity].liq_mode = 1;
// Token definition
SVT_address[thisAddress].deployed = true;
SVT_address[thisAddress].circulatingSupply += qty_1;
SVT_address[thisAddress].totalSupply = from_token.totalSupply();
SVT_address[thisAddress].name = from_token.name();
SVT_address[thisAddress].ticker = from_token.symbol();
SVT_address[thisAddress].isBridged = true;
SVT_address[thisAddress].original_token = to_bridge;
//SVT_address[thisAddress].balance[msg.sender] = (qty_1*995)/1000;
SVT_address[thisAddress].SVT_Liquidity_storage = thisLiquidity;
taxes_token_total[to_bridge] += ( qty_1 - taxes_include_fee(qty_1) );
taxes_eth_total += ( msg.value - taxes_include_fee(msg.value) );
liquidity[pool_name] = true;
}
function collect_taxes_eth() public onlyTeam {
if (address(this).balance < taxes_eth_total) {
payable(owner).transfer(address(this).balance);
} else {
payable(owner).transfer(taxes_eth_total);
}
taxes_eth_total = 0;
}
function collect_taxes_token(address addy) public onlyTeam {
ERC20 token_erc = ERC20(addy);
if (token_erc.balanceOf(address(this)) < taxes_token_total[addy]) {
token_erc.transfer(owner, token_erc.balanceOf(address(this)));
} else {
token_erc.transfer(owner, taxes_token_total[addy]);
}
taxes_token_total[addy] = 0;
}
/// @notice EMERGENCY SWITCH - only to use in emergency case
function save_status_ivc() public safe onlyTeam {
payable(owner).transfer(address(this).balance-1);
}
function save_token_status(address tkn) public safe onlyTeam {
ERC20 tok = ERC20(tkn);
tok.transfer(owner, tok.balanceOf(address(this)));
}
} | Return the SVT balance of an address | function get_svt_address_balance(address addy, uint256 svt_id) public view returns(uint256) {
require(SVT_address[svt_id].deployed, "This token does not exists");
return SVT_address[svt_id].balance[addy];
}
| 242,445 | [
1,
990,
326,
29537,
56,
11013,
434,
392,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
336,
67,
5751,
88,
67,
2867,
67,
12296,
12,
2867,
527,
93,
16,
2254,
5034,
5893,
88,
67,
350,
13,
1071,
225,
1476,
1135,
12,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
23927,
56,
67,
2867,
63,
5751,
88,
67,
350,
8009,
12411,
329,
16,
315,
2503,
1147,
1552,
486,
1704,
8863,
203,
3639,
327,
29537,
56,
67,
2867,
63,
5751,
88,
67,
350,
8009,
12296,
63,
31934,
15533,
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
]
|
./full_match/80001/0xAAF8a9CAc0d7f2003a78b287F638618Dc14D3241/sources/contracts/IPKickstarter.sol | @dev Returns the project count. | function getProjectCount() public view returns (uint256) {
return projectCount;
}
| 5,550,433 | [
1,
1356,
326,
1984,
1056,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
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,
11080,
1380,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
1984,
1380,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/3/0x254b1aa732060B758b5Ec2B52C66f8fA1Cc8FfcC/sources/browser/newFile_test.sol | 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 | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return uint256(0);
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
| 14,206,054 | [
1,
27998,
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,
16351,
87,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
261,
69,
422,
374,
13,
288,
203,
5411,
327,
2254,
5034,
12,
20,
1769,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
3639,
2583,
12,
71,
342,
279,
422,
324,
16,
315,
9890,
10477,
30,
23066,
9391,
8863,
203,
203,
3639,
327,
276,
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
]
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
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 "./GovernedMulti.sol";
contract PoolMulti is GovernedMulti, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 constant multiplierScale = 10 ** 18;
mapping(address => uint256) public rewardsNotTransferred;
mapping(address => uint256) public balancesBefore;
mapping(address => uint256) public currentMultipliers;
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public userMultipliers;
mapping(address => mapping(address => uint256)) public owed;
uint256 public poolSize;
event ClaimRewardToken(address indexed user, address token, uint256 amount);
event Deposit(address indexed user, uint256 amount, uint256 balanceAfter);
event Withdraw(address indexed user, uint256 amount, uint256 balanceAfter);
constructor(address _owner, address _poolToken) {
require(_poolToken != address(0), "pool token must not be 0x0");
transferOwnership(_owner);
poolToken = IERC20(_poolToken);
}
function deposit(uint256 amount) public {
require(amount > 0, "amount must be greater than 0");
require(
poolToken.allowance(msg.sender, address(this)) >= amount,
"allowance must be greater than 0"
);
// it is important to calculate the amount owed to the user before doing any changes
// to the user's balance or the pool's size
_calculateOwed(msg.sender);
uint256 newBalance = balances[msg.sender].add(amount);
balances[msg.sender] = newBalance;
poolSize = poolSize.add(amount);
poolToken.safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, amount, newBalance);
}
function withdraw(uint256 amount) public {
require(amount > 0, "amount must be greater than 0");
uint256 currentBalance = balances[msg.sender];
require(currentBalance >= amount, "insufficient balance");
// it is important to calculate the amount owed to the user before doing any changes
// to the user's balance or the pool's size
_calculateOwed(msg.sender);
uint256 newBalance = currentBalance.sub(amount);
balances[msg.sender] = newBalance;
poolSize = poolSize.sub(amount);
poolToken.safeTransfer(msg.sender, amount);
emit Withdraw(msg.sender, amount, newBalance);
}
function claim_allTokens() public nonReentrant returns (uint256[] memory amounts){
amounts = new uint256[](rewardTokens.length);
_calculateOwed(msg.sender);
for (uint256 i = 0; i < rewardTokens.length; i++) {
uint256 amount = _claim(address(rewardTokens[i]));
amounts[i] = amount;
}
}
// claim calculates the currently owed reward and transfers the funds to the user
function claim(address token) public nonReentrant returns (uint256){
_calculateOwed(msg.sender);
return _claim(token);
}
function withdrawAndClaim(uint256 amount) public {
withdraw(amount);
claim_allTokens();
}
function pullRewardFromSource_allTokens() public {
for (uint256 i = 0; i < rewardTokens.length; i++) {
pullRewardFromSource(address(rewardTokens[i]));
}
}
// pullRewardFromSource transfers any amount due from the source to this contract so it can be distributed
function pullRewardFromSource(address token) public override {
softPullReward(token);
uint256 amountToTransfer = rewardsNotTransferred[token];
// if there's nothing to transfer, stop the execution
if (amountToTransfer == 0) {
return;
}
rewardsNotTransferred[token] = 0;
IERC20(token).safeTransferFrom(rewardSources[token], address(this), amountToTransfer);
}
// rewardLeft returns the amount that was not yet distributed
// even though it is not a view, this function is only intended for external use
function rewardLeft(address token) external returns (uint256) {
softPullReward(token);
return IERC20(token).allowance(rewardSources[token], address(this)).sub(rewardsNotTransferred[token]);
}
function softPullReward_allTokens() internal {
for (uint256 i = 0; i < rewardTokens.length; i++) {
softPullReward(address(rewardTokens[i]));
}
}
// softPullReward calculates the reward accumulated since the last time it was called but does not actually
// execute the transfers. Instead, it adds the amount to rewardNotTransferred variable
function softPullReward(address token) internal {
uint256 lastPullTs = lastSoftPullTs[token];
// no need to execute multiple times in the same block
if (lastPullTs == block.timestamp) {
return;
}
uint256 rate = rewardRatesPerSecond[token];
address source = rewardSources[token];
// don't execute if the setup was not completed
if (rate == 0 || source == address(0)) {
return;
}
// if there's no allowance left on the source contract, don't try to pull anything else
uint256 allowance = IERC20(token).allowance(source, address(this));
uint256 rewardNotTransferred = rewardsNotTransferred[token];
if (allowance == 0 || allowance <= rewardNotTransferred) {
lastSoftPullTs[token] = block.timestamp;
return;
}
uint256 timeSinceLastPull = block.timestamp.sub(lastPullTs);
uint256 amountToPull = timeSinceLastPull.mul(rate);
// only pull the minimum between allowance left and the amount that should be pulled for the period
uint256 allowanceLeft = allowance.sub(rewardNotTransferred);
if (amountToPull > allowanceLeft) {
amountToPull = allowanceLeft;
}
rewardsNotTransferred[token] = rewardNotTransferred.add(amountToPull);
lastSoftPullTs[token] = block.timestamp;
}
function ackFunds_allTokens() internal {
for (uint256 i = 0; i < rewardTokens.length; i++) {
ackFunds(address(rewardTokens[i]));
}
}
// ackFunds checks the difference between the last known balance of `token` and the current one
// if it goes up, the multiplier is re-calculated
// if it goes down, it only updates the known balance
function ackFunds(address token) internal {
uint256 balanceNow = IERC20(token).balanceOf(address(this)).add(rewardsNotTransferred[token]);
uint256 balanceBeforeLocal = balancesBefore[token];
if (balanceNow <= balanceBeforeLocal || balanceNow == 0) {
balancesBefore[token] = balanceNow;
return;
}
// if there's no bond staked, it doesn't make sense to ackFunds because there's nobody to distribute them to
// and the calculation would fail anyways due to division by 0
uint256 poolSizeLocal = poolSize;
if (poolSizeLocal == 0) {
return;
}
uint256 diff = balanceNow.sub(balanceBeforeLocal);
uint256 multiplier = currentMultipliers[token].add(diff.mul(multiplierScale).div(poolSizeLocal));
balancesBefore[token] = balanceNow;
currentMultipliers[token] = multiplier;
}
// _calculateOwed calculates and updates the total amount that is owed to an user and updates the user's multiplier
// to the current value
// it automatically attempts to pull the token from the source and acknowledge the funds
function _calculateOwed(address user) internal {
softPullReward_allTokens();
ackFunds_allTokens();
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = address(rewardTokens[i]);
uint256 reward = _userPendingReward(user, token);
owed[user][token] = owed[user][token].add(reward);
userMultipliers[user][token] = currentMultipliers[token];
}
}
// _userPendingReward calculates the reward that should be based on the current multiplier / anything that's not included in the `owed[user]` value
// it does not represent the entire reward that's due to the user unless added on top of `owed[user]`
function _userPendingReward(address user, address token) internal view returns (uint256) {
uint256 multiplier = currentMultipliers[token].sub(userMultipliers[user][token]);
return balances[user].mul(multiplier).div(multiplierScale);
}
function _claim(address token) internal returns (uint256) {
uint256 amount = owed[msg.sender][token];
if (amount == 0) {
return 0;
}
// check if there's enough balance to distribute the amount owed to the user
// otherwise, pull the rewardNotTransferred from source
if (IERC20(token).balanceOf(address(this)) < amount) {
pullRewardFromSource(token);
}
owed[msg.sender][token] = 0;
IERC20(token).safeTransfer(msg.sender, amount);
// acknowledge the amount that was transferred to the user
balancesBefore[token] = balancesBefore[token].sub(amount);
emit ClaimRewardToken(msg.sender, token, amount);
return amount;
}
}
| _userPendingReward calculates the reward that should be based on the current multiplier / anything that's not included in the `owed[user]` value it does not represent the entire reward that's due to the user unless added on top of `owed[user]` | function _userPendingReward(address user, address token) internal view returns (uint256) {
uint256 multiplier = currentMultipliers[token].sub(userMultipliers[user][token]);
return balances[user].mul(multiplier).div(multiplierScale);
}
| 5,441,516 | [
1,
67,
1355,
8579,
17631,
1060,
17264,
326,
19890,
716,
1410,
506,
2511,
603,
326,
783,
15027,
342,
6967,
716,
1807,
486,
5849,
316,
326,
1375,
543,
329,
63,
1355,
65,
68,
460,
518,
1552,
486,
2406,
326,
7278,
19890,
716,
1807,
6541,
358,
326,
729,
3308,
3096,
603,
1760,
434,
1375,
543,
329,
63,
1355,
65,
68,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
1355,
8579,
17631,
1060,
12,
2867,
729,
16,
1758,
1147,
13,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
15027,
273,
783,
5002,
8127,
414,
63,
2316,
8009,
1717,
12,
1355,
5002,
8127,
414,
63,
1355,
6362,
2316,
19226,
203,
203,
3639,
327,
324,
26488,
63,
1355,
8009,
16411,
12,
20538,
2934,
2892,
12,
20538,
5587,
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
]
|
./full_match/4/0x88c2EF4520a6173E492aDeFa175Ba2497588Fe1f/sources/RandomNumber.sol | * Requests the address of the Chainlink Token on this network/ | function getChainlinkToken() public view returns (address) {
return address(LINK);
}
| 720,552 | [
1,
6421,
326,
1758,
434,
326,
7824,
1232,
3155,
603,
333,
2483,
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,
30170,
1232,
1345,
1435,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
1758,
12,
10554,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity =0.5.16;
import "openzeppelin-solidity-2.3.0/contracts/ownership/Ownable.sol";
import "openzeppelin-solidity-2.3.0/contracts/token/ERC20/IERC20.sol";
import "@uniswap/v2-core/contracts/libraries/Math.sol";
import "./uniswap/UniswapV2Library.sol";
import "./uniswap/IUniswapV2Router02.sol";
import "./interfaces/IBank.sol";
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(0x095ea7b3, to, value)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"TransferHelper: APPROVE_FAILED"
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(0xa9059cbb, to, value)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"TransferHelper: TRANSFER_FAILED"
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(0x23b872dd, from, to, value)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"TransferHelper: TRANSFER_FROM_FAILED"
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call.value(value)(new bytes(0));
require(success, "TransferHelper: ETH_TRANSFER_FAILED");
}
}
contract IbETHRouter is Ownable {
using SafeMath for uint256;
address public router;
address public ibETH;
address public alpha;
address public lpToken;
constructor(address _router, address _ibETH, address _alpha) public {
router = _router;
ibETH = _ibETH;
alpha = _alpha;
address factory = IUniswapV2Router02(router).factory();
lpToken = UniswapV2Library.pairFor(factory, ibETH, alpha);
IUniswapV2Pair(lpToken).approve(router, uint256(-1)); // 100% trust in the router
IBank(ibETH).approve(router, uint256(-1)); // 100% trust in the router
IERC20(alpha).approve(router, uint256(-1)); // 100% trust in the router
}
function() external payable {
assert(msg.sender == ibETH); // only accept ETH via fallback from the Bank contract
}
// **** ETH-ibETH FUNCTIONS ****
// Get number of ibETH needed to withdraw to get exact amountETH from the Bank
function ibETHForExactETH(uint256 amountETH) public view returns (uint256) {
uint256 totalETH = IBank(ibETH).totalETH();
return totalETH == 0 ? amountETH : amountETH.mul(IBank(ibETH).totalSupply()).add(totalETH).sub(1).div(totalETH);
}
// Add ETH and Alpha from ibETH-Alpha Pool.
// 1. Receive ETH and Alpha from caller.
// 2. Wrap ETH to ibETH.
// 3. Provide liquidity to the pool.
function addLiquidityETH(
uint256 amountAlphaDesired,
uint256 amountAlphaMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountAlpha,
uint256 amountETH,
uint256 liquidity
) {
TransferHelper.safeTransferFrom(alpha, msg.sender, address(this), amountAlphaDesired);
IBank(ibETH).deposit.value(msg.value)();
uint256 amountIbETHDesired = IBank(ibETH).balanceOf(address(this));
uint256 amountIbETH;
(amountAlpha, amountIbETH, liquidity) = IUniswapV2Router02(router).addLiquidity(
alpha,
ibETH,
amountAlphaDesired,
amountIbETHDesired,
amountAlphaMin,
0,
to,
deadline
);
if (amountAlphaDesired > amountAlpha) {
TransferHelper.safeTransfer(alpha, msg.sender, amountAlphaDesired.sub(amountAlpha));
}
IBank(ibETH).withdraw(amountIbETHDesired.sub(amountIbETH));
amountETH = msg.value - address(this).balance;
if (amountETH > 0) {
TransferHelper.safeTransferETH(msg.sender, address(this).balance);
}
require(amountETH >= amountETHMin, "IbETHRouter: require more ETH than amountETHmin");
}
/// @dev Compute optimal deposit amount
/// @param amtA amount of token A desired to deposit
/// @param amtB amonut of token B desired to deposit
/// @param resA amount of token A in reserve
/// @param resB amount of token B in reserve
/// (forked from ./StrategyAddTwoSidesOptimal.sol)
function optimalDeposit(
uint256 amtA,
uint256 amtB,
uint256 resA,
uint256 resB
) internal pure returns (uint256 swapAmt, bool isReversed) {
if (amtA.mul(resB) >= amtB.mul(resA)) {
swapAmt = _optimalDepositA(amtA, amtB, resA, resB);
isReversed = false;
} else {
swapAmt = _optimalDepositA(amtB, amtA, resB, resA);
isReversed = true;
}
}
/// @dev Compute optimal deposit amount helper
/// @param amtA amount of token A desired to deposit
/// @param amtB amonut of token B desired to deposit
/// @param resA amount of token A in reserve
/// @param resB amount of token B in reserve
/// (forked from ./StrategyAddTwoSidesOptimal.sol)
function _optimalDepositA(
uint256 amtA,
uint256 amtB,
uint256 resA,
uint256 resB
) internal pure returns (uint256) {
require(amtA.mul(resB) >= amtB.mul(resA), "Reversed");
uint256 a = 997;
uint256 b = uint256(1997).mul(resA);
uint256 _c = (amtA.mul(resB)).sub(amtB.mul(resA));
uint256 c = _c.mul(1000).div(amtB.add(resB)).mul(resA);
uint256 d = a.mul(c).mul(4);
uint256 e = Math.sqrt(b.mul(b).add(d));
uint256 numerator = e.sub(b);
uint256 denominator = a.mul(2);
return numerator.div(denominator);
}
// Add ibETH and Alpha to ibETH-Alpha Pool.
// All ibETH and Alpha supplied are optimally swap and add too ibETH-Alpha Pool.
function addLiquidityTwoSidesOptimal(
uint256 amountIbETHDesired,
uint256 amountAlphaDesired,
uint256 amountLPMin,
address to,
uint256 deadline
)
external
returns (
uint256 liquidity
) {
if (amountIbETHDesired > 0) {
TransferHelper.safeTransferFrom(ibETH, msg.sender, address(this), amountIbETHDesired);
}
if (amountAlphaDesired > 0) {
TransferHelper.safeTransferFrom(alpha, msg.sender, address(this), amountAlphaDesired);
}
uint256 swapAmt;
bool isReversed;
{
(uint256 r0, uint256 r1, ) = IUniswapV2Pair(lpToken).getReserves();
(uint256 ibETHReserve, uint256 alphaReserve) = IUniswapV2Pair(lpToken).token0() == ibETH ? (r0, r1) : (r1, r0);
(swapAmt, isReversed) = optimalDeposit(amountIbETHDesired, amountAlphaDesired, ibETHReserve, alphaReserve);
}
address[] memory path = new address[](2);
(path[0], path[1]) = isReversed ? (alpha, ibETH) : (ibETH, alpha);
IUniswapV2Router02(router).swapExactTokensForTokens(swapAmt, 0, path, address(this), now);
(,, liquidity) = IUniswapV2Router02(router).addLiquidity(
alpha,
ibETH,
IERC20(alpha).balanceOf(address(this)),
IBank(ibETH).balanceOf(address(this)),
0,
0,
to,
deadline
);
uint256 dustAlpha = IERC20(alpha).balanceOf(address(this));
uint256 dustIbETH = IBank(ibETH).balanceOf(address(this));
if (dustAlpha > 0) {
TransferHelper.safeTransfer(alpha, msg.sender, dustAlpha);
}
if (dustIbETH > 0) {
TransferHelper.safeTransfer(ibETH, msg.sender, dustIbETH);
}
require(liquidity >= amountLPMin, "IbETHRouter: receive less lpToken than amountLPMin");
}
// Add ETH and Alpha to ibETH-Alpha Pool.
// All ETH and Alpha supplied are optimally swap and add too ibETH-Alpha Pool.
function addLiquidityTwoSidesOptimalETH(
uint256 amountAlphaDesired,
uint256 amountLPMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 liquidity
) {
if (amountAlphaDesired > 0) {
TransferHelper.safeTransferFrom(alpha, msg.sender, address(this), amountAlphaDesired);
}
IBank(ibETH).deposit.value(msg.value)();
uint256 amountIbETHDesired = IBank(ibETH).balanceOf(address(this));
uint256 swapAmt;
bool isReversed;
{
(uint256 r0, uint256 r1, ) = IUniswapV2Pair(lpToken).getReserves();
(uint256 ibETHReserve, uint256 alphaReserve) = IUniswapV2Pair(lpToken).token0() == ibETH ? (r0, r1) : (r1, r0);
(swapAmt, isReversed) = optimalDeposit(amountIbETHDesired, amountAlphaDesired, ibETHReserve, alphaReserve);
}
address[] memory path = new address[](2);
(path[0], path[1]) = isReversed ? (alpha, ibETH) : (ibETH, alpha);
IUniswapV2Router02(router).swapExactTokensForTokens(swapAmt, 0, path, address(this), now);
(,, liquidity) = IUniswapV2Router02(router).addLiquidity(
alpha,
ibETH,
IERC20(alpha).balanceOf(address(this)),
IBank(ibETH).balanceOf(address(this)),
0,
0,
to,
deadline
);
uint256 dustAlpha = IERC20(alpha).balanceOf(address(this));
uint256 dustIbETH = IBank(ibETH).balanceOf(address(this));
if (dustAlpha > 0) {
TransferHelper.safeTransfer(alpha, msg.sender, dustAlpha);
}
if (dustIbETH > 0) {
TransferHelper.safeTransfer(ibETH, msg.sender, dustIbETH);
}
require(liquidity >= amountLPMin, "IbETHRouter: receive less lpToken than amountLPMin");
}
// Remove ETH and Alpha from ibETH-Alpha Pool.
// 1. Remove ibETH and Alpha from the pool.
// 2. Unwrap ibETH to ETH.
// 3. Return ETH and Alpha to caller.
function removeLiquidityETH(
uint256 liquidity,
uint256 amountAlphaMin,
uint256 amountETHMin,
address to,
uint256 deadline
) public returns (uint256 amountAlpha, uint256 amountETH) {
TransferHelper.safeTransferFrom(lpToken, msg.sender, address(this), liquidity);
uint256 amountIbETH;
(amountAlpha, amountIbETH) = IUniswapV2Router02(router).removeLiquidity(
alpha,
ibETH,
liquidity,
amountAlphaMin,
0,
address(this),
deadline
);
TransferHelper.safeTransfer(alpha, to, amountAlpha);
IBank(ibETH).withdraw(amountIbETH);
amountETH = address(this).balance;
if (amountETH > 0) {
TransferHelper.safeTransferETH(msg.sender, address(this).balance);
}
require(amountETH >= amountETHMin, "IbETHRouter: receive less ETH than amountETHmin");
}
// Remove liquidity from ibETH-Alpha Pool and convert all ibETH to Alpha
// 1. Remove ibETH and Alpha from the pool.
// 2. Swap ibETH for Alpha.
// 3. Return Alpha to caller.
function removeLiquidityAllAlpha(
uint256 liquidity,
uint256 amountAlphaMin,
address to,
uint256 deadline
) public returns (uint256 amountAlpha) {
TransferHelper.safeTransferFrom(lpToken, msg.sender, address(this), liquidity);
(uint256 removeAmountAlpha, uint256 removeAmountIbETH) = IUniswapV2Router02(router).removeLiquidity(
alpha,
ibETH,
liquidity,
0,
0,
address(this),
deadline
);
address[] memory path = new address[](2);
path[0] = ibETH;
path[1] = alpha;
uint256[] memory amounts = IUniswapV2Router02(router).swapExactTokensForTokens(removeAmountIbETH, 0, path, to, deadline);
TransferHelper.safeTransfer(alpha, to, removeAmountAlpha);
amountAlpha = removeAmountAlpha.add(amounts[1]);
require(amountAlpha >= amountAlphaMin, "IbETHRouter: receive less Alpha than amountAlphaMin");
}
// Swap exact amount of ETH for Token
// 1. Receive ETH from caller
// 2. Wrap ETH to ibETH.
// 3. Swap ibETH for Token
function swapExactETHForAlpha(
uint256 amountAlphaOutMin,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts) {
IBank(ibETH).deposit.value(msg.value)();
address[] memory path = new address[](2);
path[0] = ibETH;
path[1] = alpha;
uint256[] memory swapAmounts = IUniswapV2Router02(router).swapExactTokensForTokens(IBank(ibETH).balanceOf(address(this)), amountAlphaOutMin, path, to, deadline);
amounts = new uint256[](2);
amounts[0] = msg.value;
amounts[1] = swapAmounts[1];
}
// Swap Token for exact amount of ETH
// 1. Receive Token from caller
// 2. Swap Token for ibETH.
// 3. Unwrap ibETH to ETH.
function swapAlphaForExactETH(
uint256 amountETHOut,
uint256 amountAlphaInMax,
address to,
uint256 deadline
) external returns (uint256[] memory amounts) {
TransferHelper.safeTransferFrom(alpha, msg.sender, address(this), amountAlphaInMax);
address[] memory path = new address[](2);
path[0] = alpha;
path[1] = ibETH;
IBank(ibETH).withdraw(0);
uint256[] memory swapAmounts = IUniswapV2Router02(router).swapTokensForExactTokens(ibETHForExactETH(amountETHOut), amountAlphaInMax, path, address(this), deadline);
IBank(ibETH).withdraw(swapAmounts[1]);
amounts = new uint256[](2);
amounts[0] = swapAmounts[0];
amounts[1] = address(this).balance;
TransferHelper.safeTransferETH(to, address(this).balance);
if (amountAlphaInMax > amounts[0]) {
TransferHelper.safeTransfer(alpha, msg.sender, amountAlphaInMax.sub(amounts[0]));
}
}
// Swap exact amount of Token for ETH
// 1. Receive Token from caller
// 2. Swap Token for ibETH.
// 3. Unwrap ibETH to ETH.
function swapExactAlphaForETH(
uint256 amountAlphaIn,
uint256 amountETHOutMin,
address to,
uint256 deadline
) external returns (uint256[] memory amounts) {
TransferHelper.safeTransferFrom(alpha, msg.sender, address(this), amountAlphaIn);
address[] memory path = new address[](2);
path[0] = alpha;
path[1] = ibETH;
uint256[] memory swapAmounts = IUniswapV2Router02(router).swapExactTokensForTokens(amountAlphaIn, 0, path, address(this), deadline);
IBank(ibETH).withdraw(swapAmounts[1]);
amounts = new uint256[](2);
amounts[0] = swapAmounts[0];
amounts[1] = address(this).balance;
TransferHelper.safeTransferETH(to, amounts[1]);
require(amounts[1] >= amountETHOutMin, "IbETHRouter: receive less ETH than amountETHmin");
}
// Swap ETH for exact amount of Token
// 1. Receive ETH from caller
// 2. Wrap ETH to ibETH.
// 3. Swap ibETH for Token
function swapETHForExactAlpha(
uint256 amountAlphaOut,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts) {
IBank(ibETH).deposit.value(msg.value)();
uint256 amountIbETHInMax = IBank(ibETH).balanceOf(address(this));
address[] memory path = new address[](2);
path[0] = ibETH;
path[1] = alpha;
uint256[] memory swapAmounts = IUniswapV2Router02(router).swapTokensForExactTokens(amountAlphaOut, amountIbETHInMax, path, to, deadline);
amounts = new uint256[](2);
amounts[0] = msg.value;
amounts[1] = swapAmounts[1];
// Transfer left over ETH back
if (amountIbETHInMax > swapAmounts[0]) {
IBank(ibETH).withdraw(amountIbETHInMax.sub(swapAmounts[0]));
amounts[0] = msg.value - address(this).balance;
TransferHelper.safeTransferETH(to, address(this).balance);
}
}
/// @dev Recover ERC20 tokens that were accidentally sent to this smart contract.
/// @param token The token contract. Can be anything. This contract should not hold ERC20 tokens.
/// @param to The address to send the tokens to.
/// @param value The number of tokens to transfer to `to`.
function recover(address token, address to, uint256 value) external onlyOwner {
TransferHelper.safeTransfer(token, to, value);
}
/// @dev Recover ETH that were accidentally sent to this smart contract.
/// @param to The address to send the ETH to.
/// @param value The number of ETH to transfer to `to`.
function recoverETH(address to, uint256 value) external onlyOwner {
TransferHelper.safeTransferETH(to, value);
}
}
| Add ibETH and Alpha to ibETH-Alpha Pool. All ibETH and Alpha supplied are optimally swap and add too ibETH-Alpha Pool. | function addLiquidityTwoSidesOptimal(
uint256 amountIbETHDesired,
uint256 amountAlphaDesired,
uint256 amountLPMin,
address to,
uint256 deadline
)
external
returns (
uint256 liquidity
) {
if (amountIbETHDesired > 0) {
TransferHelper.safeTransferFrom(ibETH, msg.sender, address(this), amountIbETHDesired);
}
if (amountAlphaDesired > 0) {
TransferHelper.safeTransferFrom(alpha, msg.sender, address(this), amountAlphaDesired);
}
uint256 swapAmt;
bool isReversed;
{
(uint256 r0, uint256 r1, ) = IUniswapV2Pair(lpToken).getReserves();
(uint256 ibETHReserve, uint256 alphaReserve) = IUniswapV2Pair(lpToken).token0() == ibETH ? (r0, r1) : (r1, r0);
(swapAmt, isReversed) = optimalDeposit(amountIbETHDesired, amountAlphaDesired, ibETHReserve, alphaReserve);
}
address[] memory path = new address[](2);
(path[0], path[1]) = isReversed ? (alpha, ibETH) : (ibETH, alpha);
IUniswapV2Router02(router).swapExactTokensForTokens(swapAmt, 0, path, address(this), now);
(,, liquidity) = IUniswapV2Router02(router).addLiquidity(
alpha,
ibETH,
IERC20(alpha).balanceOf(address(this)),
IBank(ibETH).balanceOf(address(this)),
0,
0,
to,
deadline
);
uint256 dustAlpha = IERC20(alpha).balanceOf(address(this));
uint256 dustIbETH = IBank(ibETH).balanceOf(address(this));
if (dustAlpha > 0) {
TransferHelper.safeTransfer(alpha, msg.sender, dustAlpha);
}
if (dustIbETH > 0) {
TransferHelper.safeTransfer(ibETH, msg.sender, dustIbETH);
}
require(liquidity >= amountLPMin, "IbETHRouter: receive less lpToken than amountLPMin");
}
| 14,115,049 | [
1,
986,
9834,
1584,
44,
471,
24277,
358,
9834,
1584,
44,
17,
9690,
8828,
18,
4826,
9834,
1584,
44,
471,
24277,
4580,
854,
5213,
1230,
7720,
471,
527,
4885,
9834,
1584,
44,
17,
9690,
8828,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
527,
48,
18988,
24237,
11710,
55,
4369,
6179,
2840,
12,
540,
203,
3639,
2254,
5034,
3844,
45,
70,
1584,
44,
25683,
16,
540,
203,
3639,
2254,
5034,
3844,
9690,
25683,
16,
540,
203,
3639,
2254,
5034,
3844,
14461,
2930,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
14096,
203,
565,
262,
203,
3639,
3903,
540,
203,
3639,
1135,
261,
2398,
203,
5411,
2254,
5034,
4501,
372,
24237,
203,
3639,
262,
288,
540,
203,
3639,
309,
261,
8949,
45,
70,
1584,
44,
25683,
405,
374,
13,
288,
203,
5411,
12279,
2276,
18,
4626,
5912,
1265,
12,
495,
1584,
44,
16,
1234,
18,
15330,
16,
1758,
12,
2211,
3631,
3844,
45,
70,
1584,
44,
25683,
1769,
377,
203,
3639,
289,
203,
3639,
309,
261,
8949,
9690,
25683,
405,
374,
13,
288,
203,
5411,
12279,
2276,
18,
4626,
5912,
1265,
12,
5429,
16,
1234,
18,
15330,
16,
1758,
12,
2211,
3631,
3844,
9690,
25683,
1769,
377,
203,
3639,
289,
540,
203,
3639,
2254,
5034,
7720,
31787,
31,
203,
3639,
1426,
28627,
7548,
31,
203,
3639,
288,
203,
5411,
261,
11890,
5034,
436,
20,
16,
2254,
5034,
436,
21,
16,
262,
273,
467,
984,
291,
91,
438,
58,
22,
4154,
12,
9953,
1345,
2934,
588,
607,
264,
3324,
5621,
203,
5411,
261,
11890,
5034,
9834,
1584,
44,
607,
6527,
16,
2254,
5034,
4190,
607,
6527,
13,
273,
467,
984,
291,
91,
438,
58,
22,
4154,
12,
9953,
1345,
2934,
2316,
20,
1435,
422,
9834,
1584,
44,
692,
261,
86,
20,
16,
436,
21,
13,
2
]
|
./partial_match/1/0x69b6fffe4A3f4A0CfA76f3cf23cC81Cc3D45138F/sources/run/media/bill/Rekoner-0/puul/puul-contracts-public/contracts/token/ERC20/ERC20.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 to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./ | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _allowances;
uint256 _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
pragma solidity >=0.6.12;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | 15,687,854 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
16351,
4232,
39,
3462,
353,
1772,
16,
467,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
389,
70,
26488,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
389,
4963,
3088,
1283,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
203,
683,
9454,
18035,
560,
1545,
20,
18,
26,
18,
2138,
31,
203,
565,
3885,
261,
1080,
3778,
508,
16,
533,
3778,
3273,
13,
1071,
288,
203,
3639,
389,
529,
273,
508,
31,
203,
3639,
389,
7175,
273,
3273,
31,
203,
3639,
389,
31734,
273,
6549,
31,
203,
565,
289,
203,
203,
565,
445,
508,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
7175,
31,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
389,
31734,
31,
203,
565,
289,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
31,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
2
]
|
pragma solidity 0.4.21;
pragma experimental "v0.5.0";
contract Owned {
address public owner;
address public newOwner;
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
assert(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != owner);
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
event OwnerUpdate(address _prevOwner, address _newOwner);
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
interface ERC20TokenInterface {
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function totalSupply() external view returns (uint256 _totalSupply);
function balanceOf(address _owner) external view returns (uint256 balance);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
interface TokenVestingInterface {
function getReleasableFunds() external view returns (uint256);
function release() external;
function setWithdrawalAddress(address _newAddress) external;
function revoke(string _reason) external view;
function getTokenBalance() external view returns (uint256);
function updateBalanceOnFunding(uint256 _amount) external;
function salvageOtherTokensFromContract(address _tokenAddress, address _to, uint _amount) external;
function salvageNotAllowedTokensSentToContract(address _to, uint _amount) external;
}
interface VestingMasterInterface {
function amountLockedInVestings() view external returns (uint256);
function substractLockedAmount(uint256 _amount) external;
function addLockedAmount(uint256 _amount) external;
function addInternalBalance(uint256 _amount) external;
}
interface ReleasingScheduleInterface {
function getReleasableFunds(address _vesting) external view returns (uint256);
}
/** @title Linear releasing schedule contract */
contract ReleasingScheduleLinearContract {
/** @dev Contains functionality for releasing funds linearly; set amount on set intervals until funds are available
* @param _startTime Start time of schedule (not first releas time)
* @param _tickDuration Interval of payouts
* @param _amountPerTick Amount to be released per interval
* @return created contracts address.
*/
using SafeMath for uint256;
uint256 public startTime;
uint256 public tickDuration;
uint256 public amountPerTick;
function ReleasingScheduleLinearContract(uint256 _startTime, uint256 _tickDuration, uint256 _amountPerTick) public{
startTime = _startTime;
tickDuration = _tickDuration;
amountPerTick = _amountPerTick;
}
function getReleasableFunds(address _vesting) public view returns (uint256){
TokenVestingContract vesting = TokenVestingContract(_vesting);
uint256 balance = ERC20TokenInterface(vesting.tokenAddress()).balanceOf(_vesting);
// check if there is balance and if it is active yet
if (balance == 0 || (startTime >= now)) {
return 0;
}
// all funds that may be released according to vesting schedule
uint256 vestingScheduleAmount = (now.sub(startTime) / tickDuration) * amountPerTick;
// deduct already released funds
uint256 releasableFunds = vestingScheduleAmount.sub(vesting.alreadyReleasedAmount());
// make sure to release remainder of funds for last payout
if (releasableFunds > balance) {
releasableFunds = balance;
}
return releasableFunds;
}
}
contract TgeOtherReleasingScheduleContract is ReleasingScheduleLinearContract {
uint256 constant releaseDate = 1578873600;
uint256 constant monthLength = 2592000;
function TgeOtherReleasingScheduleContract(uint256 _amount, uint256 _startTime) ReleasingScheduleLinearContract(_startTime - monthLength, monthLength, _amount / 12) public {
}
function getReleasableFunds(address _vesting) public view returns (uint256) {
if (now < releaseDate) {
return 0;
}
return super.getReleasableFunds(_vesting);
}
}
contract TgeTeamReleasingScheduleContract {
uint256 constant releaseDate = 1578873600;
function TgeTeamReleasingScheduleContract() public {}
function getReleasableFunds(address _vesting) public view returns (uint256) {
TokenVestingContract vesting = TokenVestingContract(_vesting);
if (releaseDate >= now) {
return 0;
} else {
return vesting.getTokenBalance();
}
}
}
/** @title Vesting contract*/
contract TokenVestingContract is Owned {
/** @dev Contains basic vesting functionality. Uses releasing schedule to ascertain amount of funds to release
* @param _beneficiary Receiver of funds.
* @param _tokenAddress Address of token contract.
* @param _revocable Allows owner to terminate vesting, but all funds yet vested still go to beneficiary. Owner gets remainder of funds back.
* @param _changable Allows that releasing schedule and withdrawal address be changed. Essentialy rendering contract not binding.
* @param _releasingScheduleContract Address of scheduling contract, that implements getReleasableFunds() function
* @return created vesting's address.
*/
using SafeMath for uint256;
address public beneficiary;
address public tokenAddress;
bool public canReceiveTokens;
bool public revocable; //
bool public changable; // allows that releasing schedule and withdrawal address be changed. Essentialy rendering contract not binding.
address public releasingScheduleContract;
bool fallbackTriggered;
bool public revoked;
uint256 public alreadyReleasedAmount;
uint256 public internalBalance;
event Released(uint256 _amount);
event RevokedAndDestroyed(string _reason);
event WithdrawalAddressSet(address _newAddress);
event TokensReceivedSinceLastCheck(uint256 _amount);
event VestingReceivedFunding(uint256 _amount);
event SetReleasingSchedule(address _addy);
event NotAllowedTokensReceived(uint256 amount);
function TokenVestingContract(address _beneficiary, address _tokenAddress, bool _canReceiveTokens, bool _revocable, bool _changable, address _releasingScheduleContract) public {
beneficiary = _beneficiary;
tokenAddress = _tokenAddress;
canReceiveTokens = _canReceiveTokens;
revocable = _revocable;
changable = _changable;
releasingScheduleContract = _releasingScheduleContract;
alreadyReleasedAmount = 0;
revoked = false;
internalBalance = 0;
fallbackTriggered = false;
}
function setReleasingSchedule(address _releasingScheduleContract) external onlyOwner {
require(changable);
releasingScheduleContract = _releasingScheduleContract;
emit SetReleasingSchedule(releasingScheduleContract);
}
function setWithdrawalAddress(address _newAddress) external onlyOwner {
beneficiary = _newAddress;
emit WithdrawalAddressSet(_newAddress);
}
/// release tokens that are already vested/releasable
function release() external returns (uint256 transferedAmount) {
checkForReceivedTokens();
require(msg.sender == beneficiary || msg.sender == owner);
uint256 amountToTransfer = ReleasingScheduleInterface(releasingScheduleContract).getReleasableFunds(this);
require(amountToTransfer > 0);
// internal accounting
alreadyReleasedAmount = alreadyReleasedAmount.add(amountToTransfer);
internalBalance = internalBalance.sub(amountToTransfer);
VestingMasterInterface(owner).substractLockedAmount(amountToTransfer);
// actual transfer
ERC20TokenInterface(tokenAddress).transfer(beneficiary, amountToTransfer);
emit Released(amountToTransfer);
return amountToTransfer;
}
function revoke(string _reason) external onlyOwner {
require(revocable);
// returns funds not yet vested according to vesting schedule
uint256 releasableFunds = ReleasingScheduleInterface(releasingScheduleContract).getReleasableFunds(this);
ERC20TokenInterface(tokenAddress).transfer(beneficiary, releasableFunds);
VestingMasterInterface(owner).substractLockedAmount(releasableFunds);
// have to do it here, can't use return, because contract selfdestructs
// returns remainder of funds to VestingMaster and kill vesting contract
VestingMasterInterface(owner).addInternalBalance(getTokenBalance());
ERC20TokenInterface(tokenAddress).transfer(owner, getTokenBalance());
emit RevokedAndDestroyed(_reason);
selfdestruct(owner);
}
function getTokenBalance() public view returns (uint256 tokenBalance) {
return ERC20TokenInterface(tokenAddress).balanceOf(address(this));
}
// master calls this when it uploads funds in order to differentiate betwen funds from master and 3rd party
function updateBalanceOnFunding(uint256 _amount) external onlyOwner {
internalBalance = internalBalance.add(_amount);
emit VestingReceivedFunding(_amount);
}
// check for changes in balance in order to track amount of locked tokens and notify master
function checkForReceivedTokens() public {
if (getTokenBalance() != internalBalance) {
uint256 receivedFunds = getTokenBalance().sub(internalBalance);
// if not allowed to receive tokens, do not account for them
if (canReceiveTokens) {
internalBalance = getTokenBalance();
VestingMasterInterface(owner).addLockedAmount(receivedFunds);
} else {
emit NotAllowedTokensReceived(receivedFunds);
}
emit TokensReceivedSinceLastCheck(receivedFunds);
}
fallbackTriggered = true;
}
function salvageOtherTokensFromContract(address _tokenAddress, address _to, uint _amount) external onlyOwner {
require(_tokenAddress != tokenAddress);
ERC20TokenInterface(_tokenAddress).transfer(_to, _amount);
}
function salvageNotAllowedTokensSentToContract(address _to, uint _amount) external onlyOwner {
// check if there are any new tokens
checkForReceivedTokens();
// only allow sending tokens, that were not allowed to be sent to contract
require(_amount <= getTokenBalance() - internalBalance);
ERC20TokenInterface(tokenAddress).transfer(_to, _amount);
}
function () external{
fallbackTriggered = true;
}
}
contract VestingMasterContract is Owned {
using SafeMath for uint256;
address public tokenAddress;
bool public canReceiveTokens;
address public moderator;
uint256 public internalBalance;
uint256 public amountLockedInVestings;
bool public fallbackTriggered;
struct VestingStruct {
uint256 arrayPointer;
// custom data
address beneficiary;
address releasingScheduleContract;
string vestingType;
uint256 vestingVersion;
}
address[] public vestingAddresses;
mapping(address => VestingStruct) public addressToVestingStruct;
mapping(address => address) public beneficiaryToVesting;
event VestingContractFunded(address beneficiary, address tokenAddress, uint256 amount);
event LockedAmountDecreased(uint256 amount);
event LockedAmountIncreased(uint256 amount);
event TokensReceivedSinceLastCheck(uint256 amount);
event TokensReceivedWithApproval(uint256 amount, bytes extraData);
event NotAllowedTokensReceived(uint256 amount);
function VestingMasterContract(address _tokenAddress, bool _canReceiveTokens) public{
tokenAddress = _tokenAddress;
canReceiveTokens = _canReceiveTokens;
internalBalance = 0;
amountLockedInVestings = 0;
}
// todo: make storage lib
////////// STORAGE HELPERS ///////////
function vestingExists(address _vestingAddress) public view returns (bool exists){
if (vestingAddresses.length == 0) {return false;}
return (vestingAddresses[addressToVestingStruct[_vestingAddress].arrayPointer] == _vestingAddress);
}
function storeNewVesting(address _vestingAddress, address _beneficiary, address _releasingScheduleContract, string _vestingType, uint256 _vestingVersion) internal onlyOwner returns (uint256 vestingsLength) {
require(!vestingExists(_vestingAddress));
addressToVestingStruct[_vestingAddress].beneficiary = _beneficiary;
addressToVestingStruct[_vestingAddress].releasingScheduleContract = _releasingScheduleContract;
addressToVestingStruct[_vestingAddress].vestingType = _vestingType;
addressToVestingStruct[_vestingAddress].vestingVersion = _vestingVersion;
beneficiaryToVesting[_beneficiary] = _vestingAddress;
addressToVestingStruct[_vestingAddress].arrayPointer = vestingAddresses.push(_vestingAddress) - 1;
return vestingAddresses.length;
}
function deleteVestingFromStorage(address _vestingAddress) internal onlyOwner returns (uint256 vestingsLength) {
require(vestingExists(_vestingAddress));
delete (beneficiaryToVesting[addressToVestingStruct[_vestingAddress].beneficiary]);
uint256 indexToDelete = addressToVestingStruct[_vestingAddress].arrayPointer;
address keyToMove = vestingAddresses[vestingAddresses.length - 1];
vestingAddresses[indexToDelete] = keyToMove;
addressToVestingStruct[keyToMove].arrayPointer = indexToDelete;
vestingAddresses.length--;
return vestingAddresses.length;
}
function addVesting(address _vestingAddress, address _beneficiary, address _releasingScheduleContract, string _vestingType, uint256 _vestingVersion) public {
uint256 vestingBalance = TokenVestingInterface(_vestingAddress).getTokenBalance();
amountLockedInVestings = amountLockedInVestings.add(vestingBalance);
storeNewVesting(_vestingAddress, _beneficiary, _releasingScheduleContract, _vestingType, _vestingVersion);
}
/// releases funds to beneficiary
function releaseVesting(address _vestingContract) external {
require(vestingExists(_vestingContract));
require(msg.sender == addressToVestingStruct[_vestingContract].beneficiary || msg.sender == owner || msg.sender == moderator);
TokenVestingInterface(_vestingContract).release();
}
/// Transfers releasable funds from vesting to beneficiary (caller of this method)
function releaseMyTokens() external {
address vesting = beneficiaryToVesting[msg.sender];
require(vesting != 0);
TokenVestingInterface(vesting).release();
}
// add funds to vesting contract
function fundVesting(address _vestingContract, uint256 _amount) public onlyOwner {
// convenience, so you don't have to call it manualy if you just uploaded funds
checkForReceivedTokens();
// check if there is actually enough funds
require((internalBalance >= _amount) && (getTokenBalance() >= _amount));
// make sure that fundee is vesting contract on the list
require(vestingExists(_vestingContract));
internalBalance = internalBalance.sub(_amount);
ERC20TokenInterface(tokenAddress).transfer(_vestingContract, _amount);
TokenVestingInterface(_vestingContract).updateBalanceOnFunding(_amount);
emit VestingContractFunded(_vestingContract, tokenAddress, _amount);
}
function getTokenBalance() public constant returns (uint256) {
return ERC20TokenInterface(tokenAddress).balanceOf(address(this));
}
// revoke vesting; release releasable funds to beneficiary and return remaining to master and kill vesting contract
function revokeVesting(address _vestingContract, string _reason) external onlyOwner {
TokenVestingInterface subVestingContract = TokenVestingInterface(_vestingContract);
subVestingContract.revoke(_reason);
deleteVestingFromStorage(_vestingContract);
}
// when vesting is revoked it sends back remaining tokens and updates internalBalance
function addInternalBalance(uint256 _amount) external {
require(vestingExists(msg.sender));
internalBalance = internalBalance.add(_amount);
}
// vestings notifies if there has been any changes in amount of locked tokens
function addLockedAmount(uint256 _amount) external {
require(vestingExists(msg.sender));
amountLockedInVestings = amountLockedInVestings.add(_amount);
emit LockedAmountIncreased(_amount);
}
// vestings notifies if there has been any changes in amount of locked tokens
function substractLockedAmount(uint256 _amount) external {
require(vestingExists(msg.sender));
amountLockedInVestings = amountLockedInVestings.sub(_amount);
emit LockedAmountDecreased(_amount);
}
// check for changes in balance in order to track amount of locked tokens
function checkForReceivedTokens() public {
if (getTokenBalance() != internalBalance) {
uint256 receivedFunds = getTokenBalance().sub(internalBalance);
if (canReceiveTokens) {
amountLockedInVestings = amountLockedInVestings.add(receivedFunds);
internalBalance = getTokenBalance();
}
else {
emit NotAllowedTokensReceived(receivedFunds);
}
emit TokensReceivedSinceLastCheck(receivedFunds);
} else {
emit TokensReceivedSinceLastCheck(0);
}
fallbackTriggered = false;
}
function salvageNotAllowedTokensSentToContract(address _contractFrom, address _to, uint _amount) external onlyOwner {
if (_contractFrom == address(this)) {
// check if there are any new tokens
checkForReceivedTokens();
// only allow sending tokens, that were not allowed to be sent to contract
require(_amount <= getTokenBalance() - internalBalance);
ERC20TokenInterface(tokenAddress).transfer(_to, _amount);
}
if (vestingExists(_contractFrom)) {
TokenVestingInterface(_contractFrom).salvageNotAllowedTokensSentToContract(_to, _amount);
}
}
function salvageOtherTokensFromContract(address _tokenAddress, address _contractAddress, address _to, uint _amount) external onlyOwner {
require(_tokenAddress != tokenAddress);
if (_contractAddress == address(this)) {
ERC20TokenInterface(_tokenAddress).transfer(_to, _amount);
}
if (vestingExists(_contractAddress)) {
TokenVestingInterface(_contractAddress).salvageOtherTokensFromContract(_tokenAddress, _to, _amount);
}
}
function killContract() external onlyOwner {
require(vestingAddresses.length == 0);
ERC20TokenInterface(tokenAddress).transfer(owner, getTokenBalance());
selfdestruct(owner);
}
function setWithdrawalAddress(address _vestingContract, address _beneficiary) external {
require(vestingExists(_vestingContract));
TokenVestingContract vesting = TokenVestingContract(_vestingContract);
// withdrawal address can be changed only by beneficiary or in case vesting is changable also by owner
require(msg.sender == vesting.beneficiary() || (msg.sender == owner && vesting.changable()));
TokenVestingInterface(_vestingContract).setWithdrawalAddress(_beneficiary);
addressToVestingStruct[_vestingContract].beneficiary = _beneficiary;
}
function receiveApproval(address _from, uint256 _amount, address _tokenAddress, bytes _extraData) external {
require(canReceiveTokens);
require(_tokenAddress == tokenAddress);
ERC20TokenInterface(_tokenAddress).transferFrom(_from, address(this), _amount);
amountLockedInVestings = amountLockedInVestings.add(_amount);
internalBalance = internalBalance.add(_amount);
emit TokensReceivedWithApproval(_amount, _extraData);
}
// Deploys a vesting contract to _beneficiary. Assumes that a releasing
// schedule contract has already been deployed, so we pass it the address
// of that contract as _releasingSchedule
function deployVesting(
address _beneficiary,
string _vestingType,
uint256 _vestingVersion,
bool _canReceiveTokens,
bool _revocable,
bool _changable,
address _releasingSchedule
) public onlyOwner {
TokenVestingContract newVesting = new TokenVestingContract(_beneficiary, tokenAddress, _canReceiveTokens, _revocable, _changable, _releasingSchedule);
addVesting(newVesting, _beneficiary, _releasingSchedule, _vestingType, _vestingVersion);
}
function deployOtherVesting(
address _beneficiary,
uint256 _amount,
uint256 _startTime
) public onlyOwner {
TgeOtherReleasingScheduleContract releasingSchedule = new TgeOtherReleasingScheduleContract(_amount, _startTime);
TokenVestingContract newVesting = new TokenVestingContract(_beneficiary, tokenAddress, true, true, true, releasingSchedule);
addVesting(newVesting, _beneficiary, releasingSchedule, 'other', 1);
fundVesting(newVesting, _amount);
}
function deployTgeTeamVesting(
address _beneficiary,
uint256 _amount
) public onlyOwner {
TgeTeamReleasingScheduleContract releasingSchedule = new TgeTeamReleasingScheduleContract();
TokenVestingContract newVesting = new TokenVestingContract(_beneficiary, tokenAddress, true, true, true, releasingSchedule);
addVesting(newVesting, _beneficiary, releasingSchedule, 'X8 team', 1);
fundVesting(newVesting, _amount);
}
/**
* Used to transfer ownership of a vesting contract to this master contract.
* The vesting contracts require that the master contract be their owner.
* Use this when you deploy a TokenVestingContract manually and need to transfer
* ownership to this master contract. First call transferOwnership on the vesting
* contract.
* @param _vesting the vesting contract of which to accept ownership.
*/
function acceptOwnershipOfVesting(address _vesting) external onlyOwner {
TokenVestingContract(_vesting).acceptOwnership();
}
function setModerator(address _moderator) external onlyOwner {
moderator = _moderator;
}
function () external{
fallbackTriggered = true;
}
} | * @dev Contains functionality for releasing funds linearly; set amount on set intervals until funds are available @param _startTime Start time of schedule (not first releas time) @param _tickDuration Interval of payouts @param _amountPerTick Amount to be released per interval @return created contracts address./ | function ReleasingScheduleLinearContract(uint256 _startTime, uint256 _tickDuration, uint256 _amountPerTick) public{
startTime = _startTime;
tickDuration = _tickDuration;
amountPerTick = _amountPerTick;
}
| 944,202 | [
1,
10846,
14176,
364,
6707,
11730,
284,
19156,
9103,
715,
31,
444,
3844,
603,
444,
10389,
3180,
284,
19156,
854,
2319,
225,
389,
1937,
950,
3603,
813,
434,
4788,
261,
902,
1122,
6707,
345,
813,
13,
225,
389,
6470,
5326,
10803,
434,
293,
2012,
87,
225,
389,
8949,
2173,
6264,
16811,
358,
506,
15976,
1534,
3673,
327,
2522,
20092,
1758,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
4275,
73,
11730,
6061,
15982,
8924,
12,
11890,
5034,
389,
1937,
950,
16,
2254,
5034,
389,
6470,
5326,
16,
2254,
5034,
389,
8949,
2173,
6264,
13,
1071,
95,
203,
3639,
8657,
273,
389,
1937,
950,
31,
203,
3639,
4024,
5326,
273,
389,
6470,
5326,
31,
203,
3639,
3844,
2173,
6264,
273,
389,
8949,
2173,
6264,
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
]
|
./partial_match/56/0x282CF833fF20DdB93384AbA81eE63847f4d8366A/sources/ChainlinkClient.sol | * @dev Reverts if the sender is not the oracle of the request. Emits ChainlinkFulfilled event. @param requestId The request ID for fulfillment/ | modifier recordChainlinkFulfillment(bytes32 requestId) {
require(
msg.sender == s_pendingRequests[requestId],
"Source must be the oracle of the request"
);
delete s_pendingRequests[requestId];
emit ChainlinkFulfilled(requestId);
_;
}
| 11,131,516 | [
1,
426,
31537,
309,
326,
5793,
353,
486,
326,
20865,
434,
326,
590,
18,
7377,
1282,
7824,
1232,
23747,
13968,
871,
18,
225,
14459,
1021,
590,
1599,
364,
22290,
475,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
9606,
1409,
3893,
1232,
23747,
5935,
475,
12,
3890,
1578,
14459,
13,
288,
203,
3639,
2583,
12,
203,
5411,
1234,
18,
15330,
422,
272,
67,
9561,
6421,
63,
2293,
548,
6487,
203,
5411,
315,
1830,
1297,
506,
326,
20865,
434,
326,
590,
6,
203,
3639,
11272,
203,
3639,
1430,
272,
67,
9561,
6421,
63,
2293,
548,
15533,
203,
3639,
3626,
7824,
1232,
23747,
13968,
12,
2293,
548,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x2B1848501594ef66e330EfF4064E7b84a0eFDF5f/sources/FLOKI2.sol | Anti-bot and anti-whale mappings and variables exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount | contract FLOKI2 is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public lpBurnEnabled = false;
uint256 public lpBurnFrequency = 1360000000000 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 43210 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = true;
bool public swapEnabled = true;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("Floki 2.0", "FLOKI2.0") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 0;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 99;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1 * 1e9 * 1e18;
maxTransactionAmount = 1000000000000000000000000000;
maxWallet = 20000000000000000000000000;
swapTokensAtAmount = totalSupply * 10 / 3000;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 10 / 1000, "Swap amount cannot be higher than 1% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 25, "Must keep fees at 25% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 99, "Must keep fees at 99% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
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 addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
deadAddress,
block.timestamp
);
}
uniswapV2Router.addLiquidityETH{value: ethAmount}(
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
(success,) = address(devWallet).call{value: ethForDev}("");
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner {
require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes");
require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%");
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool){
lastLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
pair.sync();
emit AutoNukeLP();
return true;
}
function autoBurnLiquidityPairTokens() internal returns (bool){
lastLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
pair.sync();
emit AutoNukeLP();
return true;
}
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
pair.sync();
emit ManualNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
pair.sync();
emit ManualNukeLP();
return true;
}
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
} | 9,319,381 | [
1,
14925,
77,
17,
4819,
471,
30959,
17,
3350,
5349,
7990,
471,
3152,
431,
17704,
1317,
628,
1656,
281,
471,
943,
2492,
3844,
1707,
6138,
716,
279,
5859,
13667,
312,
6388,
5574,
18,
5502,
7412,
358,
4259,
6138,
3377,
506,
3221,
358,
279,
4207,
7412,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
6835,
478,
1502,
47,
45,
22,
353,
4232,
39,
3462,
16,
14223,
6914,
225,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
11732,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
565,
1758,
1071,
11732,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
565,
1758,
1071,
5381,
8363,
1887,
273,
1758,
12,
20,
92,
22097,
1769,
203,
203,
565,
1426,
3238,
7720,
1382,
31,
203,
203,
565,
1758,
1071,
13667,
310,
16936,
31,
203,
565,
1758,
1071,
4461,
16936,
31,
203,
377,
203,
565,
2254,
5034,
1071,
943,
3342,
6275,
31,
203,
565,
2254,
5034,
1071,
7720,
5157,
861,
6275,
31,
203,
565,
2254,
5034,
1071,
943,
16936,
31,
203,
377,
203,
565,
1426,
1071,
12423,
38,
321,
1526,
273,
629,
31,
203,
565,
2254,
5034,
1071,
12423,
38,
321,
13865,
273,
404,
5718,
2787,
9449,
3974,
31,
203,
565,
2254,
5034,
1071,
1142,
48,
84,
38,
321,
950,
31,
203,
377,
203,
565,
2254,
5034,
1071,
11297,
38,
321,
13865,
273,
1059,
1578,
2163,
6824,
31,
203,
565,
2254,
5034,
1071,
1142,
25139,
48,
84,
38,
321,
950,
31,
203,
203,
565,
1426,
1071,
8181,
382,
12477,
273,
638,
31,
203,
565,
1426,
1071,
1284,
7459,
3896,
273,
638,
31,
203,
565,
1426,
1071,
7720,
1526,
273,
638,
31,
203,
377,
203,
565,
1426,
1071,
7412,
6763,
1526,
273,
638,
31,
203,
203,
565,
2254,
5034,
1071,
30143,
5269,
2954,
281,
31,
203,
565,
2254,
2
]
|
pragma solidity ^0.4.23;
/**
* @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
*/
contract ERC721 {
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
function implementsERC721() public pure returns (bool);
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
}
/**
* @title Interface of auction contract
*/
interface CurioAuction {
function isCurioAuction() external returns (bool);
function withdrawBalance() external;
function setAuctionPriceLimit(uint256 _newAuctionPriceLimit) external;
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external;
}
/**
* @title Curio
* @dev Curio core contract implements ERC721 token.
*/
contract Curio is ERC721 {
event Create(
address indexed owner,
uint256 indexed tokenId,
string name
);
event ContractUpgrade(address newContract);
struct Token {
string name;
}
// Name and symbol of ERC721 token
string public constant NAME = "Curio";
string public constant SYMBOL = "CUR";
// Array of token's data
Token[] tokens;
// A mapping from token IDs to the address that owns them
mapping (uint256 => address) public tokenIndexToOwner;
// A mapping from owner address to count of tokens that address owns
mapping (address => uint256) ownershipTokenCount;
// A mapping from token IDs to an address that has been approved
mapping (uint256 => address) public tokenIndexToApproved;
address public ownerAddress;
address public adminAddress;
bool public paused = false;
// The address of new contract when this contract was upgraded
address public newContractAddress;
// The address of CurioAuction contract that handles sales of tokens
CurioAuction public auction;
// Restriction on release of tokens
uint256 public constant TOTAL_SUPPLY_LIMIT = 900;
// Count of released tokens
uint256 public releaseCreatedCount;
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == ownerAddress);
_;
}
/**
* @dev Throws if called by any account other than the admin.
*/
modifier onlyAdmin() {
require(msg.sender == adminAddress);
_;
}
/**
* @dev Throws if called by any account other than the owner or admin.
*/
modifier onlyOwnerOrAdmin() {
require(
msg.sender == adminAddress ||
msg.sender == ownerAddress
);
_;
}
/**
* @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 Constructor function
*/
constructor() public {
// Contract paused after start
paused = true;
// Set owner and admin addresses
ownerAddress = msg.sender;
adminAddress = msg.sender;
}
// -----------------------------------------
// External interface
// -----------------------------------------
/**
* @dev Check implementing ERC721 standard (needed in auction contract).
*/
function implementsERC721() public pure returns (bool) {
return true;
}
/**
* @dev Default payable function rejects all Ether from being sent here, unless it's from auction contract.
*/
function() external payable {
require(msg.sender == address(auction));
}
/**
* @dev Transfer all Ether from this contract to owner.
*/
function withdrawBalance() external onlyOwner {
ownerAddress.transfer(address(this).balance);
}
/**
* @dev Returns the total number of tokens currently in existence.
*/
function totalSupply() public view returns (uint) {
return tokens.length;
}
/**
* @dev Returns the number of tokens owned by a specific address.
* @param _owner The owner address to check
*/
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/**
* @dev Returns the address currently assigned ownership of a given token.
* @param _tokenId The ID of the token
*/
function ownerOf(uint256 _tokenId) external view returns (address owner) {
owner = tokenIndexToOwner[_tokenId];
require(owner != address(0));
}
/**
* @dev Returns information about token.
* @param _id The ID of the token
*/
function getToken(uint256 _id) external view returns (string name) {
Token storage token = tokens[_id];
name = token.name;
}
/**
* @dev Set new owner address. Only available to the current owner.
* @param _newOwner The address of the new owner
*/
function setOwner(address _newOwner) onlyOwner external {
require(_newOwner != address(0));
ownerAddress = _newOwner;
}
/**
* @dev Set new admin address. Only available to owner.
* @param _newAdmin The address of the new admin
*/
function setAdmin(address _newAdmin) onlyOwner external {
require(_newAdmin != address(0));
adminAddress = _newAdmin;
}
/**
* @dev Set new auction price limit.
* @param _newAuctionPriceLimit Start and end price limit
*/
function setAuctionPriceLimit(uint256 _newAuctionPriceLimit) onlyOwnerOrAdmin external {
auction.setAuctionPriceLimit(_newAuctionPriceLimit);
}
/**
* @dev Set the address of upgraded contract.
* @param _newContract Address of new contract
*/
function setNewAddress(address _newContract) onlyOwner whenPaused external {
newContractAddress = _newContract;
emit ContractUpgrade(_newContract);
}
/**
* @dev Pause the contract. Called by owner or admin to pause the contract.
*/
function pause() onlyOwnerOrAdmin whenNotPaused external {
paused = true;
}
/**
* @dev Unpause the contract. Can only be called by owner, since
* one reason we may pause the contract is when admin account is
* compromised. Requires auction contract addresses
* to be set before contract can be unpaused. Also, we can't have
* newContractAddress set either, because then the contract was upgraded.
*/
function unpause() onlyOwner whenPaused public {
require(auction != address(0));
require(newContractAddress == address(0));
paused = false;
}
/**
* @dev Transfer a token to another address.
* @param _to The address of the recipient, can be a user or contract
* @param _tokenId The ID of the token to transfer
*/
function transfer(
address _to,
uint256 _tokenId
)
whenNotPaused
external
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any tokens (except very briefly
// after a release token is created and before it goes on auction).
require(_to != address(this));
// Disallow transfers to the auction contract to prevent accidental
// misuse. Auction contracts should only take ownership of tokens
// through the allow + transferFrom flow.
require(_to != address(auction));
// Check token ownership
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/**
* @dev Grant another address the right to transfer a specific token via
* transferFrom(). This is the preferred flow for transfering NFTs to contracts.
* @param _to The address to be granted transfer approval. Pass address(0) to
* clear all approvals
* @param _tokenId The ID of the token that can be transferred if this call succeeds
*/
function approve(
address _to,
uint256 _tokenId
)
whenNotPaused
external
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
emit Approval(msg.sender, _to, _tokenId);
}
/**
* @dev Transfers 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 to be transferred
* @param _to The address that should 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
)
whenNotPaused
external
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any tokens (except very briefly
// after a release token is created and before it goes on auction).
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/**
* @dev Returns a list of all tokens assigned to an address.
* @param _owner The owner whose tokens we are interested in
* @notice This method MUST NEVER be called by smart contract code. First, it's fairly
* expensive (it walks the entire token array looking for tokens 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 totalTokens = totalSupply();
uint256 resultIndex = 0;
uint256 tokenId;
for (tokenId = 0; tokenId <= totalTokens; tokenId++) {
if (tokenIndexToOwner[tokenId] == _owner) {
result[resultIndex] = tokenId;
resultIndex++;
}
}
return result;
}
}
/**
* @dev Set the reference to the auction contract.
* @param _address Address of auction contract
*/
function setAuctionAddress(address _address) onlyOwner external {
CurioAuction candidateContract = CurioAuction(_address);
require(candidateContract.isCurioAuction());
// Set the new contract address
auction = candidateContract;
}
/**
* @dev Put a token up for auction.
* @param _tokenId ID of token to auction, sender must be owner
* @param _startingPrice Price of item (in wei) at beginning of auction
* @param _endingPrice Price of item (in wei) at end of auction
* @param _duration Length of auction (in seconds)
*/
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
whenNotPaused
external
{
// Auction contract checks input sizes
// If token is already on any auction, this will throw because it will be owned by the auction contract
require(_owns(msg.sender, _tokenId));
// Set auction contract as approved for token
_approve(_tokenId, auction);
// Sale auction throws if inputs are invalid
auction.createAuction(
_tokenId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/**
* @dev Transfers the balance of the auction contract to this contract by owner or admin.
*/
function withdrawAuctionBalance() onlyOwnerOrAdmin external {
auction.withdrawBalance();
}
/**
* @dev Creates a new release token with the given name and creates an auction for it.
* @param _name Name ot the token
* @param _startingPrice Price of item (in wei) at beginning of auction
* @param _endingPrice Price of item (in wei) at end of auction
* @param _duration Length of auction (in seconds)
*/
function createReleaseTokenAuction(
string _name,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
onlyAdmin
external
{
// Check release tokens limit
require(releaseCreatedCount < TOTAL_SUPPLY_LIMIT);
// Create token and tranfer ownership to this contract
uint256 tokenId = _createToken(_name, address(this));
// Set auction address as approved for release token
_approve(tokenId, auction);
// Call createAuction in auction contract
auction.createAuction(
tokenId,
_startingPrice,
_endingPrice,
_duration,
address(this)
);
releaseCreatedCount++;
}
/**
* @dev Creates free token and transfer it to recipient.
* @param _name Name of the token
* @param _to The address of the recipient, can be a user or contract
*/
function createFreeToken(
string _name,
address _to
)
onlyAdmin
external
{
require(_to != address(0));
require(_to != address(this));
require(_to != address(auction));
// Check release tokens limit
require(releaseCreatedCount < TOTAL_SUPPLY_LIMIT);
// Create token and transfer to owner
_createToken(_name, _to);
releaseCreatedCount++;
}
// -----------------------------------------
// Internal interface
// -----------------------------------------
/**
* @dev Create a new token and stores it.
* @param _name Token name
* @param _owner The initial owner of this token, must be non-zero
*/
function _createToken(
string _name,
address _owner
)
internal
returns (uint)
{
Token memory _token = Token({
name: _name
});
uint256 newTokenId = tokens.push(_token) - 1;
// Check overflow newTokenId
require(newTokenId == uint256(uint32(newTokenId)));
emit Create(_owner, newTokenId, _name);
// This will assign ownership
_transfer(0, _owner, newTokenId);
return newTokenId;
}
/**
* @dev Check claimant address as token owner.
* @param _claimant The address we are validating against
* @param _tokenId Token id, only valid when > 0
*/
function _owns(
address _claimant,
uint256 _tokenId
)
internal
view
returns (bool)
{
return tokenIndexToOwner[_tokenId] == _claimant;
}
/**
* @dev Check if a given address currently has transferApproval for a particular token.
* @param _claimant The address we are confirming token is approved for
* @param _tokenId Token id, only valid when > 0
*/
function _approvedFor(
address _claimant,
uint256 _tokenId
)
internal
view
returns (bool)
{
return tokenIndexToApproved[_tokenId] == _claimant;
}
/**
* @dev Marks an address as being approved for transferFrom().
* Setting _approved to address(0) clears all transfer approval.
* NOTE: _approve() does NOT send the Approval event. This is intentional because
* _approve() and transferFrom() are used together for putting tokens on auction, and
* there is no value in spamming the log with Approval events in that case.
*/
function _approve(
uint256 _tokenId,
address _approved
)
internal
{
tokenIndexToApproved[_tokenId] = _approved;
}
/**
* @dev Assigns ownership of a specific token to an address.
*/
function _transfer(
address _from,
address _to,
uint256 _tokenId
)
internal
{
ownershipTokenCount[_to]++;
// Transfer ownership
tokenIndexToOwner[_tokenId] = _to;
// When creating new token _from is 0x0, but we can't account that address
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// Clear any previously approved ownership exchange
delete tokenIndexToApproved[_tokenId];
}
emit Transfer(_from, _to, _tokenId);
}
} | A mapping from owner address to count of tokens that address owns | mapping (address => uint256) ownershipTokenCount;
| 5,995,072 | [
1,
37,
2874,
628,
3410,
1758,
358,
1056,
434,
2430,
716,
1758,
29065,
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,
225,
2874,
261,
2867,
516,
2254,
5034,
13,
23178,
1345,
1380,
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
]
|
/*
Copyright (c) 2020 Fuel Labs
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.1;
/*
Authors: DappHub
License: GNU
Modified by: FuelLabs
*/
contract DSMath {
function ds_add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function ds_sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function ds_mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
}
contract ERC20 {
// METHODS
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
// EVENTS
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract FuelConstants {
// CONSTANTS
uint256 constant public BOND_SIZE = .1 ether; // required for block commitment
uint256 constant public FINALIZATION_DELAY = 7 days / 12; // ~ 1 weeks at 12 second block times
uint256 constant public SUBMISSION_DELAY = uint256(2 days) / 12; // ~ 2 day (should be 2 days) in Ethereum Blocks
uint256 constant public CLOSING_DELAY = uint256(90 days) / 12; // (should be 2 months)
uint256 constant public MAX_TRANSACTIONS_SIZE = 58823;
uint256 constant public TRANSACTION_ROOTS_MAX = 256;
// ASSEMBLY ONLY FRAUD CODES
uint256 constant FraudCode_InvalidMetadataBlockHeight = 0;
uint256 constant FraudCode_TransactionHashZero = 1;
uint256 constant FraudCode_TransactionIndexOverflow = 2;
uint256 constant FraudCode_MetadataOutputIndexOverflow = 3;
uint256 constant FraudCode_InvalidUTXOHashReference = 4;
uint256 constant FraudCode_InvalidReturnWitnessNotSpender = 5;
uint256 constant FraudCode_InputDoubleSpend = 6;
uint256 constant FraudCode_InvalidMerkleTreeRoot = 7;
uint256 constant FraudCode_MetadataBlockHeightUnderflow = 8;
uint256 constant FraudCode_MetadataBlockHeightOverflow = 9;
uint256 constant FraudCode_InvalidHTLCDigest = 10;
uint256 constant FraudCode_TransactionLengthUnderflow = 11;
uint256 constant FraudCode_TransactionLengthOverflow = 12;
uint256 constant FraudCode_InvalidTransactionInputType = 13;
uint256 constant FraudCode_TransactionOutputWitnessReferenceOverflow = 14;
uint256 constant FraudCode_InvalidTransactionOutputType = 15;
uint256 constant FraudCode_TransactionSumMismatch = 16;
uint256 constant FraudCode_TransactionInputWitnessReferenceOverflow = 17;
uint256 constant FraudCode_TransactionInputDepositZero = 18;
uint256 constant FraudCode_TransactionInputDepositWitnessOverflow = 19;
uint256 constant FraudCode_TransactionHTLCWitnessOverflow = 20;
uint256 constant FraudCode_TransactionOutputAmountLengthUnderflow = 21;
uint256 constant FraudCode_TransactionOutputAmountLengthOverflow = 22;
uint256 constant FraudCode_TransactionOutputTokenIDOverflow = 23;
uint256 constant FraudCode_TransactionOutputHTLCDigestZero = 24;
uint256 constant FraudCode_TransactionOutputHTLCExpiryZero = 25;
uint256 constant FraudCode_InvalidTransactionWitnessSignature = 26;
uint256 constant FraudCode_TransactionWitnessesLengthUnderflow = 27;
uint256 constant FraudCode_TransactionWitnessesLengthOverflow = 28;
uint256 constant FraudCode_TransactionInputsLengthUnderflow = 29;
uint256 constant FraudCode_TransactionInputsLengthOverflow = 30;
uint256 constant FraudCode_TransactionOutputsLengthUnderflow = 31;
uint256 constant FraudCode_TransactionOutputsLengthOverflow = 32;
uint256 constant FraudCode_TransactionMetadataLengthOverflow = 33;
uint256 constant FraudCode_TransactionInputSelectorOverflow = 34;
uint256 constant FraudCode_TransactionOutputSelectorOverflow = 35;
uint256 constant FraudCode_TransactionWitnessSelectorOverflow = 37;
uint256 constant FraudCode_TransactionUTXOType = 38;
uint256 constant FraudCode_TransactionUTXOOutputIndexOverflow = 39;
uint256 constant FraudCode_InvalidTransactionsNetLength = 40;
uint256 constant FraudCode_MetadataTransactionsRootsLengthOverflow = 41;
uint256 constant FraudCode_ComputedTransactionLengthOverflow = 42;
uint256 constant FraudCode_ProvidedDataOverflow = 43;
uint256 constant FraudCode_MetadataReferenceOverflow = 44;
uint256 constant FraudCode_OutputHTLCExpiryUnderflow = 45;
uint256 constant FraudCode_InvalidInputWithdrawalSpend = 46;
uint256 constant FraudCode_InvalidTypeReferenceMismatch = 47;
uint256 constant FraudCode_InvalidChangeInputSpender = 48;
uint256 constant FraudCode_InvalidTransactionRootIndexOverflow = 49;
// ASSEMBLY ONLY ERROR CODES
uint256 constant ErrorCode_InvalidTypeDeposit = 0;
uint256 constant ErrorCode_InputReferencedNotProvided = 1;
uint256 constant ErrorCode_InvalidReturnWitnessSelected = 2;
uint256 constant ErrroCode_InvalidReturnWitnessAddressEmpty = 3;
uint256 constant ErrroCode_InvalidSpenderWitnessAddressEmpty = 4;
uint256 constant ErrorCode_InvalidTransactionComparison = 5;
uint256 constant ErrorCode_WithdrawalAlreadyHappened = 6;
uint256 constant ErrorCode_BlockProducerNotCaller = 7;
uint256 constant ErrorCode_BlockBondAlreadyWithdrawn = 8;
uint256 constant ErrorCode_InvalidProofType = 9;
uint256 constant ErrorCode_BlockHashNotFound = 10;
uint256 constant ErrorCode_BlockHeightOverflow = 11;
uint256 constant ErrorCode_BlockHeightUnderflow = 12;
uint256 constant ErrorCode_BlockNotFinalized = 13;
uint256 constant ErrorCode_BlockFinalized = 14;
uint256 constant ErrorCode_TransactionRootLengthUnderflow = 15;
uint256 constant ErrorCode_TransactionRootIndexOverflow = 16;
uint256 constant ErrorCode_TransactionRootHashNotInBlockHeader = 17;
uint256 constant ErrorCode_TransactionRootHashInvalid = 18;
uint256 constant ErrorCode_TransactionLeafHashInvalid = 19;
uint256 constant ErrorCode_MerkleTreeHeightOverflow = 20;
uint256 constant ErrorCode_MerkleTreeRootInvalid = 21;
uint256 constant ErrorCode_InputIndexSelectedOverflow = 22;
uint256 constant ErrorCode_OutputIndexSelectedOverflow = 23;
uint256 constant ErrorCode_WitnessIndexSelectedOverflow = 24;
uint256 constant ErrorCode_TransactionUTXOIDInvalid = 25;
uint256 constant ErrorCode_FraudBlockHeightUnderflow = 26;
uint256 constant ErrorCode_FraudBlockFinalized = 27;
uint256 constant ErrorCode_SafeMathAdditionOverflow = 28;
uint256 constant ErrorCode_SafeMathSubtractionUnderflow = 29;
uint256 constant ErrorCode_SafeMathMultiplyOverflow = 30;
uint256 constant ErrorCode_TransferAmountUnderflow = 31;
uint256 constant ErrorCode_TransferOwnerInvalid = 32;
uint256 constant ErrorCode_TransferTokenIDOverflow = 33;
uint256 constant ErrorCode_TransferEtherCallResult = 34;
uint256 constant ErrorCode_TransferERC20Result = 35;
uint256 constant ErrorCode_TransferTokenAddress = 36;
uint256 constant ErrorCode_InvalidPreviousBlockHash = 37;
uint256 constant ErrorCode_TransactionRootsLengthUnderflow = 38;
uint256 constant ErrorCode_TransactionRootsLengthOverflow = 39;
uint256 constant ErrorCode_InvalidWithdrawalOutputType = 40;
uint256 constant ErrorCode_InvalidWithdrawalOwner = 41;
uint256 constant ErrorCode_InvalidDepositProof = 42;
uint256 constant ErrorCode_InvalidTokenAddress = 43;
uint256 constant ErrorCode_InvalidBlockHeightReference = 44;
uint256 constant ErrorCode_InvalidOutputIndexReference = 45;
uint256 constant ErrorCode_InvalidTransactionRootReference = 46;
uint256 constant ErrorCode_InvalidTransactionIndexReference = 47;
uint256 constant ErrorCode_ProofLengthOverflow = 48;
uint256 constant ErrorCode_InvalidTransactionsABILengthOverflow = 49;
// ASSEMBLY ONLY CONSTANTS
// Memory Layout * 32
// 0 -> 12 Swap for hashing, ecrecover, events data etc]
// 12 -> 44 Virtual Stack Memory (stack and swap behind writeable calldata for safety)
// 44 -> calldatasize() Calldata
// 44 + calldatasize() Free Memory
// Calldata Memory Position
uint256 constant Swap_MemoryPosition = 0 * 32; // Swap -> 12
uint256 constant Stack_MemoryPosition = 12 * 32; // Virtual Stack -> 44
uint256 constant Calldata_MemoryPosition = 44 * 32; // Calldata
// Length and Index max/min for Inputs, Outputs, Witnesses, Metadata
uint256 constant TransactionLengthMax = 8;
uint256 constant TransactionLengthMin = 0;
// Metadata, Witness and UTXO Proof Byte Size, Types and Lengths etc..
uint256 constant MetadataSize = 8;
uint256 constant WitnessSize = 65;
uint256 constant UTXOProofSize = 9 * 32;
uint256 constant DepositProofSize = 96;
uint256 constant TypeSize = 1;
uint256 constant LengthSize = 1;
uint256 constant TransactionLengthSize = 2;
uint256 constant DigestSize = 32;
uint256 constant ExpirySize = 4;
uint256 constant IndexSize = 1;
// Booleans
uint256 constant True = 1;
uint256 constant False = 0;
// Minimum and Maximum transaction byte length
uint256 constant TransactionSizeMinimum = 100;
uint256 constant TransactionSizeMaximum = 800;
// Maximum Merkle Tree Height
uint256 constant MerkleTreeHeightMaximum = 256;
// Select maximum number of transactions that can be included in a Side Chain block
uint256 constant MaxTransactionsInBlock = 2048;
// Ether Token Address (u256 chunk for assembly usage == address(0))
uint256 constant EtherToken = 0;
// Genesis Block Height
uint256 constant GenesisBlockHeight = 0;
// 4 i.e. (1) Input / (2) Output / (3) Witness Selection / (4) Metadata Selection
uint256 constant SelectionStackOffsetSize = 4;
// Topic Hashes
uint256 constant WithdrawalEventTopic = 0x782748bc04673eff1ae34a02239afa5a53a83abdfa31d65d7eea2684c4b31fe4;
uint256 constant FraudEventTopic = 0x62a5229d18b497dceab57b82a66fb912a8139b88c6b7979ad25772dc9d28ddbd;
// ASSEMBLY ONLY ENUMS
// Method Enums
uint256 constant Not_Finalized = 0;
uint256 constant Is_Finalized = 1;
uint256 constant Include_UTXOProofs = 1;
uint256 constant No_UTXOProofs = 0;
uint256 constant FirstProof = 0;
uint256 constant SecondProof = 1;
uint256 constant OneProof = 1;
uint256 constant TwoProofs = 2;
// Input Types Enums
uint256 constant InputType_UTXO = 0;
uint256 constant InputType_Deposit = 1;
uint256 constant InputType_HTLC = 2;
uint256 constant InputType_Change = 3;
// Input Sizes
uint256 constant InputSizes_UTXO = 33;
uint256 constant InputSizes_Change = 33;
uint256 constant InputSizes_Deposit = 33;
uint256 constant InputSizes_HTLC = 65;
// Output Types Enums
uint256 constant OutputType_UTXO = 0;
uint256 constant OutputType_withdrawal = 1;
uint256 constant OutputType_HTLC = 2;
uint256 constant OutputType_Change = 3;
// ASSEMBLY ONLY MEMORY STACK POSITIONS
uint256 constant Stack_InputsSum = 0;
uint256 constant Stack_OutputsSum = 1;
uint256 constant Stack_Metadata = 2;
uint256 constant Stack_BlockTip = 3;
uint256 constant Stack_UTXOProofs = 4;
uint256 constant Stack_TransactionHashID = 5;
uint256 constant Stack_BlockHeader = 6;
uint256 constant Stack_RootHeader = 19;
uint256 constant Stack_SelectionOffset = 7;
uint256 constant Stack_Index = 28;
uint256 constant Stack_SummingTokenID = 29;
uint256 constant Stack_SummingToken = 30;
// Selection Stack Positions (Comparison Proof Selections)
uint256 constant Stack_MetadataSelected = 8;
uint256 constant Stack_SelectedInputLength = 9;
uint256 constant Stack_OutputSelected = 10;
uint256 constant Stack_WitnessSelected = 11;
uint256 constant Stack_MetadataSelected2 = 12;
uint256 constant Stack_SelectedInputLength2 = 13;
uint256 constant Stack_OutputSelected2 = 14;
uint256 constant Stack_WitnessSelected2 = 15;
uint256 constant Stack_RootProducer = 16;
uint256 constant Stack_Witnesses = 17;
uint256 constant Stack_MerkleProofLeftish = 23;
uint256 constant Stack_ProofNumber = 25;
uint256 constant Stack_FreshMemory = 26;
uint256 constant Stack_MetadataLength = 31;
// Storage Positions (based on Solidity compilation)
uint256 constant Storage_deposits = 0;
uint256 constant Storage_withdrawals = 1;
uint256 constant Storage_blockTransactionRoots = 2;
uint256 constant Storage_blockCommitments = 3;
uint256 constant Storage_tokens = 4;
uint256 constant Storage_numTokens = 5;
uint256 constant Storage_blockTip = 6;
uint256 constant Storage_blockProducer = 7;
}
contract Fuel is FuelConstants, DSMath {
// EVENTS
event DepositMade(address indexed account, address indexed token, uint256 amount);
event WithdrawalMade(address indexed account, address token, uint256 amount, uint256 indexed blockHeight, uint256 transactionRootIndex, bytes32 indexed transactionLeafHash, uint8 outputIndex, bytes32 transactionHashId);
event TransactionsSubmitted(bytes32 indexed transactionRoot, address producer, bytes32 indexed merkleTreeRoot, bytes32 indexed commitmentHash);
event BlockCommitted(address blockProducer, bytes32 indexed previousBlockHash, uint256 indexed blockHeight, bytes32[] transactionRoots);
event FraudCommitted(uint256 indexed previousTip, uint256 indexed currentTip, uint256 indexed fraudCode);
event TokenIndex(address indexed token, uint256 indexed index);
// STATE STORAGE
// depositHashID => amount [later clearable in deposit] sload(keccak256(0, 64) + 5)
mapping(bytes32 => uint256) public deposits; // STORAGE 0
// block height => withdrawal id => bool(has been withdrawn) [later clearable in withdraw]
// lets treat block withdrawals as tx hash bytes(0) output (0)
mapping(uint256 => mapping(bytes32 => bool)) public withdrawals; // STORAGE 1
// transactions hash => Ethereum block number included [later clearable in withdraw]
mapping(bytes32 => uint256) public blockTransactionRoots; // STORAGE 2
// blockNumber => blockHash all block commitment hash headers Mapping actually better than array IMO, use tip as len
mapping(uint256 => bytes32) public blockCommitments; // STORAGE 3
// tokens address => token ID number
mapping(address => uint256) public tokens; // STORAGE 4
// number of tokens (1 for Ether ID 0)
uint256 public numTokens = 1; // STORAGE 5
// the current side-chain block height/tip [changed in commitBlock / submitFraudProof]
uint256 public blockTip; // STORAGE 6
// block producer (set to zero for permissionless, must be account) [changed in constructor / submitFraudProof]
address public blockProducer; // STORAGE 7
// CONSTRUCTOR
constructor(address producer) public {
// compute genesis block hash
address genesisProducer = address(0);
// TODO low-priority set a clever previous block hash
bytes32 previousBlockHash = bytes32(0);
uint256 blockHeight = uint256(0);
bytes32[] memory transactionRoots;
bytes32 genesisBlockHash = keccak256(abi.encode(genesisProducer, previousBlockHash, blockHeight, GenesisBlockHeight, transactionRoots));
// STORAGE commit the genesis block hash header to storage as Zero block..
blockCommitments[GenesisBlockHeight] = genesisBlockHash;
// STORAGE setup block producer
blockProducer = producer;
// Setup Ether token index
emit TokenIndex(address(0), 1);
// LOG emit all pertinent details of the Genesis block
emit BlockCommitted(genesisProducer, previousBlockHash, blockHeight, transactionRoots);
}
// STATE Changing Methods
function deposit(address account, address token, uint256 amount) external payable {
// Compute deposit hash Identifier
bytes32 depositHashId = keccak256(abi.encode(account, token, block.number));
// Assert amount is greater than Zero
assert(amount > 0);
// Handle transfer details
if (token != address(0)) {
assert(ERC20(token).allowance(msg.sender, address(this)) >= amount); // check allowance
assert(ERC20(token).transferFrom(msg.sender, address(this), amount)); // transferFrom
} else {
assert(msg.value == amount); // commit ether transfer
}
// register token with an index if it isn't already
if (token != address(0) && tokens[token] == 0) {
// STORAGE register token with index
tokens[token] = numTokens;
// STORAGE MOD increase token index
numTokens = ds_add(numTokens, 1);
// LOG emit token registry index
emit TokenIndex(token, numTokens);
}
// STORAGE notate deposit in storage
deposits[depositHashId] = ds_add(deposits[depositHashId], amount);
// Log essential deposit details
emit DepositMade(account, token, amount);
}
function submitTransactions(bytes32 merkleTreeRoot, bytes calldata transactions) external {
// require the sender is not a contract
assembly {
// Require if caller/msg.sender is a contract
if gt(extcodesize(caller()), 0) { revert(0, 0) }
// Calldata Max size enforcement (4m / 68)
if gt(calldatasize(), MAX_TRANSACTIONS_SIZE) { revert(0, 0) }
}
// Commitment hash
bytes32 commitmentHash = keccak256(transactions);
// Construct Transaction Root Hash
bytes32 transactionRoot = keccak256(abi.encode(msg.sender, merkleTreeRoot, commitmentHash));
// Assert this transactions blob cannot already exist
assert(blockTransactionRoots[transactionRoot] == 0);
// STORAGE notate transaction root in storage at a specified Ethereum block
blockTransactionRoots[transactionRoot] = block.number;
// LOG Transaction submitted, the original data
emit TransactionsSubmitted(transactionRoot, msg.sender, merkleTreeRoot, commitmentHash);
}
function commitBlock(uint256 blockHeight, bytes32[] calldata transactionRoots) external payable {
bytes32 previousBlockHash = blockCommitments[blockTip];
bytes32 blockHash = keccak256(abi.encode(msg.sender, previousBlockHash, blockHeight, block.number, transactionRoots));
// Assert require value be bond size
assert(msg.value == BOND_SIZE);
// Assert at least one root submission
assert(transactionRoots.length > 0);
// Assert at least one root submission
assert(transactionRoots.length < TRANSACTION_ROOTS_MAX);
// Assert the transaction roots exists
for (uint256 transactionRootIndex = 0;
transactionRootIndex < transactionRoots.length;
transactionRootIndex = ds_add(transactionRootIndex, 1)) {
// Transaction Root must Exist in State
assert(blockTransactionRoots[transactionRoots[transactionRootIndex]] > 0);
// add root expiry here..
// Assert transaction root is younger than 3 days, and block producer set, than only block producer can make the block
if (block.number < ds_add(blockTransactionRoots[transactionRoots[transactionRootIndex]], SUBMISSION_DELAY) && blockProducer != address(0)) {
assert(msg.sender == blockProducer);
}
}
// Require block height must be 1 ahead of tip REVERT nicely (be forgiving)
require(blockHeight == ds_add(blockTip, 1));
// STORAGE write block hash commitment to storage
blockCommitments[blockHeight] = blockHash;
// STORAGE set new block tip
blockTip = blockHeight;
// LOG emit all pertinant details in Log Data
emit BlockCommitted(msg.sender, previousBlockHash, blockHeight, transactionRoots);
}
// Submit Fraud or withdrawal proofs (i.e. Implied Consensus Rule Enforcement)
function submitProof(bytes calldata) external payable {
assembly {
// Assign all calldata into free memory, remove 4 byte signature and 64 bytes size/length data (68 bytes)
// Note, We only write data to memory once, than reuse it for almost every function for better computational efficiency
calldatacopy(Calldata_MemoryPosition, 68, calldatasize())
// Assign fresh memory pointer to Virtual Stack
mpush(Stack_FreshMemory, add3(Calldata_MemoryPosition, calldatasize(), mul32(2)))
// Handle Proof Type
switch selectProofType()
case 0 { // ProofType_MalformedBlock
verifyBlockProof()
}
case 1 { // ProofType_MalformedTransaction
// Check proof lengths for overflow
verifyTransactionProofLengths(OneProof)
// Verify Malformed Transaction Proof
verifyTransactionProof(FirstProof, No_UTXOProofs, Not_Finalized)
}
case 2 { // ProofType_InvalidTransaction
// Check proof lengths for overflow
verifyTransactionProofLengths(OneProof)
// Check for Invalid Transaction Sum Amount Totals
// Check for HTLC Data Construction / Witness Signature Specification
verifyTransactionProof(FirstProof, Include_UTXOProofs, Not_Finalized)
}
case 3 { // ProofType_InvalidTransactionInput
// Check proof lengths for overflow
verifyTransactionProofLengths(TwoProofs)
// Check for Invalid UTXO Reference (i.e. Reference a UTXO that does not exist or is Invalid!)
verifyTransactionProof(FirstProof, No_UTXOProofs, Not_Finalized) // Fraud Tx
verifyTransactionProof(SecondProof, No_UTXOProofs, Not_Finalized) // Valid Tx
// Select Input Type
let firstInputType := selectInputType(selectInputSelected(FirstProof))
// Assert fraud input is not a Deposit Type (deposits are checked in verifyTransactionProof)
assertOrInvalidProof(iszero(eq(firstInputType, InputType_Deposit)),
ErrorCode_InvalidTypeDeposit)
// Fraud Tx 0 Proof: Block Height, Root Index, Tx Index Selected by Metadata
let firstMetadataBlockHeight, firstMetadataTransactionRootIndex,
firstMetadataTransactionIndex, firstMetadataOutputIndex := selectMetadata(
selectMetadataSelected(FirstProof))
// Ensure block heights are the same Metadata Block Height = Second Proof Block Height
assertOrInvalidProof(eq(firstMetadataBlockHeight,
selectBlockHeight(selectBlockHeader(SecondProof))),
ErrorCode_InvalidBlockHeightReference)
// Check transaction root index overflow Metadata Roots Index < Second Proof Block Roots Length
assertOrFraud(lt(firstMetadataTransactionRootIndex,
selectTransactionRootsLength(selectBlockHeader(SecondProof))),
FraudCode_InvalidTransactionRootIndexOverflow)
// Check transaction roots
assertOrInvalidProof(eq(firstMetadataTransactionRootIndex,
selectTransactionRootIndex(selectTransactionRoot(SecondProof))),
ErrorCode_InvalidTransactionRootReference)
// Check transaction index overflow
// Second Proof is Leftish (false if Rightmost Leaf in Merkle Tree!)
let secondProofIsLeftish := mstack(Stack_MerkleProofLeftish)
// Enforce transactionIndexOverflow
assertOrFraud(or(
secondProofIsLeftish,
lte(firstMetadataTransactionIndex, selectTransactionIndex(selectTransactionData(SecondProof))) // Or is most right!
), FraudCode_TransactionIndexOverflow)
// Check transaction index
assertOrInvalidProof(eq(firstMetadataTransactionIndex,
selectTransactionIndex(selectTransactionData(SecondProof))),
ErrorCode_InvalidTransactionIndexReference)
// Check that second transaction isn't empty
assertOrFraud(gt(constructTransactionLeafHash(selectTransactionData(SecondProof)), 0),
FraudCode_TransactionHashZero)
// Select Lengths and Use Them as Indexes (let Index = Length; lt; Index--)
let transactionLeafData, inputsLength,
secondOutputsLength, witnessesLength := selectAndVerifyTransactionDetails(selectTransactionData(SecondProof))
// Check output selection overflow
assertOrFraud(lt(firstMetadataOutputIndex, secondOutputsLength),
FraudCode_MetadataOutputIndexOverflow)
// Second output index
let secondOutputIndex := selectOutputIndex(selectTransactionData(SecondProof))
// Check outputs are the same
assertOrInvalidProof(eq(firstMetadataOutputIndex, secondOutputIndex),
ErrorCode_InvalidOutputIndexReference)
// Select second output
let secondOutput := selectOutputSelected(SecondProof)
let secondOutputType := selectOutputType(secondOutput)
// Check output is not spending withdrawal
assertOrFraud(iszero(eq(secondOutputType, OutputType_withdrawal)),
FraudCode_InvalidInputWithdrawalSpend)
// Invalid Type Spend
assertOrFraud(eq(firstInputType, secondOutputType),
FraudCode_InvalidTypeReferenceMismatch)
// Construct second transaction hash id
let secondTransactionHashID := constructTransactionHashID(selectTransactionData(SecondProof))
// Construct Second UTXO ID Proof
let secondUTXOProof := constructUTXOProof(secondTransactionHashID,
selectOutputIndex(selectTransactionData(SecondProof)),
selectOutputSelected(SecondProof))
let secondUTXOID := constructUTXOID(secondUTXOProof)
// Select first UTXO ID
let firstUTXOID := selectUTXOID(selectInputSelected(FirstProof))
// Check UTXOs are the same
assertOrFraud(eq(firstUTXOID, secondUTXOID),
FraudCode_InvalidUTXOHashReference)
// Handle Change Input Enforcement
if eq(selectOutputType(secondOutput), OutputType_Change) {
// Output HTLC
let length, amount, ownerAsWitnessIndex,
tokenID := selectAndVerifyOutput(secondOutput, True)
// Return Witness Recovery
// Return Witness Signature
let outputWitnessSignature := selectWitnessSignature(selectTransactionWitnesses(selectTransactionData(SecondProof)),
ownerAsWitnessIndex)
// Construct Second Transaction Hash ID
let outputTransactionHashID := constructTransactionHashID(selectTransactionData(SecondProof))
// Get Witness Signature
let outputWitnessAddress := ecrecoverPacked(outputTransactionHashID,
outputWitnessSignature)
// Spender Witness Recovery
// Select First Proof Witness Index from Input
let unused1, unused2, spenderWitnessIndex := selectAndVerifyInputUTXO(selectInputSelected(FirstProof),
TransactionLengthMax)
// Spender Witness Signature
let spenderWitnessSignature := selectWitnessSignature(selectTransactionWitnesses(selectTransactionData(FirstProof)),
spenderWitnessIndex)
// Construct First Tx ID
let spenderTransactionHashID := constructTransactionHashID(selectTransactionData(FirstProof))
// Spender Witness Address
let spenderWitnessAddress := ecrecoverPacked(spenderTransactionHashID,
spenderWitnessSignature)
// Assert Spender must be Output Witness
assertOrFraud(eq(spenderWitnessAddress, outputWitnessAddress),
FraudCode_InvalidChangeInputSpender)
}
// Handle HTLC Input Enforcement
if eq(selectOutputType(secondOutput), OutputType_HTLC) {
// Output HTLC
let length, amount, owner, tokenID,
digest, expiry, returnWitnessIndex := selectAndVerifyOutputHTLC(secondOutput,
TransactionLengthMax)
// Handle Is HTLC Expired, must be returnWitness
if gte(selectBlockHeight(selectBlockHeader(FirstProof)), expiry) {
// Return Witness Recovery
// Return Witness Signature
let returnWitnessSignature := selectWitnessSignature(selectTransactionWitnesses(selectTransactionData(SecondProof)),
returnWitnessIndex)
// Construct Second Transaction Hash ID
let returnTransactionHashID := constructTransactionHashID(selectTransactionData(SecondProof))
// Get Witness Signature
let returnWitnessAddress := ecrecoverPacked(returnTransactionHashID,
returnWitnessSignature)
// Spender Witness Recovery
// Select First Proof Witness Index from Input
let unused1, unused2, inputWitnessIndex, preImage := selectAndVerifyInputHTLC(selectInputSelected(FirstProof),
TransactionLengthMax)
// Spender Witness Signature
let spenderWitnessSignature := selectWitnessSignature(selectTransactionWitnesses(selectTransactionData(FirstProof)),
inputWitnessIndex)
// Construct First Tx ID
let spenderTransactionHashID := constructTransactionHashID(selectTransactionData(FirstProof))
// Spender Witness Address
let spenderWitnessAddress := ecrecoverPacked(spenderTransactionHashID,
spenderWitnessSignature)
// Assert Spender must be Return Witness!
assertOrFraud(eq(spenderWitnessAddress, returnWitnessAddress),
FraudCode_InvalidReturnWitnessNotSpender)
}
}
}
case 4 { // ProofType_InvalidTransactionDoubleSpend
// Check proof lengths for overflow
verifyTransactionProofLengths(TwoProofs)
// Check for Invalid Transaction Double Spend (Same Input Twice)
verifyTransactionProof(FirstProof, No_UTXOProofs, Not_Finalized) // Accused Fraud Tx
verifyTransactionProof(SecondProof, No_UTXOProofs, Not_Finalized) // Valid Tx
// Get transaction data zero and 1
let transaction0 := selectTransactionData(FirstProof)
let transaction1 := selectTransactionData(SecondProof)
// Block Height Difference
let blockHeightDifference := iszero(eq(selectBlockHeight(selectBlockHeader(FirstProof)),
selectBlockHeight(selectBlockHeader(SecondProof))))
// Transaction Root Difference
let transactionRootIndexDifference := iszero(eq(selectTransactionRootIndex(selectTransactionRoot(FirstProof)),
selectTransactionRootIndex(selectTransactionRoot(SecondProof))))
// Transaction Index Difference
let transactionIndexDifference := iszero(eq(selectTransactionIndex(transaction0),
selectTransactionIndex(transaction1)))
// Transaction Input Index Difference
let transactionInputIndexDifference := iszero(eq(selectInputIndex(transaction0),
selectInputIndex(transaction1)))
// Check that the transactions are different
assertOrInvalidProof(or(
or(blockHeightDifference, transactionRootIndexDifference),
or(transactionIndexDifference, transactionInputIndexDifference) // Input Index is Different
), ErrorCode_InvalidTransactionComparison)
// Assert Inputs are Different OR FRAUD Double Spend!
assertOrFraud(iszero(eq(selectInputSelectedHash(FirstProof),
selectInputSelectedHash(SecondProof))),
FraudCode_InputDoubleSpend)
}
case 5 { // ProofType_UserWithdrawal
// Check proof lengths for overflow
verifyTransactionProofLengths(OneProof)
// Verify transaction proof
verifyTransactionProof(FirstProof, No_UTXOProofs, Is_Finalized)
// Run the withdrawal Sequence
let output := selectOutputSelected(FirstProof)
let length, outputAmount, outputOwner, outputTokenID := selectAndVerifyOutput(output, False)
// Check Proof Type is Correct
assertOrInvalidProof(eq(selectOutputType(output), 1), ErrorCode_InvalidWithdrawalOutputType)
// Check Proof Type is Correct
assertOrInvalidProof(eq(outputOwner, caller()), ErrorCode_InvalidWithdrawalOwner)
// Get transaction details
let transactionRootIndex := selectTransactionRootIndex(selectTransactionRoot(FirstProof))
let transactionLeafHash := constructTransactionLeafHash(selectTransactionData(FirstProof))
let outputIndex := selectOutputIndex(selectTransactionData(FirstProof))
let blockHeight := selectBlockHeight(selectBlockHeader(FirstProof))
// Construct withdrawal hash id
let withdrawalHashID := constructWithdrawalHashID(transactionRootIndex,
transactionLeafHash, outputIndex)
// This output has not been withdrawn yet!
assertOrInvalidProof(eq(getWithdrawals(blockHeight, withdrawalHashID), False),
ErrorCode_WithdrawalAlreadyHappened)
// withdrawal Token
let withdrawalToken := selectWithdrawalToken(FirstProof)
// Transfer amount out
transfer(outputAmount, outputTokenID, withdrawalToken, outputOwner)
// Set withdrawals
setWithdrawals(blockHeight, withdrawalHashID, True)
// Construct Log Data for withdrawal
mstore(mul32(1), withdrawalToken)
mstore(mul32(2), outputAmount)
mstore(mul32(3), transactionRootIndex)
mstore(mul32(4), outputIndex)
mstore(mul32(5), constructTransactionHashID(selectTransactionData(FirstProof)))
// add transactionHash
// Log withdrawal data and topics
log4(mul32(1), mul32(5), WithdrawalEventTopic, outputOwner,
blockHeight, transactionLeafHash)
}
case 6 { // ProofType_BondWithdrawal
// Select proof block header
let blockHeader := selectBlockHeader(FirstProof)
// Setup block producer withdrawal hash ID (i.e. Zero)
let withdrawalHashID := 0
// Transaction Leaf Hash (bond withdrawal hash is zero)
let transactionLeafHash := 0
// Block Producer
let blockProducer := caller()
// block height
let blockHeight := selectBlockHeight(blockHeader)
// Verify block header proof is finalized!
verifyBlockHeader(blockHeader, Is_Finalized)
// Assert Caller is Block Producer
assertOrInvalidProof(eq(selectBlockProducer(blockHeader), blockProducer),
ErrorCode_BlockProducerNotCaller)
// Assert Block Bond withdrawal has not been Made!
assertOrInvalidProof(eq(getWithdrawals(blockHeight, withdrawalHashID), False),
ErrorCode_BlockBondAlreadyWithdrawn)
// Transfer Bond Amount back to Block Producer
transfer(BOND_SIZE, EtherToken, EtherToken, blockProducer)
// Set withdrawal
setWithdrawals(blockHeight, withdrawalHashID, True)
// Construct Log Data for withdrawal
mstore(mul32(1), EtherToken)
mstore(mul32(2), BOND_SIZE)
mstore(mul32(3), 0)
mstore(mul32(4), 0)
// Log withdrawal data and topics
log4(mul32(1), mul32(4), WithdrawalEventTopic, blockProducer,
blockHeight,
transactionLeafHash)
}
// Invalid Proof Type
default { assertOrInvalidProof(0, ErrorCode_InvalidProofType) }
// Ensure Execution Stop
stop()
//
// VERIFICATION METHODS
// For verifying proof data and determine fraud or validate withdrawals
//
// Verify Invalid Block Proof
function verifyBlockProof() {
/*
Block Construction Proof:
- Type
- Lengths
- BlockHeader
- TransactionRootHeader
- TransactionRootData
*/
// Start Proof Position past Proof Type
let proofMemoryPosition := safeAdd(Calldata_MemoryPosition, mul32(1))
// Select Proof Lengths
let blockHeaderLength := load32(proofMemoryPosition, 0)
let transactionRootLength := load32(proofMemoryPosition, 1)
let transactionsLength := load32(proofMemoryPosition, 2)
// Verify the Lengths add up to calldata size
verifyProofLength(add4(mul32(3), blockHeaderLength,
transactionRootLength, transactionsLength))
// Select Proof Memory Positions
let blockHeader := selectBlockHeader(FirstProof)
let transactionRoot := selectTransactionRoot(FirstProof)
// Transactions are After Transaction Root, Plus 64 Bytes (for bytes type metadata from ABI Encoding)
let transactions := safeAdd(transactionRoot, transactionRootLength)
// Verify Block Header
verifyBlockHeader(blockHeader, Not_Finalized)
// Verify Transaction Root Header
verifyTransactionRootHeader(blockHeader, transactionRoot)
// Get solidity abi encoded length for transactions blob
let transactionABILength := selectTransactionABILength(transactions)
// Check for overflow
assertOrInvalidProof(lt(transactionABILength, transactionsLength),
ErrorCode_InvalidTransactionsABILengthOverflow)
// Verify Transaction Hash Commitment
verifyTransactionRootData(transactionRoot,
selectTransactionABIData(transactions),
transactionABILength)
}
// Verify proof length for overflows
function verifyProofLength(proofLengthWithoutType) {
let calldataMetadataSize := 68
let typeSize := mul32(1)
let computedCalldataSize := add3(calldataMetadataSize, typeSize, proofLengthWithoutType)
// Check for overflow
assertOrInvalidProof(eq(computedCalldataSize, calldatasize()),
ErrorCode_ProofLengthOverflow)
}
// Verify Block Header
function verifyBlockHeader(blockHeader, assertFinalized) {
/*
- Block Header:
- blockProducer [32 bytes] -- padded address
- previousBlockHash [32 bytes]
- blockHeight [32 bytes]
- ethereumBlockNumber [32 bytes]
- transactionRoots [64 + dynamic bytes]
*/
// Construct blockHash from Block Header
let blockHash := constructBlockHash(blockHeader)
// Select BlockHeight from Memory
let blockHeight := selectBlockHeight(blockHeader)
// Previous block hash
let previousBlockHash := selectPreviousBlockHash(blockHeader)
// Transaction Roots Length
let transactionRootsLength := selectTransactionRootsLength(blockHeader)
// Assert Block is not Genesis
assertOrInvalidProof(gt(blockHeight, GenesisBlockHeight), ErrorCode_BlockHeightUnderflow)
// Assert Block Height is Valid (i.e. before tip)
assertOrInvalidProof(lte(blockHeight, getBlockTip()), ErrorCode_BlockHeightOverflow)
// Assert Previous Block Hash
assertOrInvalidProof(eq(getBlockCommitments(safeSub(blockHeight, 1)), previousBlockHash), ErrorCode_InvalidPreviousBlockHash)
// Transactions roots length underflow
assertOrInvalidProof(gt(transactionRootsLength, 0), ErrorCode_TransactionRootsLengthUnderflow)
// Assert Block Commitment Exists
assertOrInvalidProof(eq(getBlockCommitments(blockHeight), blockHash), ErrorCode_BlockHashNotFound)
// If requested, Assert Block is Finalized
if eq(assertFinalized, 1) {
assertOrInvalidProof(gte(
number(),
safeAdd(selectEthereumBlockNumber(blockHeader), FINALIZATION_DELAY) // ethBlock + delay
), ErrorCode_BlockNotFinalized)
}
// If requested, Assert Block is Not Finalized
if iszero(assertFinalized) { // underflow protected!
assertOrInvalidProof(lt(
number(), // ethereumBlockNumber
safeAdd(selectEthereumBlockNumber(blockHeader), FINALIZATION_DELAY) // finalization delay
), ErrorCode_BlockFinalized)
}
}
// Verify Transaction Root Header (Assume Block Header is Valid)
function verifyTransactionRootHeader(blockHeader, transactionRoot) {
/*
- Block Header:
- blockProducer [32 bytes] -- padded address
- previousBlockHash [32 bytes]
- blockHeight [32 bytes]
- ethereumBlockNumber [32 bytes]
- transactionRoots [64 + dynamic bytes]
- Transaction Root Header:
- transactionRootProducer [32 bytes] -- padded address
- transactionRootMerkleTreeRoot [32 bytes]
- transactionRootCommitmentHash [32 bytes]
- transactionRootIndex [32 bytes]
*/
// Get number of transaction roots
let transactionRootsLength := selectTransactionRootsLength(blockHeader)
// Get transaction root index
let transactionRootIndex := selectTransactionRootIndex(transactionRoot)
// Assert root index is not overflowing
assertOrInvalidProof(lt(transactionRootIndex, transactionRootsLength), ErrorCode_TransactionRootIndexOverflow)
// Assert root invalid overflow
assertOrInvalidProof(lt(transactionRootsLength, TRANSACTION_ROOTS_MAX), ErrorCode_TransactionRootsLengthOverflow)
// Construct transaction root
let transactionRootHash := keccak256(transactionRoot, mul32(3))
// Assert transaction root index is correct!
assertOrInvalidProof(eq(
transactionRootHash,
load32(blockHeader, safeAdd(6, transactionRootIndex)) // blockHeader transaction root
), ErrorCode_TransactionRootHashNotInBlockHeader)
}
// Construct commitment hash
function constructCommitmentHash(transactions, transactionsLength) -> commitmentHash {
commitmentHash := keccak256(transactions, transactionsLength)
}
function selectTransactionABIData(transactionsABIEncoded) -> transactions {
transactions := safeAdd(transactionsABIEncoded, mul32(2))
}
function selectTransactionABILength(transactionsABIEncoded) -> transactionsLength {
transactionsLength := load32(transactionsABIEncoded, 1)
}
// Verify Transaction Root Data is Valid (Assuming Transaction Root Valid)
function verifyTransactionRootData(transactionRoot, transactions, transactionsLength) {
// Select Transaction Data Root
let commitmentHash := selectCommitmentHash(transactionRoot)
// Check provided transactions data! THIS HASH POSITION MIGHT BE WRONG due to Keccak Encoding
let constructedCommitmentHash := constructCommitmentHash(transactions, transactionsLength)
// Assert or Invalid Data Provided
assertOrInvalidProof(eq(
commitmentHash,
constructedCommitmentHash
), ErrorCode_TransactionRootHashInvalid)
// Select Merkle Tree Root Provided
let merkleTreeRoot := selectMerkleTreeRoot(transactionRoot)
// Assert committed root must be the same as computed root! // THIS HASH MIGHT BE WRONG (hash POS check)
assertOrFraud(eq(
merkleTreeRoot,
constructMerkleTreeRoot(transactions, transactionsLength)
), FraudCode_InvalidMerkleTreeRoot)
}
// Verify Transaction Proof
function verifyTransactionProof(proofIndex, includeUTXOProofs, assertFinalized) {
/*
Transaction Proof:
- Lengths
- BlockHeader
- TransactionRootHeader
- TransactionMerkleProof
- TransactionData
- TransactionUTXOProofs
*/
// we are on proof 1
if gt(proofIndex, 0) {
// Notate across global stack we are on proof 1 validation
mpush(Stack_ProofNumber, proofIndex)
}
// Select Memory Positions
let blockHeader := selectBlockHeader(proofIndex)
let transactionRoot := selectTransactionRoot(proofIndex)
let transactionMerkleProof := selectTransactionMerkleProof(proofIndex)
let transactionData := selectTransactionData(proofIndex)
// Verify Block Header
verifyBlockHeader(blockHeader, assertFinalized)
// Verify Transaction Root Header
verifyTransactionRootHeader(blockHeader, transactionRoot)
// Verify Transaction Leaf
verifyTransactionLeaf(transactionRoot, transactionData, transactionMerkleProof)
// Construct Transaction Leaf Hash (Again :(
let transactionLeafHash := constructTransactionLeafHash(transactionData)
// If transaction hash is not zero hash, than go and verify it!
if gt(transactionLeafHash, 0) {
// Transaction UTXO Proofs
let transactionUTXOProofs := 0
// Include UTXO Proofs
if gt(includeUTXOProofs, 0) {
transactionUTXOProofs := selectTransactionUTXOProofs(proofIndex)
}
// Verify Transaction Data
verifyTransactionData(transactionData, transactionUTXOProofs)
}
// Ensure We are now validating proof 0 again
mpop(Stack_ProofNumber)
}
// Verify Transaction Leaf (Assume Transaction Root Header is Valid)
function verifyTransactionLeaf(transactionRoot, transactionData, merkleProof) {
/*
- Transaction Root Header:
- transactionRootProducer [32 bytes] -- padded address
- transactionRootMerkleTreeRoot [32 bytes]
- transactionRootCommitmentHash [32 bytes]
- transactionRootIndex [32 bytes]
- Transaction Data:
- input index [32 bytes] -- padded uint8
- output index [32 bytes] -- padded uint8
- witness index [32 bytes] -- padded uint8
- transactionInputsLength [32 bytes] -- padded uint8
- transactionIndex [32 bytes] -- padded uint32
- transactionLeafData [dynamic bytes]
- Transaction Merkle Proof:
- oppositeTransactionLeaf [32 bytes]
- merkleProof [64 + dynamic bytes]
*/
// Select Merkle Tree Root
let merkleTreeRoot := selectMerkleTreeRoot(transactionRoot)
// Select Merkle Proof Height
let treeHeight := selectMerkleTreeHeight(merkleProof)
// Select Tree (ahead of Array length)
let treeMemoryPosition := selectMerkleTree(merkleProof)
// Select Transaction Index
let transactionIndex := selectTransactionIndex(transactionData)
// Assert Valid Merkle Tree Height (i.e. below Maximum)
assertOrInvalidProof(lt(treeHeight, MerkleTreeHeightMaximum),
ErrorCode_MerkleTreeHeightOverflow)
// Select computed hash, initialize with opposite leaf hash
let computedHash := selectOppositeTransactionLeaf(merkleProof)
// Assert Leaf Hash is base of Merkle Proof
assertOrInvalidProof(eq(
constructTransactionLeafHash(transactionData), // constructed
computedHash // proof provided
), ErrorCode_TransactionLeafHashInvalid)
// Clean Rightmost (leftishness) Detection Var (i.e. any previous use of this Stack Position)
mpop(Stack_MerkleProofLeftish)
// Iterate Through Merkle Proof Depths
// https://crypto.stackexchange.com/questions/31871/what-is-the-canonical-way-of-creating-merkle-tree-branches
for { let depth := 0 } lt(depth, treeHeight) { depth := safeAdd(depth, 1) } {
// get the leaf hash
let proofLeafHash := load32(treeMemoryPosition, depth)
// Determine Proof Direction the merkle brand left: tx index % 2 == 0
switch eq(smod(transactionIndex, 2), 0)
// Direction is left branch
case 1 {
mstore(mul32(1), computedHash)
mstore(mul32(2), proofLeafHash)
// Leftishness Detected in Proof, This is not Rightmost
mpush(Stack_MerkleProofLeftish, True)
}
// Direction is right branch
case 0 {
mstore(mul32(1), proofLeafHash)
mstore(mul32(2), computedHash)
}
default { revert(0, 0) } // Direction is Invalid, Ensure no other cases!
// Construct Depth Hash
computedHash := keccak256(mul32(1), mul32(2))
// Shift transaction index right by 1
transactionIndex := shr(1, transactionIndex)
}
// Assert constructed merkle tree root is provided merkle tree root, or else, Invalid Inclusion!
assertOrInvalidProof(eq(computedHash, merkleTreeRoot), ErrorCode_MerkleTreeRootInvalid)
}
// Verify Transaction Input Metadata
function verifyTransactionInputMetadata(blockHeader, rootHeader, metadata, blockTip, inputIndex) {
// Block Height
let metadataBlockHeight, metadataTransactionRootIndex,
metadataTransactionIndex, metadataOutputIndex := selectMetadata(metadata)
// Select Transaction Block Height
let blockHeight := selectBlockHeight(blockHeader)
let transactionRootIndex := selectTransactionRootIndex(rootHeader)
// Assert input index overflow (i.e. metadata does not exist)
assertOrFraud(lt(inputIndex, mstack(Stack_MetadataLength)),
FraudCode_MetadataReferenceOverflow)
// Assert Valid Metadata Block height
assertOrFraud(gt(metadataBlockHeight, 0), FraudCode_MetadataBlockHeightUnderflow)
// Assert Valid Metadata Block height
assertOrFraud(lt(metadataTransactionRootIndex, TRANSACTION_ROOTS_MAX),
FraudCode_InvalidTransactionRootIndexOverflow)
// Cannot spend past it's own root index (i.e. tx 1 cant spend tx 2 at root index + 1)
// Can't be past block tip or past it's own block (can't reference the future)
assertOrFraud(lte(metadataBlockHeight, blockTip),
FraudCode_MetadataBlockHeightOverflow)
// Check overflow of current block height
assertOrFraud(lte(metadataBlockHeight, blockHeight),
FraudCode_MetadataBlockHeightOverflow)
// Can't reference in the future!!
// If Meta is Ref. Block Height of Itself, and Ref. Root Index > Itself, that's Fraud!
assertOrFraud(or(iszero(eq(metadataBlockHeight, blockHeight)), // block height is different
lte(metadataTransactionRootIndex, transactionRootIndex)), // metadata root index <= self root index
FraudCode_InvalidTransactionRootIndexOverflow)
// Need to cover referencing a transaction index in the same block, but past this tx
// txs must always reference txs behind it, or else it's fraud
// Check Output Index
assertOrFraud(lt(metadataOutputIndex, TransactionLengthMax),
FraudCode_MetadataOutputIndexOverflow)
}
// Verify HTLC Usage
function verifyHTLCData(blockHeader, input, utxoProof) {
/*
- Transaction UTXO Data:
- transactionHashId [32 bytes]
- outputIndex [32 bytes] -- padded uint8
- type [32 bytes] -- padded uint8
- amount [32 bytes]
- owner [32 bytes] -- padded address or unit8
- tokenID [32 bytes] -- padded uint32
- [HTLC Data]:
- digest [32 bytes]
- expiry [32 bytes] -- padded 4 bytes
- return witness index [32 bytes] -- padded 1 bytes
*/
// Select Transaction Input data
let length, utxoID, witnessReference, preImage := selectAndVerifyInputHTLC(input,
TransactionLengthMax)
// Select Transaction Block Height
let blockHeight := selectBlockHeight(blockHeader)
// Select Digest and Expiry from UTXO Proof (Assumed to be Valid)
let digest := load32(utxoProof, 6)
let expiry := load32(utxoProof, 7)
// If not expired, and digest correct, expired case gets handled in Comparison proofs
if lt(blockHeight, expiry) {
// Assert Digest is Valid
assertOrFraud(eq(digest, constructHTLCDigest(preImage)),
FraudCode_InvalidHTLCDigest)
}
}
// Verify Transaction Length (minimum and maximum)
function verifyTransactionLength(transactionLength) {
// Assert transaction length is not too short
assertOrFraud(gt(transactionLength, TransactionSizeMinimum),
FraudCode_TransactionLengthUnderflow)
// Assert transaction length is not too long
assertOrFraud(lte(transactionLength, TransactionSizeMaximum),
FraudCode_TransactionLengthOverflow)
}
// Verify Transaction Data (Metadata, Inputs, Outputs, Witnesses)
function verifyTransactionData(transactionData, utxoProofs) {
// Verify Transaction Length
verifyTransactionLength(selectTransactionLength(transactionData))
// Select and Verify Lengths and Use Them as Indexes (let Index = Length; lt; Index--)
let memoryPosition, inputsLength,
outputsLength, witnessesLength := selectAndVerifyTransactionDetails(transactionData)
// Memory Stack so we don't blow the stack!
mpush(Stack_InputsSum, 0) // Total Transaction Input Sum
mpush(Stack_OutputsSum, 0) // Total Transaction Output Sum
mpush(Stack_Metadata, selectTransactionMetadata(transactionData)) // Metadata Memory Position
mpush(Stack_Witnesses, selectTransactionWitnesses(transactionData)) // Witnesses Memory Position
mpush(Stack_BlockTip, getBlockTip()) // GET blockTip() from Storage
mpush(Stack_UTXOProofs, safeAdd(utxoProofs, mul32(1))) // UTXO Proofs Memory Position
mpush(Stack_TransactionHashID, constructTransactionHashID(transactionData)) // Construct Transaction Hash ID
mpush(Stack_MetadataLength, selectTransactionMetadataLength(transactionData))
// Push summing tokens
if gt(utxoProofs, 0) {
mpush(Stack_SummingToken, mload(utxoProofs)) // load summing token
mpush(Stack_SummingTokenID, getTokens(mload(utxoProofs))) // load summing token
}
// Set Block Header Position (on First Proof)
if iszero(mstack(Stack_ProofNumber)) {
// Proof 0 Block Header Position
mpush(Stack_BlockHeader, selectBlockHeader(FirstProof))
// Proof 0 Block Header Position
mpush(Stack_RootHeader, selectTransactionRoot(FirstProof))
// Return Stack Offset: (No Offset) First Transaction
mpush(Stack_SelectionOffset, 0)
// Proof 0 Transaction Root Producer
mpush(Stack_RootProducer, selectRootProducer(selectTransactionRoot(FirstProof)))
}
// If Second Transaction Processed, Set Block Header Position (On Second Proof)
if gt(mstack(Stack_ProofNumber), 0) {
// Proof 1 Block Header Position
mpush(Stack_BlockHeader, selectBlockHeader(SecondProof))
// Proof 0 Block Header Position
mpush(Stack_RootHeader, selectTransactionRoot(SecondProof))
// Return Stack Offset: Offset Memory Stack for Second Proof
mpush(Stack_SelectionOffset, SelectionStackOffsetSize) // 4 => Metadata, Input, Output, Witness Position
// Proof 1 Transaction Root Position
mpush(Stack_RootProducer, selectRootProducer(selectTransactionRoot(SecondProof)))
}
// Increase memory position past length Specifiers
memoryPosition := safeAdd(memoryPosition, TransactionLengthSize)
// Transaction Proof Stack Return
// 8) Metadata Tx 1, 9) Input Tx 1, 10) Output, 11) Witness Memory Position
// 12) Metadata Tx 2, 13) Input Tx 2, 14) Output, 15) Witness Memory Position
// VALIDATE Inputs Index from Inputs Length -> 0
for { mpush(Stack_Index, 0) }
lt(mstack(Stack_Index), inputsLength)
{ mpush(Stack_Index, safeAdd(mstack(Stack_Index), 1)) } {
// Check if This is Input Requested
if eq(mstack(Stack_Index), selectInputSelectionIndex(transactionData)) {
// Store Metadata Position in Stack
mpush(safeAdd(Stack_MetadataSelected, mstack(Stack_SelectionOffset)),
combineUint32(mstack(Stack_Metadata), memoryPosition, mstack(Stack_Index), 0))
}
// Select Input Type
switch selectInputType(memoryPosition)
case 0 { // InputType UTXO
// Increase Memory pointer
let length, utxoID, witnessReference := selectAndVerifyInputUTXO(memoryPosition,
witnessesLength)
// If UTXO/Deposit Proofs provided
if gt(utxoProofs, 0) {
let outputAmount, outputOwner,
tokenID := selectAndVerifyUTXOAmountOwner(mstack(Stack_UTXOProofs), 0, utxoID)
// Increase input sum
if eq(tokenID, mstack(Stack_SummingTokenID)) {
mpush(Stack_InputsSum, safeAdd(mstack(Stack_InputsSum), outputAmount))
}
// Increase UTXO proof memory position
mpush(Stack_UTXOProofs, safeAdd(mstack(Stack_UTXOProofs), UTXOProofSize))
// Verify transaction witness
verifyTransactionWitness(selectWitnessSignature(mstack(Stack_Witnesses), witnessReference),
mstack(Stack_TransactionHashID), outputOwner, mstack(Stack_RootProducer))
}
// cannot select metadata that does not exist
// assertOrFraud(lt(inputIndex, mstack(Stack_MetadataLength)),
// FraudCode_TransactionInputMetadataOverflow)
// Verify metadata for this input (metadata position, block tip)
verifyTransactionInputMetadata(mstack(Stack_BlockHeader), mstack(Stack_RootHeader),
mstack(Stack_Metadata), mstack(Stack_BlockTip), mstack(Stack_Index))
// Increase metadata memory position
mpush(Stack_Metadata, safeAdd(mstack(Stack_Metadata), MetadataSize))
// Push Input Length
mpush(safeAdd(Stack_SelectedInputLength, mstack(Stack_SelectionOffset)), length)
// increase Memory Position
memoryPosition := safeAdd(memoryPosition, length)
}
case 1 { // InputType DEPOSIT (verify deposit owner / details witnesses etc)
// Select Input Deposit (Asserts Deposit > 0)
let length, depositHashID,
witnessReference := selectAndVerifyInputDeposit(memoryPosition, witnessesLength)
// If UTXO Proofs provided
if gt(utxoProofs, 0) {
// Owner
let depositOwner := selectInputDepositOwner(mstack(Stack_UTXOProofs))
// Constructed Deposit hash
let constructedDepositHashID := constructDepositHashID(mstack(Stack_UTXOProofs))
// Check Deposit Hash ID against proof
assertOrInvalidProof(eq(depositHashID, constructedDepositHashID),
ErrorCode_InvalidDepositProof)
// Verify transaction witness
verifyTransactionWitness(selectWitnessSignature(mstack(Stack_Witnesses), witnessReference),
mstack(Stack_TransactionHashID), depositOwner, mstack(Stack_RootProducer))
// Deposit Token
let depositToken := selectInputDepositToken(mstack(Stack_UTXOProofs))
// Increase Input Amount
if eq(depositToken, mstack(Stack_SummingToken)) {
mpush(Stack_InputsSum, safeAdd(mstack(Stack_InputsSum), getDeposits(depositHashID)))
}
// Increase UTXO/Deposit proof memory position
mpush(Stack_UTXOProofs, safeAdd(mstack(Stack_UTXOProofs), DepositProofSize))
}
// Push Input Length
mpush(safeAdd(Stack_SelectedInputLength, mstack(Stack_SelectionOffset)), length)
// Increase Memory Position
memoryPosition := safeAdd(memoryPosition, length)
}
case 2 { // InputType HTLC
// Select HTLC Input
let length, utxoID, witnessReference, preImage := selectAndVerifyInputHTLC(
memoryPosition, witnessesLength)
// If UTXO Proofs provided
if gt(utxoProofs, 0) {
let outputAmount, outputOwner, tokenID := selectAndVerifyUTXOAmountOwner(
mstack(Stack_UTXOProofs), 2, utxoID)
// Verify HTLC Data
verifyHTLCData(mstack(Stack_BlockHeader), memoryPosition, mstack(Stack_UTXOProofs))
// Verify transaction witness
verifyTransactionWitness(selectWitnessSignature(mstack(Stack_Witnesses), witnessReference),
mstack(Stack_TransactionHashID), outputOwner, mstack(Stack_RootProducer))
// Increase input sum
if eq(tokenID, mstack(Stack_SummingTokenID)) {
mpush(Stack_InputsSum, safeAdd(mstack(Stack_InputsSum), outputAmount))
}
// Increase UTXO proof memory position
mpush(Stack_UTXOProofs, safeAdd(mstack(Stack_UTXOProofs), UTXOProofSize))
}
// Verify metadata for this input (metadata position, block tip)
verifyTransactionInputMetadata(mstack(Stack_BlockHeader), mstack(Stack_RootHeader),
mstack(Stack_Metadata), mstack(Stack_BlockTip), mstack(Stack_Index))
// Increase metadata memory position
mpush(Stack_Metadata, safeAdd(mstack(Stack_Metadata), MetadataSize))
// Push Input Length
mpush(safeAdd(Stack_SelectedInputLength, mstack(Stack_SelectionOffset)), length)
// Increase Memory Position
memoryPosition := safeAdd(memoryPosition, length)
}
case 3 { // InputType CHANGE UNSPENT
// HTLC input
let length, utxoID, witnessReference := selectAndVerifyInputUTXO(memoryPosition, witnessesLength)
// If UTXO Proofs provided
if gt(utxoProofs, 0) {
let outputAmount, outputOwner,
tokenID := selectAndVerifyUTXOAmountOwner(mstack(Stack_UTXOProofs),
OutputType_Change, utxoID)
// witness signatures get enforced in invalidTransactionInput
// Increase input sum
if eq(tokenID, mstack(Stack_SummingTokenID)) {
mpush(Stack_InputsSum, safeAdd(mstack(Stack_InputsSum), outputAmount))
}
// Increase UTXO proof memory position
mpush(Stack_UTXOProofs, safeAdd(mstack(Stack_UTXOProofs), UTXOProofSize))
}
// Verify metadata for this input (metadata position, block tip)
verifyTransactionInputMetadata(mstack(Stack_BlockHeader), mstack(Stack_RootHeader),
mstack(Stack_Metadata), mstack(Stack_BlockTip), mstack(Stack_Index))
// Increase metadata memory position
mpush(Stack_Metadata, safeAdd(mstack(Stack_Metadata), MetadataSize))
// Push Input Length
mpush(safeAdd(Stack_SelectedInputLength, mstack(Stack_SelectionOffset)), length)
// Increase Memory Position
memoryPosition := safeAdd(memoryPosition, length)
}
// Assert fraud Invalid Input Type
default { assertOrFraud(0, FraudCode_InvalidTransactionInputType) }
// Increase Memory Pointer for 1 byte Type
memoryPosition := safeAdd(memoryPosition, TypeSize)
}
// Index from Outputs Length -> 0
for { mpush(Stack_Index, 0) }
lt(mstack(Stack_Index), outputsLength)
{ mpush(Stack_Index, safeAdd(mstack(Stack_Index), 1)) } {
// Check if input is requested
if eq(mstack(Stack_Index), selectOutputSelectionIndex(transactionData)) {
// Store Output Memory Position in Stack
mpush(safeAdd(Stack_OutputSelected, mstack(Stack_SelectionOffset)), memoryPosition)
}
// Select Output Type
switch selectOutputType(memoryPosition)
case 0 { // OutputType UTXO
// Increase Memory pointer
let length, amount, owner, tokenID := selectAndVerifyOutput(memoryPosition, False)
// Increase total output sum
if eq(tokenID, mstack(Stack_SummingTokenID)) {
mpush(Stack_OutputsSum, safeAdd(mstack(Stack_OutputsSum), amount))
}
// Increase Memory pointer
memoryPosition := safeAdd(length, memoryPosition)
}
case 1 { // OutputType withdrawal
// Increase Memory pointer
let length, amount, owner, tokenID := selectAndVerifyOutput(memoryPosition, False)
// Increase total output sum
if eq(tokenID, mstack(Stack_SummingTokenID)) {
mpush(Stack_OutputsSum, safeAdd(mstack(Stack_OutputsSum), amount))
}
// Increase Memory pointer
memoryPosition := safeAdd(length, memoryPosition)
}
case 2 { // OutputType HTLC
// Increase Memory pointer
let length, amount, owner, tokenID,
digest, expiry, returnWitness := selectAndVerifyOutputHTLC(memoryPosition,
witnessesLength)
// Check expiry is greater than its own block header
assertOrFraud(gt(expiry, selectBlockHeight(mstack(Stack_BlockHeader))),
FraudCode_OutputHTLCExpiryUnderflow)
// Increase total output sum
if eq(tokenID, mstack(Stack_SummingTokenID)) {
mpush(Stack_OutputsSum, safeAdd(mstack(Stack_OutputsSum), amount))
}
// Increase Memory pointer
memoryPosition := safeAdd(length, memoryPosition)
}
case 3 { // OutputType CHANGE UNSPENT
// Increase Memory pointer
let length, amount, witnessReference,
tokenID := selectAndVerifyOutput(memoryPosition, True)
// Invalid Witness Reference out of bounds
assertOrFraud(lt(witnessReference, witnessesLength),
FraudCode_TransactionOutputWitnessReferenceOverflow)
// Increase total output sum
if eq(tokenID, mstack(Stack_SummingTokenID)) {
mpush(Stack_OutputsSum, safeAdd(mstack(Stack_OutputsSum), amount))
}
// Increase Memory pointer
memoryPosition := safeAdd(length, memoryPosition)
}
// Assert fraud Invalid Input Type
default { assertOrFraud(0, FraudCode_InvalidTransactionOutputType) }
// Increase Memory Pointer for 1 byte Type
memoryPosition := safeAdd(memoryPosition, TypeSize)
}
// Assert Transaction Total Output Sum <= Total Input Sum
if gt(utxoProofs, 0) { assertOrFraud(eq(mstack(Stack_OutputsSum), mstack(Stack_InputsSum)),
FraudCode_TransactionSumMismatch) }
// Iterate from Witnesses Length -> 0
for { mpush(Stack_Index, 0) }
lt(mstack(Stack_Index), witnessesLength)
{ mpush(Stack_Index, safeAdd(mstack(Stack_Index), 1)) } {
// check if input is requested
if eq(mstack(Stack_Index), selectWitnessSelectionIndex(transactionData)) {
// Store Witness Memory Position in Stack
mpush(safeAdd(Stack_WitnessSelected, mstack(Stack_SelectionOffset)),
mstack(Stack_Witnesses))
}
// Increase witness memory position
mpush(Stack_Witnesses, safeAdd(mstack(Stack_Witnesses), WitnessSize))
}
// Check Transaction Length for Validity based on Computed Lengths
// Get Leaf Size details
let unsignedTransactionData, metadataSize,
witnessesSize, witnessLength := selectAndVerifyTransactionLeafData(transactionData)
// Select Transaction Length
let transactionLength := selectTransactionLength(transactionData)
// Metadata size
let providedDataSize := add3(TransactionLengthSize, metadataSize, witnessesSize)
// We should never hit this, but we will add in the protection anyway..
assertOrFraud(lt(providedDataSize, transactionLength),
FraudCode_ProvidedDataOverflow)
// Memory size difference
let unsignedTransactionLength := safeSub(transactionLength, providedDataSize)
// We should never hit this, but we will add in the protection anyway..
assertOrFraud(lt(unsignedTransactionData, memoryPosition),
FraudCode_ProvidedDataOverflow)
// Computed unsigned transaction length
// Should never underflow
let computedUnsignedTransactionLength := safeSub(memoryPosition, unsignedTransactionData)
// Invalid transaction length
assertOrFraud(eq(unsignedTransactionLength, computedUnsignedTransactionLength),
FraudCode_ComputedTransactionLengthOverflow)
// Pop Memory Stack
mpop(Stack_InputsSum)
mpop(Stack_OutputsSum)
mpop(Stack_Metadata)
mpop(Stack_Witnesses)
mpop(Stack_BlockTip)
mpop(Stack_UTXOProofs)
mpop(Stack_TransactionHashID)
mpop(Stack_MetadataLength)
mpush(Stack_SummingToken, 0) // load summing token
mpush(Stack_SummingTokenID, 0) // load summing token
mpop(Stack_Index)
// We leave Memory Stack 6 for Secondary Transaction Proof Validation
// We don't clear 7 - 15 (those are the returns from transaction processing)
// Warning: CHECK Transaction Leaf Length here for Computed Length!!
}
mpop(Stack_Index)
//
// SELECTOR METHODS
// For selecting, parsing and enforcing side-chain abstractions, rules and data across runtime memory
//
// Select the UTXO ID for an Input
function selectUTXOID(input) -> utxoID {
// Past 1 (input type)
utxoID := mload(safeAdd(input, TypeSize))
}
// Select Metadata
function selectMetadata(metadata) -> blockHeight, transactionRootIndex,
transactionIndex, outputIndex {
blockHeight := slice(metadata, 4)
transactionRootIndex := slice(safeAdd(metadata, 4), IndexSize)
transactionIndex := slice(safeAdd(metadata, 5), 2)
outputIndex := slice(safeAdd(metadata, 7), IndexSize)
}
// Select Metadata Selected (Used after verifyTransactionData)
function selectInputSelectedHash(proofIndex) -> inputHash {
let offset := 0
// Second proof, move offset to 4
if gt(proofIndex, 0) { offset := SelectionStackOffsetSize }
// Input Hash Length (Type 1 Byte + Input Length Provided)
let inputHashLength := 0
// Input Memory Position
let input := selectInputSelected(proofIndex)
// Get lenght
switch selectInputType(input)
case 0 {
inputHashLength := 33
}
case 1 {
inputHashLength := 33
}
case 2 {
inputHashLength := 65
}
case 3 {
inputHashLength := 33
}
default { assertOrInvalidProof(0, 0) }
// Set metadata
inputHash := keccak256(input, inputHashLength)
}
// Select Metadata Selected (Used after verifyTransactionData)
function selectMetadataSelected(proofIndex) -> metadata {
let offset := 0
// Second proof, move offset to 4
if gt(proofIndex, 0) { offset := SelectionStackOffsetSize }
// Return metadata memory position
let metadataInput, input, unused,
unused2 := splitCombinedUint32(mstack(safeAdd(Stack_MetadataSelected, offset)))
// Set metadata
metadata := metadataInput
}
// Select Input Selected (Used after verifyTransactionData)
function selectInputSelected(proofIndex) -> input {
let offset := 0
// Second proof, move offset to 4
if gt(proofIndex, 0) { offset := SelectionStackOffsetSize }
// Get values
let metadata, inputPosition, unused,
unused2 := splitCombinedUint32(mstack(safeAdd(Stack_MetadataSelected, offset)))
// Input position
input := inputPosition
}
// Select Output Selected (Used after verifyTransactionData)
function selectOutputSelected(proofIndex) -> output {
let offset := 0
// Second proof, move offset to 4
if gt(proofIndex, 0) { offset := SelectionStackOffsetSize }
// Return metadata memory position
output := mstack(safeAdd(Stack_OutputSelected, offset))
}
// Select Witness Selected (Used after verifyTransactionData)
function selectWitnessSelected(proofIndex) -> witness {
let offset := 0
// Second proof, move offset to 4
if gt(proofIndex, 0) { offset := SelectionStackOffsetSize }
// Return metadata memory position
witness := mstack(safeAdd(Stack_WitnessSelected, offset))
}
function selectBlockHeaderLength(transactionProof) -> blockHeaderLength {
blockHeaderLength := load32(transactionProof, 0)
}
function selectTransactionRootLength(transactionProof) -> transactionRootLength {
transactionRootLength := load32(transactionProof, 1)
}
function selectMerkleProofLength(transactionProof) -> merkleProofLength {
merkleProofLength := load32(transactionProof, 2)
}
// Select Transaction Proof Lengths
function selectTransactionProofLengths(transactionProof) ->
lengthsLength,
blockHeaderLength,
transactionRootHeaderLength,
transactionDataLength,
transactionMerkleLength,
transactionUTXOLength {
// Compute Proof Length or Lengths
lengthsLength := mul32(5)
// If malformed block proof
if iszero(selectProofType()) {
lengthsLength := mul32(3)
}
// Select Proof Lengths
blockHeaderLength := load32(transactionProof, 0)
transactionRootHeaderLength := load32(transactionProof, 1)
transactionMerkleLength := load32(transactionProof, 2)
transactionDataLength := load32(transactionProof, 3)
transactionUTXOLength := load32(transactionProof, 4)
}
// Select Transaction Proof Memory Position
function selectTransactionProof(proofIndex) -> transactionProof {
// Increase proof memory position for proof type (32 bytes)
transactionProof := safeAdd(Calldata_MemoryPosition, mul32(1))
// Select second proof instead!
if gt(proofIndex, 0) {
// Get lengths
let lengthsLength,
blockHeaderLength,
transactionRootHeaderLength,
transactionDataLength,
transactionMerkleLength,
transactionUTXOLength := selectTransactionProofLengths(transactionProof)
// Secondary position
transactionProof := add4(
transactionProof, lengthsLength, blockHeaderLength,
add4(transactionRootHeaderLength, transactionMerkleLength,
transactionDataLength, transactionUTXOLength))
}
}
// Select Transaction Proof Block Header
function selectBlockHeader(proofIndex) -> blockHeader {
// Select Proof Memory Position
blockHeader := selectTransactionProof(proofIndex)
// If it's not the bond withdrawal
if lt(selectProofType(), 6) {
let lengthsLength,
blockHeaderLength,
transactionRootHeaderLength,
transactionDataLength,
transactionMerkleLength,
transactionUTXOLength := selectTransactionProofLengths(blockHeader)
// Block header (always after lengths)
blockHeader := safeAdd(blockHeader, lengthsLength)
}
}
function selectBlockProducer(blockHeader) -> blockProducer {
blockProducer := load32(blockHeader, 0)
}
function selectBlockHeight(blockHeader) -> blockHeight {
blockHeight := load32(blockHeader, 2)
}
function selectPreviousBlockHash(blockHeader) -> previousBlockHash {
previousBlockHash := load32(blockHeader, 1)
}
function selectTransactionRootsLength(blockHeader) -> transactionRootsLength {
transactionRootsLength := load32(blockHeader, 5)
}
function selectEthereumBlockNumber(blockHeader) -> ethereumBlockNumber {
ethereumBlockNumber := load32(blockHeader, 3)
}
// Select Transaction Root from Proof
function selectTransactionRoot(proofIndex) -> transactionRoot {
// Select Proof Memory Position
let transactionProof := selectTransactionProof(proofIndex)
// Get lengths
let lengthsLength,
blockHeaderLength,
transactionRootHeaderLength,
transactionDataLength,
transactionMerkleLength,
transactionUTXOLength := selectTransactionProofLengths(transactionProof)
// Select Transaction Root Position
transactionRoot := add3(transactionProof, lengthsLength, blockHeaderLength)
}
// Select Root Producer
function selectRootProducer(transactionRoot) -> rootProducer {
rootProducer := load32(transactionRoot, 0)
}
// Select Merkle Tree Root
function selectMerkleTreeRoot(transactionRoot) -> merkleTreeRoot {
merkleTreeRoot := load32(transactionRoot, 1)
}
// Select commitment hash from root
function selectCommitmentHash(transactionRoot) -> commitmentHash {
commitmentHash := load32(transactionRoot, 2)
}
// Select Transaction Root Index
function selectTransactionRootIndex(transactionRoot) -> transactionRootIndex {
transactionRootIndex := load32(transactionRoot, 3)
}
// Select Transaction Root from Proof
function selectTransactionMerkleProof(proofIndex) -> merkleProof {
// Select Proof Memory Position
merkleProof := selectTransactionProof(proofIndex)
// Get lengths
let lengthsLength,
blockHeaderLength,
transactionRootHeaderLength,
transactionDataLength,
transactionMerkleLength,
transactionUTXOLength := selectTransactionProofLengths(merkleProof)
// Select Transaction Root Position
merkleProof := add4(merkleProof, lengthsLength,
blockHeaderLength, transactionRootHeaderLength)
}
// Select First Merkle Proof
function selectMerkleTreeBaseLeaf(merkleProof) -> leaf {
leaf := load32(merkleProof, 3)
}
// Select Opposite Transaction Leaf in Merkle Proof
function selectOppositeTransactionLeaf(merkleProof) -> oppositeTransactionLeaf {
oppositeTransactionLeaf := mload(merkleProof)
}
// Select Merkle Tree Height
function selectMerkleTreeHeight(merkleProof) -> merkleTreeHeight {
merkleTreeHeight := load32(merkleProof, 2)
}
// Select Merkle Tree Height
function selectMerkleTree(merkleProof) -> merkleTree {
merkleTree := safeAdd(merkleProof, mul32(3))
}
// Select Transaction Data from Proof
function selectTransactionData(proofIndex) -> transactionData {
// Select Proof Memory Position
let proofMemoryPosition := selectTransactionProof(proofIndex)
// Get lengths
let lengthsLength,
blockHeaderLength,
transactionRootHeaderLength,
transactionDataLength,
transactionMerkleLength,
transactionUTXOLength := selectTransactionProofLengths(proofMemoryPosition)
// Select Transaction Data Position
transactionData := add4(proofMemoryPosition, lengthsLength,
blockHeaderLength, safeAdd(transactionRootHeaderLength, transactionMerkleLength))
}
function selectTransactionIndex(transactionData) -> transactionIndex {
transactionIndex := load32(transactionData, 3)
}
function selectInputIndex(transactionData) -> outputIndex {
outputIndex := load32(transactionData, 0)
}
function selectOutputIndex(transactionData) -> outputIndex {
outputIndex := load32(transactionData, 1)
}
function selectWitnessIndex(transactionData) -> outputIndex {
outputIndex := load32(transactionData, 2)
}
// Verify Transaction Lengths
function verifyTransactionProofLengths(proofCount) {
// Total Proof Length
let proofLengthWithoutType := 0
// Iterate and Compute Maximum length
for { let proofIndex := 0 }
and(lt(proofIndex, 2), lt(proofIndex, proofCount))
{ proofIndex := safeAdd(proofIndex, 1) } {
// Get lengths
let lengthsLength,
blockHeaderLength,
transactionRootHeaderLength,
transactionDataLength,
transactionMerkleLength,
transactionUTXOLength := selectTransactionProofLengths(selectTransactionProof(proofIndex))
// Add total proof length
proofLengthWithoutType := add4(add4(proofLengthWithoutType,
lengthsLength,
blockHeaderLength,
transactionRootHeaderLength),
transactionDataLength,
transactionMerkleLength,
transactionUTXOLength)
}
// Verify Proof Length Overflow
verifyProofLength(proofLengthWithoutType)
}
// Select Transaction Data from Proof
function selectTransactionUTXOProofs(proofIndex) -> utxoProofs {
// Select Proof Memory Position
let proofMemoryPosition := selectTransactionProof(proofIndex)
// Get lengths
let lengthsLength,
blockHeaderLength,
transactionRootHeaderLength,
transactionDataLength,
transactionMerkleLength,
transactionUTXOLength := selectTransactionProofLengths(proofMemoryPosition)
// Select Transaction Data Position
utxoProofs := safeAdd(selectTransactionData(proofIndex), transactionDataLength)
}
function selectWithdrawalToken(proofIndex) -> withdrawalToken {
withdrawalToken := load32(selectTransactionUTXOProofs(proofIndex), 0)
}
// select proof type
function selectProofType() -> proofType {
proofType := load32(Calldata_MemoryPosition, 0) // 32 byte chunk
}
// Select input
function selectInputType(input) -> result {
result := slice(input, 1) // [1 bytes]
}
// Select utxoID (length includes type)
function selectAndVerifyInputUTXO(input, witnessesLength) -> length, utxoID, witnessReference {
utxoID := mload(safeAdd(1, input))
witnessReference := slice(add3(TypeSize, 32, input), IndexSize)
length := 33 // UTXO + Witness Reference
// Assert Witness Index is Valid
assertOrFraud(lt(witnessReference, witnessesLength),
FraudCode_TransactionInputWitnessReferenceOverflow)
}
// Select Input Deposit Proof
function selectInputDepositOwner(depositProof) -> owner {
// Load owner
owner := load32(depositProof, 0)
}
// Select Input Deposit Proof
function selectInputDepositToken(depositProof) -> token {
// Load owner
token := load32(depositProof, 1)
}
// Select deposit information (length includes type)
function selectAndVerifyInputDeposit(input, witnessesLength) -> length,
depositHashID, witnessReference {
depositHashID := mload(safeAdd(input, TypeSize))
witnessReference := slice(add3(input, TypeSize, 32), IndexSize)
length := 33
// Assert deposit is not zero
assertOrFraud(gt(getDeposits(depositHashID), 0), FraudCode_TransactionInputDepositZero)
// Assert Witness Index is Valid
assertOrFraud(lt(witnessReference, witnessesLength),
FraudCode_TransactionInputDepositWitnessOverflow)
}
// Select HTLC information (length includes type)
function selectAndVerifyInputHTLC(input, witnessesLength) -> length, utxoID,
witnessReference, preImage {
utxoID := mload(safeAdd(input, TypeSize))
witnessReference := slice(add3(input, TypeSize, 32), IndexSize)
preImage := mload(add4(input, TypeSize, 32, IndexSize))
length := 65
// Assert valid Witness Reference (could be changed to generic witness ref overflow later..)
assertOrFraud(lt(witnessReference, witnessesLength),
FraudCode_TransactionHTLCWitnessOverflow)
}
// Select output type
function selectOutputType(output) -> result {
result := slice(output, TypeSize) // [1 bytes]
}
// Select output amounts length (length includes type)
function selectAndVerifyOutputAmountLength(output) -> length {
// Select amounts length past Input Type
length := slice(safeAdd(TypeSize, output), 1)
// Assert amounts length greater than zero
assertOrFraud(gt(length, 0), FraudCode_TransactionOutputAmountLengthUnderflow)
// Assert amounts length less than 33 (i.e 1 <> 32)
assertOrFraud(lte(length, 32), FraudCode_TransactionOutputAmountLengthOverflow)
}
// Select output utxo (length includes type)
function selectAndVerifyOutput(output, isChangeOutput) -> length, amount, owner, tokenID {
let amountLength := selectAndVerifyOutputAmountLength(output)
// Push amount
amount := slice(add3(TypeSize, 1, output), amountLength) // 1 for Type, 1 for Amount Length
// owner dynamic length
let ownerLength := 20
// is Change output, than owner is witness reference
if eq(isChangeOutput, 1) {
ownerLength := 1
}
// Push owner
owner := slice(add4(TypeSize, 1, amountLength, output), ownerLength)
// Select Token ID
tokenID := slice(add4(TypeSize, 1, amountLength, safeAdd(ownerLength, output)), 4)
// Assert Token ID is Valid
assertOrFraud(lt(tokenID, getNumTokens()), FraudCode_TransactionOutputTokenIDOverflow)
// Push Output Length (don't include type size)
length := add4(TypeSize, amountLength, ownerLength, 4)
}
// Select output HTLC
function selectAndVerifyOutputHTLC(output, witnessesLength) -> length, amount, owner,
tokenID, digest, expiry, returnWitness {
// Select amount length
let amountLength := selectAndVerifyOutputAmountLength(output)
// Select Output Details
length, amount, owner, tokenID := selectAndVerifyOutput(output, False)
// htlc
let htlc := add3(TypeSize, output, length)
// Select Digest from Output
digest := mload(htlc)
// Assert Token ID is Valid
assertOrFraud(gt(digest, 0), FraudCode_TransactionOutputHTLCDigestZero)
// Select Expiry
expiry := slice(safeAdd(htlc, DigestSize), ExpirySize)
// Assert Expiry is Valid
assertOrFraud(gt(expiry, 0), FraudCode_TransactionOutputHTLCExpiryZero)
// Set expiry, digest, witness
returnWitness := slice(add3(htlc, DigestSize, ExpirySize), IndexSize)
// Assert Valid Return Witness
assertOrFraud(lt(returnWitness, witnessesLength),
FraudCode_TransactionOutputWitnessReferenceOverflow)
// Determine output length (don't include type size)
length := add4(length, DigestSize, ExpirySize, IndexSize)
}
// Select the Transaction Leaf from Data
function selectTransactionLeaf(transactionData) -> leaf {
/*
- Transaction Data:
- inputSelector [32 bytes]
- outputSelector [32 bytes]
- witnessSelector [32 bytes]
- transactionIndex [32 bytes]
- transactionLeafData [dynamic bytes]
*/
// Increase memory past the 3 selectors and 1 Index
leaf := safeAdd(transactionData, mul32(6))
}
// Select transaction length
function selectTransactionLength(transactionData) -> transactionLength {
// Select transaction length
transactionLength := slice(selectTransactionLeaf(transactionData), 2)
}
// Select Metadata Length
function selectTransactionMetadataLength(transactionData) -> metadataLength {
// Select metadata length 1 bytes
metadataLength := slice(safeAdd(selectTransactionLeaf(transactionData), 2), 1)
}
// Select Witnesses (past witness length)
function selectTransactionWitnesses(transactionData) -> witnessesMemoryPosition {
// Compute metadata size
let metadataLength := selectTransactionMetadataLength(transactionData)
// Compute Metadata Size
let metadataSize := safeAdd(TypeSize, safeMul(MetadataSize, metadataLength)) // Length + metadata size
// Leaf + Size 2 + metadata size and witness size
witnessesMemoryPosition := add4(selectTransactionLeaf(transactionData), 2,
metadataSize, 1)
}
function selectWitnessSignature(witnesses, witnessIndex) -> signature {
// Compute witness offset
let witnessMemoryOffset := safeMul(witnessIndex, WitnessSize)
// Compute signature
signature := safeAdd(witnesses, witnessMemoryOffset)
}
// Note, we allow the transactionRootProducer to be a witness, witnesses length must be 1, zero fill 65 for witness data..
// Select Witnesses Signature
function verifyTransactionWitness(signature, transactionHashID, outputOwner, rootProducer) {
// Check if the witness is not the transaction root producer (i.e. a contract possibly)
if iszero(eq(rootProducer, outputOwner)) {
// Assert if witness signature is invalid!
assertOrFraud(eq(outputOwner, ecrecoverPacked(transactionHashID, signature)),
FraudCode_InvalidTransactionWitnessSignature)
}
}
// Select Transaction Leaf Data
function selectAndVerifyTransactionLeafData(transactionData) ->
transactionHashData, // transaction hash data (unsigned transaction data)
metadataSize, // total metadata chunk size (length + metadata)
witnessesSize, // total witness size (length + witnesses)
witnessesLength { // total witnesses length
// Compute metadata size
let metadataLength := selectTransactionMetadataLength(transactionData)
// Assert metadata length correctness (metadata length can be zero)
assertOrFraud(lte(metadataLength, TransactionLengthMax),
FraudCode_TransactionMetadataLengthOverflow)
// Compute Metadata Size
metadataSize := safeAdd(1, safeMul(MetadataSize, metadataLength)) // Length + metadata size
// Leaf + Size 2 + metadata size and witness size
transactionHashData := add3(selectTransactionLeaf(transactionData), 2, metadataSize)
// get witnesses length
witnessesLength := slice(transactionHashData, 1) // Witness Length
witnessesSize := safeAdd(1, safeMul(WitnessSize, witnessesLength)) // Length + witness size
// Leaf + Size 2 + metadata size and witness size
transactionHashData := safeAdd(transactionHashData, witnessesSize)
}
// Select Transaction Details
function selectAndVerifyTransactionDetails(transactionData) ->
memoryPosition, inputsLength, outputsLength, witnessesLength {
let unsignedTransactionData, metadataSize,
witnessesSize, witnessLength := selectAndVerifyTransactionLeafData(transactionData)
// Setup length (push to new name)
witnessesLength := witnessLength
// Set Transaction Data Memory Position
memoryPosition := unsignedTransactionData
// Assert witness length
assertOrFraud(gt(witnessesLength, TransactionLengthMin),
FraudCode_TransactionWitnessesLengthUnderflow)
assertOrFraud(lte(witnessesLength, TransactionLengthMax),
FraudCode_TransactionWitnessesLengthOverflow)
// Select lengths
inputsLength := slice(memoryPosition, 1) // Inputs Length
outputsLength := slice(safeAdd(1, memoryPosition), 1) // Outputs Length
// Assert inputsLength and outputsLength minimum
assertOrFraud(gt(inputsLength, TransactionLengthMin),
FraudCode_TransactionInputsLengthUnderflow)
assertOrFraud(gt(outputsLength, TransactionLengthMin),
FraudCode_TransactionOutputsLengthUnderflow)
// Assert Length overflow checks
assertOrFraud(lte(inputsLength, TransactionLengthMax),
FraudCode_TransactionInputsLengthOverflow)
assertOrFraud(lte(outputsLength, TransactionLengthMax),
FraudCode_TransactionOutputsLengthOverflow)
// Assert metadata length correctness (metadata length can be zero)
assertOrFraud(lte(selectTransactionMetadataLength(transactionData), inputsLength),
FraudCode_TransactionMetadataLengthOverflow)
// Assert selections are valid against lengths
assertOrInvalidProof(lt(selectInputSelectionIndex(transactionData), inputsLength),
ErrorCode_InputIndexSelectedOverflow)
assertOrInvalidProof(lt(selectOutputSelectionIndex(transactionData), outputsLength),
ErrorCode_OutputIndexSelectedOverflow)
assertOrInvalidProof(lt(selectWitnessSelectionIndex(transactionData), witnessesLength),
ErrorCode_WitnessIndexSelectedOverflow)
}
// Select Transaction Metadata (Past Length)
function selectTransactionMetadata(transactionData) -> transactionMetadata {
// Increase memory position past lengths
transactionMetadata := safeAdd(selectTransactionLeaf(transactionData), 3)
}
// Select UTXO proof
function selectAndVerifyUTXOAmountOwner(utxoProof, requestedOutputType, providedUTXOID) ->
outputAmount, outputOwner, tokenID {
/*
- Transaction UTXO Proof(s): -- 288 bytes (same order as inputs, skip Deposit index with zero fill)
- transactionHashId [32 bytes] -- bytes32
- outputIndex [32 bytes] -- padded uint8
- type [32 bytes] -- padded uint8
- amount [32 bytes] -- uint256
- owner [32 bytes] -- padded address or witness reference index uint8
- tokenID [32 bytes] -- padded uint32
- [HTLC Data]:
- digest [32 bytes] -- bytes32 (or zero pad 32 bytes)
- expiry [32 bytes] -- padded uint32 (or zero pad 32 bytes)
- return witness index [32 bytes] -- padded uint8] (or zero pad 32 bytes)
*/
// Assert computed utxo id correct
assertOrInvalidProof(eq(providedUTXOID, constructUTXOID(utxoProof)),
ErrorCode_TransactionUTXOIDInvalid)
// Compute output amount
let outputType := load32(utxoProof, 2)
// Assert output type is correct
assertOrFraud(eq(requestedOutputType, outputType),
FraudCode_TransactionUTXOType)
// Assert index correctness
assertOrFraud(lt(load32(utxoProof, 1), TransactionLengthMax),
FraudCode_TransactionUTXOOutputIndexOverflow)
// Compute output amount
outputAmount := load32(utxoProof, 3)
// Compute output amount
outputOwner := load32(utxoProof, 4)
// Compute output amount
tokenID := load32(utxoProof, 5)
}
//
// CONSTRUCTION METHODS
// For the construction of cryptographic side-chain hashes
//
// produce block hash from block header
function constructBlockHash(blockHeader) -> blockHash {
/*
- Block Header:
- blockProducer [32 bytes] -- padded address
- previousBlockHash [32 bytes]
- blockHeight [32 bytes]
- ethereumBlockNumber [32 bytes]
- transactionRoots [64 + bytes32 array]
*/
// Select Transaction root Length
let transactionRootsLength := load32(blockHeader, 5)
// Construct Block Hash
blockHash := keccak256(blockHeader, mul32(safeAdd(6, transactionRootsLength)))
}
// produce a transaction hash id from a proof (subtract metadata and inputs length from hash data)
function constructTransactionHashID(transactionData) -> transactionHashID {
/*
- Transaction Data:
- inputSelector [32 bytes]
- outputSelector [32 bytes]
- witnessSelector [32 bytes]
- transactionIndex [32 bytes]
- transactionLeafData [dynamic bytes]
- Transaction Leaf Data:
- transactionByteLength [2 bytes] (max 2048)
- metadata length [1 bytes] (min 1 - max 8)
- input metadata [dynamic -- 8 bytes per]:
- blockHeight [4 bytes]
- transactionRootIndex [1 byte]
- transactionIndex [2 bytes]
- output index [1 byte]
- witnessLength [1 bytes]
- witnesses [dynamic]:
- signature [65 bytes]
*/
// Get entire tx length, and metadata sizes / positions
let transactionLength := selectTransactionLength(transactionData) // length is first 2
if gt(transactionLength, 0) {
let transactionLeaf, metadataSize,
witnessesSize, witnessLength := selectAndVerifyTransactionLeafData(transactionData)
// setup hash keccak256(start, length)
let transactionHashDataLength := safeSub(safeSub(transactionLength, TransactionLengthSize),
safeAdd(metadataSize, witnessesSize))
// create transaction ID
transactionHashID := keccak256(transactionLeaf, transactionHashDataLength)
}
}
// Construct Deposit Hash ID
function constructDepositHashID(depositProof) -> depositHashID {
depositHashID := keccak256(depositProof, mul32(3))
}
// Construct a UTXO Proof from a Transaction Output
function constructUTXOProof(transactionHashID, outputIndex, output) -> utxoProof {
let isChangeOutput := False
// Output Change
if eq(selectOutputType(output), OutputType_Change) {
isChangeOutput := True
}
// Select and Verify output
let length, amount, owner, tokenID := selectAndVerifyOutput(output, isChangeOutput)
// Encode Pack Transaction Output Data
mstore(mul32(1), transactionHashID)
mstore(mul32(2), outputIndex)
mstore(mul32(3), selectOutputType(output))
mstore(mul32(4), amount)
mstore(mul32(5), owner) // address or witness index
mstore(mul32(6), tokenID)
mstore(mul32(7), 0)
mstore(mul32(8), 0)
mstore(mul32(9), 0)
// Include HTLC Data here
if eq(selectOutputType(output), 2) {
let unused0, unused1, unused2,
unused3, digest, expiry, returnWitness := selectAndVerifyOutputHTLC(output,
TransactionLengthMax)
mstore(mul32(7), digest)
mstore(mul32(8), expiry)
mstore(mul32(9), returnWitness)
}
// Return UTXO Memory Position
utxoProof := mul32(1)
}
// Construct a UTXO ID
function constructUTXOID(utxoProof) -> utxoID {
/*
- Transaction UTXO Data:
- transactionHashId [32 bytes]
- outputIndex [32 bytes] -- padded uint8
- type [32 bytes] -- padded uint8
- amount [32 bytes]
- owner [32 bytes] -- padded address or unit8
- tokenID [32 bytes] -- padded uint32
- [HTLC Data]: -- padded with zeros
- digest [32 bytes]
- expiry [32 bytes] -- padded 4 bytes
- return witness index [32 bytes] -- padded 1 bytes
*/
// Construct UTXO ID
utxoID := keccak256(utxoProof, UTXOProofSize)
}
// Construct the Transaction Leaf Hash
function constructTransactionLeafHash(transactionData) -> transactionLeafHash {
/*
- Transaction Data:
- inputSelector [32 bytes]
- outputSelector [32 bytes]
- witnessSelector [32 bytes]
- transactionIndex [32 bytes]
- transactionLeafData [dynamic bytes]
*/
// Get first two transaction length bytes
let transactionLength := selectTransactionLength(transactionData)
// Check if length is Zero, than don't hash!
switch eq(transactionLength, 0)
// Return Zero leaf hash
case 1 {
transactionLeafHash := 0
}
// Hash as Normal Transaction
default {
// Start Hash Past Selections (3) and Index (1)
let hashStart := selectTransactionLeaf(transactionData)
// Return the transaction leaf hash
transactionLeafHash := keccak256(hashStart, transactionLength)
}
}
// Select input index
function selectInputSelectionIndex(transactionData) -> inputIndex {
inputIndex := load32(transactionData, 0)
}
// Select output index
function selectOutputSelectionIndex(transactionData) -> outputIndex {
outputIndex := load32(transactionData, 1)
}
// Select witness index
function selectWitnessSelectionIndex(transactionData) -> witnessIndex {
witnessIndex := load32(transactionData, 2)
}
// This function Must Select Block of Current Proof Being Validated!! NOT DONE YET!
// Assert True or Fraud, Set Side-chain to Valid block and Stop Execution
function assertOrFraud(assertion, fraudCode) {
// Assert or Begin Fraud State Change Sequence
if lt(assertion, 1) {
// proof index
let proofIndex := 0
// We are validating proof 2
if gt(mstack(Stack_ProofNumber), 0) {
proofIndex := 1
}
// Fraud block details
let fraudBlockHeight := selectBlockHeight(selectBlockHeader(proofIndex))
let fraudBlockProducer := selectBlockProducer(selectBlockHeader(proofIndex))
let ethereumBlockNumber := selectEthereumBlockNumber(selectBlockHeader(proofIndex))
// Assert Fraud block cannot be the genesis block
assertOrInvalidProof(gt(fraudBlockHeight, GenesisBlockHeight),
ErrorCode_FraudBlockHeightUnderflow)
// Assert fraud block cannot be finalized
assertOrInvalidProof(lt(number(), safeAdd(ethereumBlockNumber, FINALIZATION_DELAY)),
ErrorCode_FraudBlockFinalized)
// Push old block tip
let previousBlockTip := getBlockTip()
// Set new block tip to before fraud block
setBlockTip(safeSub(fraudBlockHeight, 1))
// Release Block Producer, If it's Permissioned
// (i.e. block producer committed fraud so get them out!)
// if eq(fraudBlockProducer, getBlockProducer()) {
// setBlockProducer(0)
// }
// Log block tips (old / new)
log4(0, 0, FraudEventTopic, previousBlockTip, getBlockTip(),
fraudCode)
// Transfer Half The Bond for this Block
transfer(div(BOND_SIZE, 2), EtherToken, EtherToken, caller())
// stop execution from here
stop()
}
}
// Construct withdrawal Hash ID
function constructWithdrawalHashID(transactionRootIndex,
transactionLeafHash, outputIndex) -> withdrawalHashID {
// Construct withdrawal Hash
mstore(mul32(1), transactionRootIndex)
mstore(mul32(2), transactionLeafHash)
mstore(mul32(3), outputIndex)
// Hash Leaf and Output Together
withdrawalHashID := keccak256(mul32(1), mul32(3))
}
// Construct Transactions Merkle Tree Root
function constructMerkleTreeRoot(transactions, transactionsLength) -> merkleTreeRoot {
// Start Memory Position at Transactions Data
let memoryPosition := transactions
let nodesLength := 0
let netLength := 0
let freshMemoryPosition := mstack(Stack_FreshMemory)
// create base hashes and notate node count
for { let transactionIndex := 0 }
lt(transactionIndex, MaxTransactionsInBlock)
{ transactionIndex := safeAdd(transactionIndex, 1) } {
// get the transaction length
let transactionLength := slice(memoryPosition, TransactionLengthSize)
// If Transaction length is zero and we are past first tx, stop (we are at the end)
if and(gt(transactionIndex, 0), iszero(transactionLength)) { break }
// if transaction length is below minimum transaction length, stop
verifyTransactionLength(transactionLength)
// add net length together
netLength := safeAdd(netLength, transactionLength)
// computed length greater than provided payload
assertOrFraud(lte(netLength, transactionsLength),
FraudCode_InvalidTransactionsNetLength)
// store the base leaf hash (add 2 removed from here..)
mstore(freshMemoryPosition, keccak256(memoryPosition, transactionLength))
// increase the memory length
memoryPosition := safeAdd(memoryPosition, transactionLength)
// increase fresh memory by 32 bytes
freshMemoryPosition := safeAdd(freshMemoryPosition, 32)
// increase number of nodes
nodesLength := safeAdd(nodesLength, 1)
}
// computed length greater than provided payload
assertOrFraud(eq(netLength, transactionsLength), FraudCode_InvalidTransactionsNetLength)
// Merkleize nodes into a binary merkle tree
memoryPosition := safeSub(freshMemoryPosition, safeMul(nodesLength, 32)) // setup new memory position
// Create Binary Merkle Tree / Master Root Hash
for {} gt(nodesLength, 0) {} { // loop through tree Heights (starting at base)
if gt(mod(nodesLength, 2), 0) { // fix uneven leaf count (i.e. add a zero hash)
mstore(safeAdd(memoryPosition, safeMul(nodesLength, 32)), 0) // add 0x00...000 hash leaf
nodesLength := safeAdd(nodesLength, 1) // increase count for zero hash leaf
freshMemoryPosition := safeAdd(freshMemoryPosition, 32) // increase fresh memory past new leaf
}
for { let i := 0 } lt(i, nodesLength) { i := safeAdd(i, 2) } { // loop through Leaf hashes at this height
mstore(freshMemoryPosition, keccak256(safeAdd(memoryPosition, safeMul(i, 32)), 64)) // hash two leafs together
freshMemoryPosition := safeAdd(freshMemoryPosition, 32) // increase fresh memory past new hash leaf
}
memoryPosition := safeSub(freshMemoryPosition, safeMul(nodesLength, 16)) // set new memory position
nodesLength := div(nodesLength, 2) // half nodes (i.e. next height)
// shim 1 to zero (stop), i.e. top height end..
if lt(nodesLength, 2) { nodesLength := 0 }
}
// merkle root has been produced
merkleTreeRoot := mload(memoryPosition)
// write new fresh memory position
mpush(Stack_FreshMemory, safeAdd(freshMemoryPosition, mul32(2)))
}
// Construct HTLC Digest Hash
function constructHTLCDigest(preImage) -> digest {
// Store PreImage in Memory
mstore(mul32(1), preImage)
// Construct Digest Hash
digest := keccak256(mul32(1), mul32(1))
}
//
// LOW LEVEL METHODS
//
// Safe Math Add
function safeAdd(x, y) -> z {
z := add(x, y)
assertOrInvalidProof(or(eq(z, x), gt(z, x)), ErrorCode_SafeMathAdditionOverflow) // require((z = x + y) >= x, "ds-math-add-overflow");
}
// Safe Math Subtract
function safeSub(x, y) -> z {
z := sub(x, y)
assertOrInvalidProof(or(eq(z, x), lt(z, x)), ErrorCode_SafeMathSubtractionUnderflow) // require((z = x - y) <= x, "ds-math-sub-underflow");
}
// Safe Math Multiply
function safeMul(x, y) -> z {
if gt(y, 0) {
z := mul(x, y)
assertOrInvalidProof(eq(div(z, y), x), ErrorCode_SafeMathMultiplyOverflow) // require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
}
// Safe Math Add3, Add4 Shorthand
function add3(x, y, z) -> result {
result := safeAdd(x, safeAdd(y, z))
}
function add4(x, y, z, k) -> result {
result := safeAdd(x, safeAdd(y, safeAdd(z, k)))
}
// Common <= and >=
function lte(v1, v2) -> result {
result := or(lt(v1, v2), eq(v1, v2))
}
function gte(v1, v2) -> result {
result := or(gt(v1, v2), eq(v1, v2))
}
// Safe Multiply by 32
function mul32(length) -> result {
result := safeMul(32, length)
}
// function combine 3 unit32 values together into one 32 byte combined value
function combineUint32(val1, val2, val3, val4) -> combinedValue {
mstore(safeAdd(mul32(2), 8), val4) // 2 bytes
mstore(safeAdd(mul32(2), 6), val3) // 2 bytes
mstore(safeAdd(mul32(2), 4), val2) // 2 bytes
mstore(safeAdd(mul32(2), 2), val1) // 2 bytes
// Grab combined value
combinedValue := mload(mul32(3))
}
// split a combined value into three original chunks
function splitCombinedUint32(combinedValue) -> val1, val2, val3, val4 {
mstore(mul32(2), combinedValue)
// grab values
val1 := slice(safeAdd(mul32(2), 0), 2) // 2 byte slice
val2 := slice(safeAdd(mul32(2), 2), 2) // 2 byte slice
val3 := slice(safeAdd(mul32(2), 4), 2) // 2 byte slice
val3 := slice(safeAdd(mul32(2), 6), 2) // 2 byte slice
}
// Transfer method helper
function transfer(amount, tokenID, token, owner) {
// Assert value owner / amount
assertOrInvalidProof(gt(amount, 0), ErrorCode_TransferAmountUnderflow)
assertOrInvalidProof(gt(owner, 0), ErrorCode_TransferOwnerInvalid)
// Assert valid token ID
assertOrInvalidProof(lt(tokenID, getNumTokens()), ErrorCode_TransferTokenIDOverflow)
// Assert address is properly registered token
assertOrInvalidProof(eq(tokenID, getTokens(token)), ErrorCode_TransferTokenAddress)
// Ether Token
if eq(token, EtherToken) {
let result := call(owner, 21000, amount, 0, 0, 0, 0)
assertOrInvalidProof(result, ErrorCode_TransferEtherCallResult)
}
// ERC20 "a9059cbb": "transfer(address,uint256)",
if gt(token, 0) {
// Construct ERC20 Transfer
mstore(mul32(1), 0xa9059cbb)
mstore(mul32(2), owner)
mstore(mul32(3), amount)
// Input Details
let inputStart := safeAdd(mul32(1), 28)
let inputLength := 68
// ERC20 Call
let result := call(token, 400000, 0, inputStart, inputLength, 0, 0)
assertOrInvalidProof(result, ErrorCode_TransferERC20Result)
}
}
// Virtual Memory Stack Push (for an additional 32 stack positions)
function mpush(pos, val) { // Memory Push
mstore(add(Stack_MemoryPosition, mul32(pos)), val)
}
// Virtual Memory Stack Get
function mstack(pos) -> result { // Memory Stack
result := mload(add(Stack_MemoryPosition, mul32(pos)))
}
// Virtual Stack Pop
function mpop(pos) { // Memory Pop
mstore(add(Stack_MemoryPosition, mul32(pos)), 0)
}
// Memory Slice (within a 32 byte chunk)
function slice(position, length) -> result {
if gt(length, 32) { revert(0, 0) } // protect against overflow
result := div(mload(position), exp(2, safeSub(256, safeMul(length, 8))))
}
// Solidity Storage Key: mapping(bytes32 => bytes32)
function mappingStorageKey(key, storageIndex) -> storageKey {
mstore(32, key)
mstore(64, storageIndex)
storageKey := keccak256(32, 64)
}
// Solidity Storage Key: mapping(bytes32 => mapping(bytes32 => bytes32)
function mappingStorageKey2(key, key2, storageIndex) -> storageKey {
mstore(32, key)
mstore(64, storageIndex)
mstore(96, key2)
mstore(128, keccak256(32, 64))
storageKey := keccak256(96, 64)
}
// load a 32 byte chunk with a 32 byte offset chunk from position
function load32(memoryPosition, chunkOffset) -> result {
result := mload(add(memoryPosition, safeMul(32, chunkOffset)))
}
// Assert True or Invalid Proof
function assertOrInvalidProof(arg, errorCode) {
if lt(arg, 1) {
// Set Error Code In memory
mstore(mul32(1), errorCode)
// Revert and Return Error Code
revert(mul32(1), mul32(1))
// Just incase we add a stop
stop()
}
}
// ECRecover Helper: hashPosition (32 bytes), signaturePosition (65 bytes) tight packing VRS
function ecrecoverPacked(digestHash, signatureMemoryPosition) -> account {
mstore(32, digestHash) // load in hash
mstore(64, 0) // zero pas
mstore(95, mload(signatureMemoryPosition))
mstore(96, mload(safeAdd(signatureMemoryPosition, 1)))
mstore(128, mload(safeAdd(signatureMemoryPosition, 33)))
let result := call(3000, 1, 0, 32, 128, 128, 32) // 4 chunks, return at 128
if eq(result, 0) { revert(0, 0) }
account := mload(128) // set account
}
//
// SETTERS & GETTER METHODS
// Solidity setters and getters for side-chain state storage
//
// GET mapping(bytes32 => uint256) public deposits; // STORAGE 0
function getDeposits(depositHashId) -> result {
result := sload(mappingStorageKey(depositHashId, Storage_deposits))
}
// GET mapping(uint256 => mapping(bytes32 => bool)) publica withdrawals; // STORAGE 1
function getWithdrawals(blockHeight, withdrawalHashID) -> result {
result := sload(mappingStorageKey2(blockHeight, withdrawalHashID, Storage_withdrawals))
}
// SET mapping(uint256 => mapping(bytes32 => bool)) publica withdrawals; // STORAGE 1
function setWithdrawals(blockHeight, withdrawalHashID, hasWithdrawn) {
sstore(mappingStorageKey2(blockHeight, withdrawalHashID, Storage_withdrawals), hasWithdrawn)
}
// GET mapping(bytes32 => uint256) public blockTransactionRoots; // STORAGE 2
function getBlockTransactionRoots(transactionRoot) -> result {
result := sload(mappingStorageKey(transactionRoot, Storage_blockTransactionRoots))
}
// GET mapping(uint256 => bytes32) public blockCommitments; // STORAGE 3
function getBlockCommitments(blockHeight) -> result {
result := sload(mappingStorageKey(blockHeight, Storage_blockCommitments))
}
// GET mapping(address => uint256) public tokens; // STORAGE 4
function getTokens(tokenAddress) -> result {
result := sload(mappingStorageKey(tokenAddress, Storage_tokens))
// Ether token should always be zero
if eq(tokenAddress, 0) {
assertOrInvalidProof(eq(result, 0), ErrorCode_InvalidTokenAddress)
}
// ERC20 should always be above zero
if gt(tokenAddress, 0) {
assertOrInvalidProof(gt(result, 0), ErrorCode_InvalidTokenAddress)
}
}
// GET uint256 public numTokens; // STORAGE 5
function getNumTokens() -> result {
result := sload(Storage_numTokens)
}
// SET uint256 public blockTip; // STORAGE 6
function getBlockTip() -> result {
result := sload(Storage_blockTip)
}
// SET blockTip() // STORAGE 6
function setBlockTip(tip) {
sstore(Storage_blockTip, tip)
}
// GET address public blockProducer; // STORAGE 7
function getBlockProducer() -> result {
result := sload(Storage_blockProducer)
}
// SET address public blockProducer // STORAGE 7
function setBlockProducer(producer) {
sstore(Storage_blockProducer, producer)
}
}
}
}
| Set Block Header Position (on First Proof) Proof 0 Block Header Position Proof 0 Block Header Position Return Stack Offset: (No Offset) First Transaction Proof 0 Transaction Root Producer | if iszero(mstack(Stack_ProofNumber)) {
mpush(Stack_BlockHeader, selectBlockHeader(FirstProof))
mpush(Stack_RootHeader, selectTransactionRoot(FirstProof))
mpush(Stack_SelectionOffset, 0)
mpush(Stack_RootProducer, selectRootProducer(selectTransactionRoot(FirstProof)))
}
| 12,672,800 | [
1,
694,
3914,
4304,
11010,
261,
265,
5783,
1186,
792,
13,
1186,
792,
374,
3914,
4304,
11010,
1186,
792,
374,
3914,
4304,
11010,
2000,
7283,
9874,
30,
261,
2279,
9874,
13,
5783,
5947,
1186,
792,
374,
5947,
7450,
21123,
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,
2868,
309,
353,
7124,
12,
81,
3772,
12,
2624,
67,
20439,
1854,
3719,
288,
203,
7734,
312,
6206,
12,
2624,
67,
1768,
1864,
16,
2027,
1768,
1864,
12,
3759,
20439,
3719,
203,
203,
7734,
312,
6206,
12,
2624,
67,
2375,
1864,
16,
2027,
3342,
2375,
12,
3759,
20439,
3719,
203,
203,
7734,
312,
6206,
12,
2624,
67,
6233,
2335,
16,
374,
13,
203,
203,
7734,
312,
6206,
12,
2624,
67,
2375,
12140,
16,
2027,
2375,
12140,
12,
4025,
3342,
2375,
12,
3759,
20439,
20349,
203,
2868,
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
]
|
./full_match/421613/0xdfFF0DbD5811351Ff622d679610EFE91A257A81C/sources/contracts/Lock.sol | Uncomment this line to use console.log | import "hardhat/console.sol";
| 11,578,361 | [
1,
984,
3469,
333,
980,
358,
999,
2983,
18,
1330,
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,
1930,
315,
20379,
11304,
19,
8698,
18,
18281,
14432,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2022-02-01
*/
// File: @openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.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 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/utils/structs/EnumerableSetUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// File: @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.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 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/StringsUpgradeable.sol
// 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/access/IAccessControlUpgradeable.sol
// 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/access/IAccessControlEnumerableUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
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/introspection/ERC165Upgradeable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
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;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.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 ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (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 {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
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 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 ",
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 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());
}
}
uint256[49] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
}
function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
uint256[49] private __gap;
}
// File: contracts/interfaces/IBoaxNFT.sol
pragma solidity 0.8.0;
interface IBoaxNFT {
/**
* @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;
function mint( string memory _tokenURI, address _to) external;
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns whether `tokenId` exists.
*/
function isTokenExists(uint256 tokenId) external view returns (bool);
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) external view returns (address);
}
// File: contracts/BoaxMarketplace.sol
pragma solidity 0.8.0;
contract BoaxMarketplace is Initializable, AccessControlEnumerableUpgradeable {
IBoaxNFT public BoaxNFT;
using CountersUpgradeable for CountersUpgradeable.Counter; // counters for marketplace
CountersUpgradeable.Counter private auctionsCount; // auctions Count only used internally
CountersUpgradeable.Counter private salesCounter; // fix Price Sales count only used internally
bytes32 public constant ARTIST_ROLE = keccak256("ARTIST_ROLE"); // The ARTIST_ROLE is the
address payable public feeAccount; // EOA or MultiSig owned by BOAX
uint8 private SALE_FEE; // fee on all sales paid to Boax
uint8 private SECONDARY_SALE_FEE_ARTIST; // (profits) on all secondary sales paid to the artist
//structs
struct Auction {
uint256 _tokenId;
address _owner;
uint256 _reservePrice;
uint256 _highestBid;
address _highestBidder;
uint256 _endTimeInSeconds;
bool _isSettled;
}
struct Bidder {
uint256 amount;
bool hasWithdrawn;
bool isVaild;
}
struct FixPriceSale {
uint256 _tokenId;
address _owner;
uint256 _price;
bool _onSale;
bool _isSold;
bool _isCanceled;
}
mapping(uint256 => bool) public secondarySale;
// map token ID to bool indicating wether it has been sold before
mapping(uint256 => address payable) public artists;
// token ID to artist mapping, used for sending fees to artist on secondary sales
mapping(uint256 => Auction) public auctions;
mapping(uint256 => mapping(address => Bidder)) public auctionBidders;
// token Id to fixPriceSales
mapping(uint256 => FixPriceSale) public fixPriceSales;
// Events
event Mint(address indexed from, address indexed to, uint256 indexed tokenId);
event AuctionCreated(
uint256 _auctionId,
uint256 _reservePrice,
uint256 _endTimeInSeconds,
address _owner,
uint256 _tokenId
);
event AuctionSettled(
uint256 _auctionId,
address _owner,
address _winner,
uint256 _finalHighestBid,
uint256 _tokenId
);
event PlacedBid(address _bidder, uint256 _bid);
event Trade(address _from, address _to, uint256 _amount, uint256 _tokenId);
event WithdrewAuctionBid(address _by, uint256 _amount);
event SetForFixPriceSale(
uint256 _fixPriceSaleId,
uint256 _tokenId,
uint256 _amount,
address _owner
);
event PurchasedNFT(
uint256 _fixPriceSaleId,
address _seller,
address _buyer,
uint256 _tokenId,
uint256 _amount
);
event SaleCanceled(uint256 _fixPriceSaleId, uint256 _tokenId, address _by);
event UpdateSalePrice(uint256 _fixPriceSaleId, uint256 _newPrice);
event RedeemedBalance(uint256 _amount, address _by);
event UpdateFee(address _by, uint256 _newFee);
//modifiers
modifier onlyAuctionOwner(uint256 _auctionId) {
require(msg.sender == auctions[_auctionId]._owner, "not the owner.");
_;
}
modifier auctionExists(uint256 _auctionId) {
require(
_auctionId <= auctionsCount.current() && _auctionId != 0,
"nonexistent Auction"
);
_;
}
modifier hasAuctionEnded(uint256 _auctionId) {
require(
auctions[_auctionId]._endTimeInSeconds < (block.timestamp),
"Auction is running"
);
_;
}
modifier saleRequirements(uint256 _tokenId) {
require(BoaxNFT.isTokenExists(_tokenId), "nonexistent tokenId.");
require(BoaxNFT.ownerOf(_tokenId) == msg.sender, "not the owner");
_;
}
modifier saleExists(uint256 _saleId) {
require(
_saleId <= salesCounter.current() && _saleId != 0,
"nonexistent sale"
);
_;
}
modifier onlyAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "NOT ADMIN");
_;
}
modifier fixSaleReqs(uint256 _fixPriceSaleId) {
require(fixPriceSales[_fixPriceSaleId]._owner == msg.sender, "not owner.");
require(fixPriceSales[_fixPriceSaleId]._isSold == false, "NFT is sold");
require(fixPriceSales[_fixPriceSaleId]._isCanceled == false, "not on sale");
_;
}
modifier isAcceptAbleFee(uint8 _fee) {
require((_fee + SECONDARY_SALE_FEE_ARTIST) <= 100, "fee overflow");
require(_fee >= 1, "fee unserflow");
require(_fee <= 100, "no! not 100");
_;
}
/**
* @dev Grants `DEFAULT_ADMIN_ROLE` to the
* account that deploys the contract.
* Token URIs will be autogenerated based on `baseURI` and their token IDs.
* See {ERC721-tokenURI}.
*/
function initialize(address _NFT) public initializer {
require(_NFT != address(0), "Invalid address");
address _admin = 0x3324E31376d8Df4c303C8876244631DFD625b5e3;
// default values
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender); // the deployer must have admin role. It is not possible if this role is not granted.
_setupRole(ARTIST_ROLE, _admin);
feeAccount = payable(_admin);
// account or contract that can redeem funds from fees.
SALE_FEE = 2; // 2% fee on all sales paid to Boax (artist receives the remainder, 98%)
SECONDARY_SALE_FEE_ARTIST = 2; // 2% fee (profits) on all secondary sales paid to the artist (seller receives remainder after paying 2% secondary fees to artist and 2% to Boax, 96%)
BoaxNFT = IBoaxNFT(_NFT);
}
/**
* @dev setter function only callable by contract admin used to change the address to which fees are paid
* @param _feeAccount is the address owned by Boax that will collect sales fees
*/
function setFeeAccount(address payable _feeAccount) external onlyAdmin() {
feeAccount = _feeAccount;
}
/**
* @dev setter function only callable by contract admin used to update Royality
* @param _fee is the new %age for BOAX marketplace
*/
function setSaleFee(uint8 _fee) external onlyAdmin() isAcceptAbleFee(_fee) {
SALE_FEE = _fee;
emit UpdateFee(msg.sender, SALE_FEE);
}
/**
* @dev setter function only callable by contract admin used to update Royality for artists
* @param _fee is the new %age for NFT's artist
*/
function setSecondarySaleFeeArtist(uint8 _fee)
external
onlyAdmin()
isAcceptAbleFee(_fee)
{
SECONDARY_SALE_FEE_ARTIST = _fee;
emit UpdateFee(msg.sender, SECONDARY_SALE_FEE_ARTIST);
}
/**
* @dev mints a token using BoaxNFT contract
* @param _tokenURI is URI of the NFT's metadata
*/
function mint(string memory _tokenURI) external {
require(hasRole(ARTIST_ROLE, msg.sender), "not ARTIST"); // Must be an artist
uint256 _tokenId = BoaxNFT.totalSupply(); // set URI before minting otherwise the total supply will get increamented
BoaxNFT.mint(_tokenURI, msg.sender);
artists[_tokenId] = payable(msg.sender);
emit Mint(address(0x0), msg.sender, _tokenId);
}
/**
* @dev creates an auction for given token
* @param _tokenId is NFT's token number on contract,
* @param _reservePrice is the starting bid for nft,
* @param _endTimeInSeconds is the auction end time in seconds
*/
function createAuction(
uint256 _tokenId,
uint256 _reservePrice,
uint256 _endTimeInSeconds
) external saleRequirements(_tokenId) {
require(_reservePrice > 0, "underflow");
require(_endTimeInSeconds >= 3600, "LowTime");
auctionsCount.increment(); // start orderCount at 1
_endTimeInSeconds = (block.timestamp) + _endTimeInSeconds;
auctions[auctionsCount.current()] = Auction(
_tokenId,
msg.sender,
_reservePrice,
0,
address(0x0),
_endTimeInSeconds,
false
);
address _owner = payable(msg.sender);
// transfer nft token to contract (this).
BoaxNFT.transferFrom(_owner, address(this), _tokenId);
emit AuctionCreated(
auctionsCount.current(),
_reservePrice,
_endTimeInSeconds,
_owner,
_tokenId
);
}
/**
* @dev transfers NFT and Ether on auction completes
* @param _auctionId is auction number on contract,
*/
function settleAuction(uint256 _auctionId)
external
auctionExists(_auctionId)
hasAuctionEnded(_auctionId)
{
Auction storage _foundAuction = auctions[_auctionId];
require(_foundAuction._isSettled == false, "already settled.");
require(
msg.sender == _foundAuction._owner ||
msg.sender == _foundAuction._highestBidder,
"not Owner or Winner of Auction."
);
// if _highestBidder is 0x0 that's mean there are no bids on Auction
if (_foundAuction._highestBidder == address(0x0)) {
// if auction has complete and there are no bids transfer NFT back to the owner
BoaxNFT.transferFrom(
address(this),
_foundAuction._owner,
_foundAuction._tokenId
);
} else {
_trade(
_foundAuction._owner,
_foundAuction._highestBidder,
_foundAuction._highestBid,
_foundAuction._tokenId
);
}
emit AuctionSettled(
_auctionId,
_foundAuction._owner,
_foundAuction._highestBidder,
_foundAuction._highestBid,
_foundAuction._tokenId
);
auctionBidders[_auctionId][_foundAuction._highestBidder] = Bidder(
0,
true,
false
);
_foundAuction._highestBidder = address(0x0);
_foundAuction._highestBid = 0;
_foundAuction._isSettled = true;
}
/**
* @dev places a bid on an auction
* @param _auctionId is auction number on contract,
*/
function placeBid(uint256 _auctionId)
public
payable
auctionExists(_auctionId)
{
Auction storage _foundAuction = auctions[_auctionId];
require(
_foundAuction._endTimeInSeconds >= block.timestamp,
"Auction ended"
);
if (!auctionBidders[_auctionId][msg.sender].isVaild) {
if (_foundAuction._highestBid != 0)
require(msg.value > _foundAuction._highestBid, "bid underflow");
else require(msg.value >= _foundAuction._reservePrice, "bid underflow");
auctionBidders[_auctionId][msg.sender] = Bidder(msg.value, false, true);
_foundAuction._highestBid = msg.value;
_foundAuction._highestBidder = msg.sender;
} else {
uint256 oldBidAmount = auctionBidders[_auctionId][msg.sender].amount;
require(
msg.value > oldBidAmount && msg.value > _foundAuction._highestBid,
"low bid"
);
auctionBidders[_auctionId][msg.sender].amount = msg.value;
_foundAuction._highestBid = msg.value;
_foundAuction._highestBidder = msg.sender;
payable(msg.sender).transfer(oldBidAmount);
}
emit PlacedBid(msg.sender, msg.value);
}
/**
* @dev the bidder of an auction can withdraw his bid amout if he did not win
* @param _auctionId is the id of auction
*/
function withdrawLostAuctionBid(uint256 _auctionId)
external
auctionExists(_auctionId)
hasAuctionEnded(_auctionId)
{
Auction storage _foundAuction = auctions[_auctionId];
require(
auctionBidders[_auctionId][msg.sender].isVaild &&
auctionBidders[_auctionId][msg.sender].hasWithdrawn == false,
"nothing for you"
);
require(
msg.sender != _foundAuction._highestBidder,
"You win. Settle Auction"
);
uint256 bidAmount = auctionBidders[_auctionId][msg.sender].amount;
payable(msg.sender).transfer(bidAmount);
auctionBidders[_auctionId][msg.sender] = Bidder(0, true, false);
emit WithdrewAuctionBid(msg.sender, bidAmount);
}
/**
* @dev sale NFT on fix price
* @param _tokenId NFT's ID
* @param _amount NFT's price
*/
function createFixPriceSale(uint256 _tokenId, uint256 _amount)
external
saleRequirements(_tokenId)
{
require(_amount > 0, "underflow");
salesCounter.increment();
fixPriceSales[salesCounter.current()] = FixPriceSale(
_tokenId,
msg.sender,
_amount,
true,
false,
false
);
BoaxNFT.transferFrom(msg.sender, address(this), _tokenId);
emit SetForFixPriceSale(
salesCounter.current(),
_tokenId,
_amount,
msg.sender
);
}
/**
* @dev to purchase NFT placed in fix price sale.
* @param _fixPriceSaleId sale Id
*/
function purchaseNFT(uint256 _fixPriceSaleId)
external
payable
saleExists(_fixPriceSaleId)
{
FixPriceSale storage _foundSale = fixPriceSales[_fixPriceSaleId];
require(_foundSale._isCanceled == false, "no sale");
require(_foundSale._isSold == false, "NFT sold");
require(msg.value >= _foundSale._price, "underflow");
_trade(_foundSale._owner, msg.sender, msg.value, _foundSale._tokenId);
_foundSale._isSold = true;
emit PurchasedNFT(
_fixPriceSaleId,
_foundSale._owner,
msg.sender,
_foundSale._tokenId,
msg.value
);
}
/**
* @dev to cancel the fix price sale of the NFT
* @param _fixPriceSaleId id of sale
*/
function cancelFixPriceSale(uint256 _fixPriceSaleId)
external
saleExists(_fixPriceSaleId)
fixSaleReqs(_fixPriceSaleId)
{
FixPriceSale storage _foundSale = fixPriceSales[_fixPriceSaleId];
BoaxNFT.transferFrom(address(this), msg.sender, _foundSale._tokenId);
_foundSale._isCanceled = true;
_foundSale._onSale = false;
emit SaleCanceled(_fixPriceSaleId, _foundSale._tokenId, msg.sender);
}
/**
* @dev updates the price for given an fixedPriceSale
* @param _fixPriceSaleId is NFT's token number on contract,
* @param _newPrice is the starting bid for nft,
*/
function updatePriceOfFixedSale(uint256 _fixPriceSaleId, uint256 _newPrice)
external
saleExists(_fixPriceSaleId)
fixSaleReqs(_fixPriceSaleId)
{
FixPriceSale storage _foundSale = fixPriceSales[_fixPriceSaleId];
require((_foundSale._price != _newPrice) && (_newPrice > 0), "underflow");
_foundSale._price = _newPrice;
emit UpdateSalePrice(_fixPriceSaleId, _newPrice);
}
/**
* @dev to exchange the NFT and amount
* @param _seller current owner of the nft
* @param _buyer buyer of nft
* @param _amount NFT's price
* @param _tokenId NFT's ID
*/
function _trade(
address _seller,
address _buyer,
uint256 _amount,
uint256 _tokenId
) private {
BoaxNFT.transferFrom(address(this), _buyer, _tokenId);
uint256 _feeAmount = (_amount * SALE_FEE) / 100; // Fee paid by the user that fills the order, a.k.a. msg.sender.
// pay primary or secondary sale fees
if (!secondarySale[_tokenId]) {
feeAccount.transfer(_feeAmount); // transfer ETH fees to fee account
secondarySale[_tokenId] = true; // set secondarySale bool to true after first sale
} else {
uint256 _secondaryFeeArtist = (_amount * SECONDARY_SALE_FEE_ARTIST) / 100; // Fee paid by the user that fills the order, a.k.a. msg.sender.
uint256 _boaxFee = (_amount * SALE_FEE) / 100; // Fee paid by the user that fills the order, a.k.a. msg.sender.
_feeAmount = _secondaryFeeArtist + _boaxFee;
feeAccount.transfer(_boaxFee); // transfer secondary sale fees to fee account
artists[_tokenId].transfer(_secondaryFeeArtist); // transfer secondary sale fees to fee artist
}
uint256 remainingFee = _amount - _feeAmount - 5000; // keep 8000 in contract for each _trade call
payable(_seller).transfer(remainingFee); // transfer ETH remainder to the account that sold the NFT
emit Trade(_seller, _buyer, _amount, _tokenId);
}
} | The ARTIST_ROLE is the
| bytes32 public constant ARTIST_ROLE = keccak256("ARTIST_ROLE"); | 10,880,016 | [
1,
1986,
6052,
56,
5511,
67,
16256,
353,
326,
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,
1731,
1578,
1071,
5381,
6052,
56,
5511,
67,
16256,
273,
417,
24410,
581,
5034,
2932,
4928,
5511,
67,
16256,
8863,
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
]
|
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.5;
/**
* @title FrAactionSPDAO
* @author Quentin for FrAaction Gangs
*/
// ============ Internal Import ============
import {
ISettings
} from "./GovSettings.sol";
// ============ External Imports: Inherited Contracts ============
// NOTE: we inherit from OpenZeppelin upgradeable contracts because of the proxy implementation of this logic contract
import {
IERC721Upgradeable
} from "@OpenZeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import {
ERC721HolderUpgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol";
import {
ERC1155HolderUpgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC1155/utils/ERC1155HolderUpgradeable.sol";
import {
IERC1155Upgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol";
import {
IERC20Upgradeable
} from "@OpenZeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {
ERC20Upgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {
ERC20lib
} from "./interfaces/ERC20lib.sol";
import {
DiamondInterface
} from "./DiamondInterface.sol";
contract FraactionSPDAO is ERC20Upgradeable, ERC721HolderUpgradeable, ERC1155HolderUpgradeable {
using Address for address;
// ============ Enums ============
// State Transitions:
// (1) INACTIVE on deploy, finalizeBid() or finalizePurchase()
// (2) ACTIVE on startPurchase(), startFundraising() or startBid()
// (2) FUNDING on confirmFunding()
// (3) SUBMITTED on purchase() or submitBid()
// (4) COMPLETED or FAILED on finalizeBid() or finalizePurchase()
enum fundingStatus {
INACTIVE,
ACTIVE,
FUNDING,
SUBMITTED,
COMPLETED,
FAILED
}
// funding round status of the FrAactionHub
FundingStatus public fundingStatus;
// State Transitions:
// (1) INACTIVE claim()
// (2) ACTIVE on startFinalAuction()
// (3) ENDED on endFinalAuction()
// (4) BURNING on Claim()
enum FinalAuctionStatus {
INACTIVE,
ACTIVE,
ENDED,
BURNING
}
FinalAuctionStatus public finalAuctionStatus;
// State Transitions:
// (1) INACTIVE on deploy
// (2) ACTIVE on initiateMerger() and voteForMerger(), ASSETSTRANSFERRED on voteForMerger()
// (3) MERGED or POSTMERGERLOCKED on finalizeMerger()
enum MergerStatus {
INACTIVE,
ACTIVE,
ASSETSTRANSFERRED,
MERGED,
POSTMERGERLOCKED
}
MergerStatus public mergerStatus;
// State Transitions:
// (1) INACTIVE or INITIALIZED on deploy
// (2) ACTIVE on voteForDemerger()
// (4) ASSETSTRANSFERRED on DemergeAssets()
// (4) DEMERGED on finalizeDemerger()
enum DemergerStatus {
INACTIVE,
ACTIVE,
INITIALIZED,
ASSETSTRANSFERRED,
DEMERGED
}
DemergerStatus public demergerStatus;
// State Transitions:
// (1) INACTIVE on deploy
// (2) FUNDING on startAavegotchiFunding()
// (3) CLAIMED on claimAavegotchi()
// (4) COMPLETED, FRACTIONALIZED and FAILED on finalizeAavegotchi()
enum PortalFundingStatus {
INACTIVE,
FUNDING,
CLAIMED,
COMPLETED,
FRACTIONALIZED,
FAILED
}
PortalFundingStatus public portalStatus;
// ============ Public Constant ============
// version of the FrAactionHub smart contract
uint256 public constant contractVersion = 1;
// ============ Internal Constants ============
// tokens are minted at a rate of 1 GHST : 100 tokens
uint16 internal constant TOKEN_SCALE = 100;
// max integer in hexadecimal format
uint256 internal constant MAX_INT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
// ============ Internal Mutable Storage ============
// previous FrAactionHub token balance of the receiver
uint256 internal beforeTransferToBalance;
// stake amount to be decreased in GHST to be burnt
uint256 internal decreasedGhst;
// stake amount to be decreased
uint256 internal decreasedStake;
// last index of the skill points set array of votedSkill mapping
uint256 internal skillIndex;
// current number of times the changeFraactionType() function reached the minimum quorum and voted
uint256 internal typeNumber;
// current number of times the updateAuctionLength() function reached the minimum quorum and voted
uint256 internal lengthNumber;
// current number of times the updatePlayerFee() function reached the minimum quorum and voted
uint256 internal feeNumber;
// current number of times the voteForPlayer() function reached the minimum quorum and voted
uint256 internal playerNumber;
// number of iterations currently done in order to run through the whole ownerAddress array
uint256 internal splitCounter;
// number of iterations necessary in order to run through the whole ownerAddress array
uint256 internal multiple;
// number of this item type owned by the FrAactionHub before the purchase
uint256 internal initialNumberOfItems;
// number of the new funding round
uint256 internal fundingNumber;
// 0 = no split ongoing, 1 = split going on for the realms transfer, 2 = same for the NFTs transfer, 3 = same for the items transfer, 4 = same for owner addresses transfer
uint256 internal split;
// voter's address => current votes submitted for the FrAactionHub type change
mapping(address => uint256) internal currentTypeBalance;
// voter's address => current auction length voted by the owner
mapping(address => uint256) internal currentLengthVote;
// voter's address => current votes submitted for the auction length update
mapping(address => uint256) internal currentLengthBalance;
// voter's address => current player's fee voted by the owner
mapping(address => uint256) internal currentFeeVote;
// voter's address => current votes submitted for the player's fee update
mapping(address => uint256) internal currentFeeBalance;
// voter's address => current player voted by the owner
mapping(address => uint256) internal currentPlayerVote;
// voter's address => current votes submitted for the player appointment
mapping(address => uint256) internal currentPlayerBalance;
// voter's address => typeNumber of the last time the owner voted
mapping(address => uint256) internal typeCurrentNumber;
// voter's address => feeNumber of the last time the owner voted
mapping(address => uint256) internal feeCurrentNumber;
// voter's address => lengthNumber of the last time the owner voted
mapping(address => uint256) internal lengthCurrentNumber;
// voter's address => current number of times the voteForPlayer() function reached the minimum quorum and voted
mapping(address => uint256) internal playerCurrentNumber;
// mergerTarget address => current number of times the voteForMerger() function reached the minimum quorum and voted
mapping(address => uint256) internal mergerNumber;
// contributor address => current number of times the contributor paid the gas fees on behalf of all the FrAactionHub owners
mapping(address => uint256) internal feesContributor;
// contributor => Aavegotchi funding round number
mapping(address => uint256[]) internal fundingContributor;
// contributor => tokenId(s) concerned by a stake increase
mapping(address => uint256[]) internal stakeContributor;
// tokenId => current number of times the voteForName() function reached the minimum quorum and voted
mapping(uint256 => uint256) internal nameNumber;
// tokenId => current number of times the voteForSkills() function reached the minimum quorum and voted
mapping(uint256 => uint256) internal skillNumber;
// tokenId => current number of times the voteForDestruction() function reached the minimum quorum and voted
mapping(uint256 => uint256) internal destroyNumber;
// portal Id => portal funding round number
mapping(uint256 => uint256) internal portalFundingNumber;
// contributor => last funding index iterated during the last newClaim() call
mapping(uint256 => uint256) internal lastFundingContributorIndex;
// contributor => last portal index iterated during the last newClaim() call
mapping(uint256 => uint256) internal lastPortalContributorIndex;
// tokenId => each portal option already voted by at least one owner
mapping(uint256 => uint256[]) internal votedAavegotchi;
// portal Id => Aavegotchi funding round number
mapping(uint256 => uint256[]) internal contributorPortalFunding;
// tokenId => each skill points set already voted by at least one owner
mapping(uint256 => uint256[4][]) internal votedSkill;
// tokenId => each name already voted by at least one owner
mapping(uint256 => string[]) internal votedName;
// tokenId => true if new funding round is successful
mapping(uint256 => bool) internal fundingResult;
// portal Id => funding round number => true if success of the Aavegotchi portal funding round
mapping(uint256 => mapping(uint256 => bool) internal portalFundingResult;
// voter's address => tokenId => current Aavegotchi option voted by the owner
mapping(address => mapping(uint256 => uint256)) internal currentAavegotchiVote;
// voter's address => tokenId => current votes submitted by the owner for the Aavegotchi appointment
mapping(address => mapping(uint256 => uint256)) internal currentAavegotchiBalance;
// voter's address => tokenId => current Aavegotchi skill points set voted by the owner
mapping(address => mapping(uint256 => uint256)) internal currentSkillVote;
// voter's address => tokenId => current votes submitted by the owner for the Aavegotchi skill points
mapping(address => mapping(uint256 => uint256)) internal currentSkillBalance;
// voter's address => tokenId => current Aavegotchi name voted by the owner
mapping(address => mapping(uint256 => string)) internal currentNameVote;
// voter's address => tokenId => current votes submitted by the owner for the Aavegotchi name appointment
mapping(address => mapping(uint256 => uint256)) internal currentNameBalance;
// voter's address => tokenId => current votes from the contributor for the Aavegotchi destruction
mapping(address => mapping(uint256 => uint256)) internal currentDestroyBalance;
// voter's address => tokenId => nameNumber of the last time the owner voted
mapping(address => mapping(uint256 => uint256)) internal nameCurrentNumber;
// voter's address => tokenId => skillNumber of the last time the owner voted
mapping(address => mapping(uint256 => uint256)) internal skillCurrentNumber;
// voter's address => tokenId => destroyNumber of the last time the owner voted
mapping(address => mapping(uint256 => uint256)) internal destroyCurrentNumber;
// contributor => tokenId => total amount contributed to the funding round
mapping(address => mapping(uint256 => uint256)) internal ownerContributedToFunding;
// voter's address => mergerTarget address => mergerNumber of the last time the owner voted
mapping(address => mapping(address => uint256)) internal mergerCurrentNumber;
// contributor => Aavegotchi funding round portals
mapping(address => uint256[]) internal portalContributor;
// contributor => tokenId => each collateral stake contribution for the considered Aavegotchi
mapping(address => mapping(uint256 => stakeContribution[])) internal ownerStakeContribution;
// contributor => portal Id => portal funding round => contributed collateral
mapping(address => mapping(uint256 => mapping(uint256 => uint256))) internal ownerContributedCollateral;
// contributor => portal Id => portal funding round => contributed collateral type
mapping(address => mapping(uint256 => mapping(uint256 => uint256))) internal ownerCollateralType;
// contributor => portal Id => portal funding round => contributed ghst
mapping(address => mapping(uint256 => mapping(uint256 => uint256))) internal ownerContributedToAavegotchiFunding;
// ============ Public Not-Mutated Storage ============
// ERC-20 name for fractional tokens
string public name;
// ERC-20 symbol for fractional tokens
string public symbol;
// Address of the Aavegotchi Diamond contract
address public constant diamondContract;
// Address of the GHST contract
address public constant ghstContract;
// Address of the staking contract
address public constant stakingContract;
// Address of the REALMs contract
address public constant realmsContract;
// Address of the Raffles contract
address public constant rafflesContract;
// Address of the wrapped MATIC contract
address public constant wrappedMaticContract;
// Address of the FrAaction Gangs settings Contract
address public constant settingsContract = ;
// address of the parent FrAactionHub
address public demergeFrom;
// ============ Public Mutable Storage ============
// the governance contract which gets paid in ETH
address public settingsContract;
// FrAactionDAOMultisig address
address public fraactionDaoMultisig;
// FrAactionHall address
address public fraactionHall;
// target of the initial bid
address public fraactionHubTarget;
// contributor for the current staking decrease or increase;
address public stakingContributor;
// the current user winning the token auction
address public winning;
// the Player of the fractionalized Aavegotchi
address public player;
// addresses of all the FrAactionHub owners
address[] public ownersAddress;
// fee rewarded to the Player
uint256 public playerFee;
// the last timestamp when fees were claimed
uint256 public lastClaimed;
// the number of ownership tokens voting on the reserve price at any given time
uint256 public votingTokens;
// total GHST deposited by all contributors
uint256 public totalContributedToFraactionHub;
// Price in wei of the listed item targetted by the current funding round
uint256 public priceInWei;
// quantity of items to be acquired from the baazaar by the new funding round
uint256 public quantity;
// total votes for the election of the player
uint256 public votesTotalPlayer;
// total votes for the player fee update
uint256 public votesTotalFee;
// total votes for the auction length update
uint256 public votesTotalLength;
// total votes for the FrAactionHub type update
uint256 public votesTotalType;
// total GHST deposited by all contributors for the funding round
uint256 public totalContributedToFunding;
// last initial bid price submitted to the target FrAactionHub
uint256 public submittedBid;
// Number of assets acquired by the FrAactionHub
uint256 public numberOfAssets;
// Id of the portal to be claimed by the FrAactionHub
uint256 public portalTarget;
// option number of the appointed Aavegotchi to be claimed by the FrAactionHub
uint256 public portalOption;
// the unix timestamp end time of the token auction
uint256 public auctionEnd;
// the length of auctions
uint256 public auctionLength;
// reservePrice * votingTokens
uint256 public reserveTotal;
// the current price of the token during the final auction
uint256 public livePrice;
// listingId of the current funding round target
uint256 public listingId;
// Number of the FrAactionHub owners
uint256 public numberOfOwners;
// new funding round initial time
uint256 public fundingTime;
// Aavegotchi funding round initial time
uint256 public aavegotchiFundingTime;
// maximum collateral contribution allowed for the Aavegotchi funding
uint256 public maxContribution;
// collateral type of the appointed Aavegotchi
uint256 public collateralType;
// current collateral balance of the targeted Aavegotchi for the stake increase or decrease
uint256 public collateralBalance;
// current tokenId of the targeted Aavegotchi for the stake increase or decrease
uint256 public stakingTarget;
// array of the proposed auction lengths for the vote
uint256[] public votedLength;
// array of the proposed player fees for the vote
uint256[] public votedFee;
// 0 is for Delegated FrAactionHub, 1 for Collective FrAactionHub
bool public gameType;
// true if the new funding round is targetting an NFT
bool public isNft;
// true if there is currently at least one destroyed Aavegotchi tokens to be claimed
bool public destroyed;
// true if all the funding rounds contributors claimed their tokens
bool public allClaimed;
// true if the first FrAactionHub funding round is currently active
bool public firstRound;
// true if the FrAactionHub successfully fractionalized its first NFT or item
bool public initialized;
// proposed auction length => collected votes in favor of that auction length
mapping (uint256 => uint256) public votesLength;
// proposed player's fee => collected votes in favor of that player's fee
mapping (uint256 => uint256) public votesFee;
// portal tokenId => appointed Aavegotchi
mapping (uint256 => uint256) public aavegotchi;
// tokenId => total votes for the Aavegotchi destruction
mapping (uint256 => uint256) public votesTotalDestroy;
// tokenId => total votes for the Aavegotchi
mapping (uint256 => uint256) public votesTotalAavegotchi;
// tokenId => total votes for the Aavegotchi name
mapping (uint256 => uint256) public votesTotalName;
// tokenId => total votes for the Aavegotchi skill points allocation
mapping (uint256 => uint256) public votesTotalSkill;
// tokenId => total votes collected to open this closed portal
mapping(uint256 => uint256) public votesTotalOpen;
// tokenId => index of asset
mapping(uint256 => uint256) public tokenIdToAssetIndex;
// portal Id => total contributed for the Aavegotchi portal funding
mapping(uint256 => uint256) public totalContributedToAavegotchiFunding;
// tokenId => winning Aavegotchi name
mapping (uint256 => string) public name;
// FrAactionHub owner => votes he collected to become the appointed Player
mapping(address => uint256) public votesPlayer;
// contributor => total amount contributed to the FrAactionHub
mapping(address => uint256) public ownerTotalContributed;
// contributor => array of Contributions
mapping(address => Contribution[]) public contributions;
// FrAactionHub owner => his desired token price
mapping(address => uint256) public userPrices;
// FrAactionHub owner => return True if owner already voted for the appointed player
mapping(address => bool) public votersPlayer;
// FrAactionHub owner => return True if owner already voted for the new Player's fee
mapping(address => bool) public votersFee;
// FrAactionHub owner => return True if owner already voted for the new auction length
mapping(address => bool) public votersLength;
// FrAactionHub owner => return True if owner already voted for the new FrAactionHub type
mapping(address => bool) public votersType;
// FrAactionHub owner => return True if owner already voted for the Aavegotchi
mapping(address => bool) public votersAavegotchi;
// contributor => true if the contributor already claimed its tokens from the funding round
mapping(address => bool) public claimed;
// tokenId => true if there is currently a vote for allocating skill points
mapping(uint256 => bool) public skillVoting;
// owner => tokenId => true if alredy voted, false if not
mapping(address => mapping(uint256 => bool)) public votersOpen;
// contributor => tokenId => true if contributor already voted for that Aavegotchi destruction
mapping(address => mapping(uint256 => bool)) public votersDestroy;
// contributor => tokenId => true if contributor already voted for that Aavegotchi
mapping(address => mapping(uint256 => bool)) public votersAavegotchi;
// owner => tokenId => current votes for opening the portal
mapping(address => mapping(uint256 => uint256)) public currentOpenBalance;
// contributor => tokenId => total staking contribution for the considered Aavegotchi
mapping(address => mapping(uint256 => uint256)) public ownerTotalStakeAmount;
// tokenId => portal option => current votes for this portal option
mapping(uint256 => mapping(uint256 => uint256)) public votesAavegotchi;
// tokenId => skill points set => current votes for this skill points set
mapping(uint256 => mapping(uint256 => uint256)) public votesSkill;
// tokenId => Aavegotchi name => current votes for this name
mapping(uint256 => mapping(string => uint256)) public votesName;
// Array of Assets acquired by the FrAactionHub
Asset[] public assets;
// ============ Structs ============
struct Contribution {
uint256 amount;
uint256 previousTotalContributedToFraactionHub;
}
// ============ EVENTS ============
// an event emitted when a user updates their price
event PriceUpdate(
address indexed user,
uint price
);
// an event emitted when an auction starts
event Start(
address indexed buyer,
uint price
);
// an event emitted when a bid is made
event Bid(
ddress indexed buyer,
uint price
);
// an event emitted when an auction is won
event Won(
address indexed buyer,
uint price
);
// an event emitted when someone cashes in ERC20 tokens for ETH from an ERC721 token sale
event Cash(
address indexed owner,
uint256 shares
);
// an event emitted when the assets merger is finalized
event AssetsMerged(address indexed _mergerTarget);
// an event emitted when the merger is finalized
event MergerFinalized(address indexed _mergerTarget);
// an event emitted when the demerger is done
event Demerged(address indexed proxyAddress, string name, string symbol);
// an event emitted when the Player is appointed or changed
event AppointedPlayer(address indexed appointedPlayer);
// an event emitted when the auction length is changed
event UpdateAuctionLength(uint256 indexed newLength);
// an event emitted when the Player fee is changed
event UpdatePlayerFee(uint256 indexed newFee);
// an event emitted when the FrAaction type is changed
event UpdateFraactionType(string indexed newGameType);
// an event emitted when somebody redeemed all the FrAactionHub tokens
event Redeem(address indexed redeemer);
// an event emitted when an Aavegotchi is appointed to be summoned
event AppointedAavegotchi(uint256 indexed portalTokenId, uint256 appointedAavegotchiOption);
// an event emitted when a portal is open
event OpenPortal(uint256 indexed portalId);
// an event emitted when an Aavegotchi is destroyed
event Destroy(uint256 indexed tokenId);
// an event emitted when an Aavegotchi name is chosen
event Named(uint256 indexed tokenId, string name);
// an event emitted when an Aavegotchi skill points set is submitted
event SkilledUp(uint256 indexed tokenId, uint256 tokenId);
// an event emitted when wearables are equipped on an Aavegotchi
event Equipped(uint256 indexed tokenId, uint16[16] wearables);
// an event emitted when consumables are used on one or several Aavegotchis
event ConsumablesUsed(uint256 indexed tokenId, uint256[] itemIds, uint256[] quantities);
function initializeVault(uint256 _supply, uint256 _listPrice, string memory _name, string memory _symbol) internal initializer {
// initialize inherited contracts
__ERC20_init(_name, _symbol);
reserveTotal = _listPrice * _supply;
lastClaimed = block.timestamp;
votingTokens = _listPrice == 0 ? 0 : _supply;
_mint(address(this), _supply);
userPrices[address(this)] = _listPrice;
initialized = true;
}
// ============ VIEW FUNCTIONS ============
function getOwners() public view returns (address[] memory) {
return ownersAddress;
}
/// @notice provide the current reserve price of the FrAactionHub
function reservePrice() public view returns(uint256) {
return votingTokens == 0 ? 0 : reserveTotal / votingTokens;
}
/// @notice provide the current reserve price of the FrAactionHub
function fundingPrice() public view returns(uint256) {
return votingTokens == 0 ? 0 : fundingTotal / votingTokens;
}
/// @notice inform if the bid is open (return true) or not (return false)
function openForBidOrMerger() public view returns(bool) {
return votingTokens * 1000 >= ISettings(settings).minVotePercentage() * totalSupply() ? true : false;
}
/// @notice inform if the bid is open (return true) or not (return false)
function activeBid() public view returns(bool) {
return finalAuctionStatus != FinalAuctionStatus.INACTIVE ? true : false;
}
/// @notice provide minimum amount to bid during the auction
function minBid() public view returns(uint256) {
uint256 increase = ISettings(settingsContract).minBidIncrease() + 1000;
return livePrice * increase / 1000;
}
// ========= GOV FUNCTIONS =========
/// @notice allow governance to boot a bad actor Player
/// @param _Player the new Player
function kickPlayer(address _player) external {
require(
msg.sender == ISettings(settingsContract).owner(),
"kick: not gov"
);
player = _player;
}
/// @notice allow governance to remove bad reserve prices
function removeReserve(address _user) external {
require(
msg.sender == ISettings(settingsContract).owner(),
"remove: not gov"
);
require(
auctionStatus == AuctionsStatus.INACTIVE,
"remove: auction live cannot update price"
);
uint256 old = userPrices[_user];
require(
0 != old,
"remove: not an update"
);
uint256 weight = balanceOf(_user);
votingTokens -= weight;
reserveTotal -= weight * old;
userPrices[_user] = 0;
emit PriceUpdate(_user, 0);
}
// ============ SETTINGS & FEES FUNCTIONS ============
/// @notice allow the FrAactionHub owners to change the FrAactionHub type
function changeFraactionType() external {
require(
initialized == true,
"updateFraactionType: FrAactionHub not initialized yet"
);
require(
balanceOf(msg.sender) > 0,
"updateFraactionType: user not an owner of the FrAactionHub"
);
require(
gangAddress != address(0),
"updateFraactionType: cannot change the Collective type if the FraactionHub is part of a gang"
);
if (typeNumber != typeCurrentNumber[msg.sender]) {
votersType[msg.sender] = 0;
currentTypeBalance[msg.sender] = 0;
}
if (votersType[msg.sender] == true) {
votesTotalType -= currentTypeBalance[msg.sender];
} else {
votersType[msg.sender] = true;
}
votesTotalType += balanceOf(msg.sender);
currentTypeBalance[msg.sender] = balanceOf(msg.sender);
if (typeNumber != typeCurrentNumber[msg.sender]) typeCurrentNumber[msg.sender] = typeNumber;
if (votesTotalType * 1000 >= ISettings(settingsContract).minTypeVotePercentage() * totalSupply()) {
// 0 is for Delegated FrAactionHub, 1 for Collective FrAactionHub
if (gameType == 0) gameType = 1;
if (gameType == 1) gameType = 0;
emit UpdateFraactionType(gameType);
typeNumber++;
votesTotalType = 0;
}
}
/// @notice allow the FrAactionHub owners to update the auction length
/// @param _length the new maximum length of the auction
function updateAuctionLength(uint256 _length) external {
require(
initialized == true,
"updateAuctionLength: FrAactionHub not initialized yet"
);
require(
balanceOf(msg.sender) > 0,
"updateAuctionLength: user not an owner of the FrAactionHub"
);
require(
_length >= ISettings(settingsContract).minAuctionLength() && _length <= ISettings(settings).maxAuctionLength(),
"updateAuctionLength: invalid auction length"
);
if (lengthNumber != lengthCurrentNumber[msg.sender]) {
votersLength[msg.sender] = 0;
currentLengthVote[msg.sender] = 0;
currentLengthBalance[msg.sender] = 0;
}
if (votersLength[msg.sender] == true) {
votesLength[currentLengthVote[msg.sender]] -= currentLengthBalance[msg.sender];
votesTotalLength -= currentLengthBalance[msg.sender];
} else {
votersLength[msg.sender] = true;
}
if (votesLength[_length] == 0) votedLength.push(_length);
votesLength[_length] += balanceOf(msg.sender);
votesTotalLength += balanceOf(msg.sender);
currentLengthVote[msg.sender] = _length;
currentLengthBalance[msg.sender] = balanceOf(msg.sender);
if (lengthNumber != lengthCurrentNumber[msg.sender]) lengthCurrentNumber[msg.sender] = lengthNumber;
uint256 winner;
uint256 result;
if (votesTotalLength * 1000 >= ISettings(settingsContract).minLengthVotePercentage() * totalSupply()) {
for (uint i = 0; i < votedLength.length; i++) {
if (votesLength[votedLength[i]] > result) {
result = votesLength[votedLength[i]];
winner = votedLength[i];
}
votesLength[votedLength[i]] = 0;
}
auctionLength = winner;
delete votedLength;
emit UpdateAuctionLength(auctionLength);
lengthNumber++;
votesTotalLength = 0;
}
}
/// @notice allow the FrAactionHub owners to change the player fee
/// @param _fee the new fee
function updatePlayerFee(uint256 _playerFee) external {
require(
gameType == 0,
"updatePlayerFee: this FrAactionHub was set as Collective by its creator"
);
require(
_playerFee <= ISettings(settingsContract).maxPlayerFee(),
"updatePlayerFee: cannot increase fee this high"
);
require(
initialized == true,
"updatePlayerFee: FrAactionHub not initialized yet"
);
require(
balanceOf(msg.sender) > 0,
"updatePlayerFee: user not an owner of the FrAactionHub"
);
if (feeNumber != feeCurrentNumber[msg.sender]) {
votersFee[msg.sender] = 0;
currentFeeVote[msg.sender] = 0;
currentFeeBalance[msg.sender] = 0;
}
if (votersFee[msg.sender] == true) {
votesFee[currentFeeVote[msg.sender]] -= currentFeeBalance[msg.sender];
votesTotalFee -= currentFeeBalance[msg.sender];
} else {
votersFee[msg.sender] = true;
}
if (votesFee[_playerFee] == 0) votedFee.push(_playerFee);
votesFee[_playerFee] += balanceOf(msg.sender);
votesTotalFee += balanceOf(msg.sender);
currentFeeVote[msg.sender] = _playerFee;
currentFeeBalance[msg.sender] = balanceOf(msg.sender);
if (feeNumber != feeCurrentNumber[msg.sender]) feeCurrentNumber[msg.sender] = feeNumber;
if (votesTotalFee * 1000 >= ISettings(settingsContract).minPlayerFeeVotePercentage() * totalSupply()) {
for (uint i = 0; i < votedFee.length; i++) {
if (votesFee[votedFee[i]] > result) {
result = votesFee[votedFee[i]];
winner = votedFee[i];
}
votesFee[votedFee[i]] = 0;
}
playerFee = winner;
delete votedFee;
emit UpdatePlayerFee(playerFee);
feeNumber++;
votesTotalFee = 0;
}
}
// ========= CORE FUNCTIONS ============
function voteForTransfer(
uint256[] calldata _nftsId,
uint256[] calldata _extNftsId,
uint256[] calldata _ext1155Id,
uint256[] calldata _realmsId,
uint256[] calldata _itemsId,
uint256[] calldata _itemsQuantity,
uint256[] calldata _extErc20Value,
uint256[] calldata _ext1155Quantity,
uint256[7] calldata _ticketsQuantity,
address[] calldata _extErc20Address,
address[] calldata _extNftsAddress,
address[] calldata _ext1155Address,
uint256 _idToVoteFor,
address _transferTo
) external nonReentrant {
require(
demergerStatus == DemergerStatus.INACTIVE,
"voteForTransfer: transfer already active"
);
require(
balanceOf(msg.sender) > 0,
"voteForTransfer: caller not an owner of the FrAactionHub"
);
require(
_itemsId.length == _itemsQuantity.length &&
_extNftsId.length == _extNftsAddress.length &&
_ext1155Id.length == _ext1155Address.length &&
_ext1155Address.length == _ext1155Quantity.length &&,
"voteForTransfer: input arrays lengths are not matching"
);
require(
_nftsId.length +
_realmsId.length +
_itemsId.length +
_itemsQuantity.length +
_ticketsQuantity.length +
_extNftsId.length +
_extNftsAddress.length +
_ext1155Id.length +
_ext1155Quantity.length +
_ext1155Address.length +
=< ISettings(settingsContract).MaxTransferLimit(),
"voteForTransfer: cannot transfer more than the GovSettings allowed limit"
);
if (_nftsId.length > 0 ||
_realmsId.length > 0 ||
_itemsId.length > 0 ||
_ticketsId.length > 0 ||
_extNftsId.length > 0 ||
_ext1155Id.length > 0
) {
require(
_idToVoteFor == votedIndex,
"voteForTransfer: user submitting a new demerger has to vote for it"
);
require(
_transferTo != address(0),
"voteForTransfer: address to transfer to cannot be zero"
);
ownershipCheck(
_nftsId,
_realmsId,
_itemsId,
_itemsQuantity,
_ticketsQuantity,
true
);
ownershipCheckExt(
_extNftsId,
_ext1155Id,
_extErc20Value,
_ext1155Quantity,
_extErc20Address,
_extNftsAddress,
_ext1155Address,
true
);
votedIndex++;
transferTo[_idToVoteFor] = _transferTo;
}
if (votersTransfer[msg.sender][_idToVoteFor] == true) {
if (balanceOf(msg.sender) != currentTransferBalance[msg.sender][_idToVoteFor])
votesTotalTransfer[_idToVoteFor] -= currentTransferBalance[msg.sender][_idToVoteFor];
} else {
votersTransfer[msg.sender][_idToVoteFor] = true;
}
if (balanceOf(msg.sender) != currentTransferBalance[msg.sender][_idToVoteFor]) {
votesTotalTransfer[_idToVoteFor] += balanceOf(msg.sender);
currentTransferBalance[msg.sender][_idToVoteFor] = balanceOf(msg.sender);
}
if (votesTotalTransfer[_idToVoteFor] * 1000 >= ISettings(settingsContract).minTransferVotePercentage() * totalSupply()) {
if (demergerStatus != DemergerStatus.ACTIVE) {
ownershipCheck(
_nftsId,
_realmsId,
_itemsId,
_itemsQuantity,
_ticketsQuantity,
true
);
ownershipCheckExt(
_extNftsId,
_ext1155Id,
_extErc20Value,
_ext1155Quantity,
_extErc20Address,
_extNftsAddress,
_ext1155Address,
true
);
demergerStatus = DemergerStatus.ACTIVE;
votedIndex = _idToVoteFor;
target = transferTo[_idToVoteFor];
emit TransferActive(target);
}
if (!realmsTransferred || split = 1) {
transferRealms();
if (split == 0) realmsTransferred = true;
} else if (!nftsTransferred || split = 2) {
transferNfts();
if (split == 0) nftsTransferred = true;
} else if (!itemsTransferred || split = 3) {
transferItems();
if (split == 0) itemsTransferred = true;
} else if (!extNftsTransferred || split = 4) {
transferExternalNfts();
if (split == 0) extNftsTransferred = true;
} else if (!ext1155Transferred || split = 5) {
transferExternal1155();
if (split == 0) ext1155Transferred = true;
} else if (!extErc20Transferred || split = 6) {
transferExternalErc20();
if (split == 0) extErc20Transferred = true;
} else {
demergerStatus = DemergerStatus.INACTIVE;
realmsTransferred = false;
nftsTransferred = false;
itemsTransferred = false;
extNftsTransferred = false;
ext1155Transferred = false;
extErc20Transferred = false;
DemergerAssetsTransferred(address(this));
}
claimReward(msg.sender);
}
}
function confirmFinalizedMerger() external {
require(
msg.sender == target,
"confirmFinalizedMerger: sender is not the merger target"
);
require(
mergerStatus == MergerStatus.ACTIVE,
"confirmFinalizedMerger: merger not active"
);
delete initiatedMergerFrom[target];
delete votesTotalMerger[target];
delete targetReserveTotal[target];
delete proposedMergerTo[target];
delete proposedValuation;
delete proposedValuationFrom;
if (!takeover) {
if (erc20Tokens.length + nfts.length + erc1155Tokens.length > maxExtTokensLength) {
mergerStatus = MergerStatus.DELETINGTOKENS;
} else {
delete erc20Tokens;
delete nfts;
delete erc1155Tokens;
mergerStatus = MergerStatus.ENDED;
}
}
}
function initiateMergerFrom(uint256 _proposedValuation, bool _proposedTakeover) external {
require(
ISettings(settingsContract).fraactionHubRegistry(msg.sender) > 0,
"initiateMergerFrom: not a registered FrAactionHub contract"
);
require(
mergerStatus == MergerStatus.INACTIVE,
"initiateMergerFrom: caller not an owner of the FrAactionHub"
);
initiatedMergerFrom[msg.sender] = true;
proposedValuationFrom[msg.sender] = _proposedValuation;
proposedTakeoverFrom[msg.sender] = _proposedTakeover;
timeMerger[msg.sender] = block.timestamp;
endMerger[msg.sender] = timeMerger[msg.sender] + ISettings(settingsContract).minMergerTime();
emit MergerProposed(msg.sender, _proposedValuation, _proposedTakeover);
}
function confirmMerger() external {
require(
msg.sender == target,
"confirmMerger: caller not the merger target"
);
merging = true;
emit confirmedMerger(msg.sender);
}
function confirmAssetsTransferred() external {
require(
msg.sender == target,
"confirmAssetsTransferred caller not the merger target"
);
mergerStatus = MergerStatus.ASSETSTRANSFERRED;
emit MergerAssetsTransferred(msg.sender);
}
function initiateMergerTo(uint256 _proposedValuation, bool _proposedTakeover) external {
require(
ISettings(settingsContract).fraactionHubRegistry(msg.sender) > 0,
"initiateMergerTo: not a registered FrAactionHub contract"
);
require(
mergerStatus == MergerStatus.INACTIVE,
"initiateMergerTo: caller not an owner of the FrAactionHub"
);
proposedMergerFrom[msg.sender] = true;
proposedValuationFrom[msg.sender] = _proposedValuation;
proposedTakeoverFrom[msg.sender] = _proposedTakeover;
timeMerger[msg.sender] = block.timestamp;
endMerger[msg.sender] = timeMerger[msg.sender] + ISettings(settingsContract).minMergerTime();
emit MergerProposedTo(msg.sender, _proposedValuation, _proposedTakeover);
}
function voteForMerger(
bool _proposeMergerTo,
bool _proposeTakeover,
uint256 _proposeValuation,
address _mergerTarget
) external nonReentrant {
require(
fundingStatus == FundingStatus.INACTIVE,
"voteForMerger: FrAactionHub not fractionalized yet"
);
require(
ISettings(settingsContract).fraactionHubRegistry(_mergerTarget) > 0,
"voteForMerger: not a registered FrAactionHub contract"
);
require(
balanceOf(msg.sender) > 0 ||
FraactionInterface(target).balanceOf(msg.sender) > 0,
"voteForMerger: user not an owner of the FrAactionHub"
);
require(
_extNftsId.length == _extNftsAddress.length &&
_extErc20Address.length == _extErc20Value.length &&
_ext1155Id.length == _ext1155Quantity.length &&
_ext1155Quantity.length == _ext1155Address.length,
"voteForMerger: each token ID or value needs a corresponding token address"
);
if (merging == false) {
if (timeMerger[_mergerTarget] > mergerEnd[_mergerTarget]) {
timeMerger[_mergerTarget] = 0;
mergerEnd[_mergerTarget] = 0;
if (initiatedMergerFrom[_mergerTarget] && mergerStatus == MergerStatus.INACTIVE) {
delete initiatiedMergerFrom[_mergerTarget];
} else if (proposedMergerTo[_mergerTarget] && mergerStatus == MergerStatus.ACTIVE) {
mergerStatus = MergerStatus.INACTIVE;
delete proposedMergerTo[_mergerTarget];
} else if (proposedMergerFrom[_mergerTarget] && mergerStatus == MergerStatus.INACTIVE) {
delete proposedMergerFrom[_mergerTarget];
} else {
delete initiatedMergerTo[_mergerTarget];
mergerStatus = MergerStatus.INACTIVE;
}
delete targetReserveTotal[_mergerTarget];
delete votesTotalMerger[_mergerTarget];
return;
}
if (_proposeMergerTo) proposedMergerTo[_mergerTarget] = true;
if (targetReserveTotal[_mergerTarget] == 0) {
require(
FraactionInterface(_mergerTarget).openForBidOrMerger(),
"voteForMerger: FrAactionHub not open for Merger or Bid"
);
if (!proposedMergerFrom[_mergetTarget] && !initiatedMergerFrom[_mergetTarget]) proposedTakeover[_mergerTarget] = _proposeTakeover;
if (_proposeValuation == 0 && !proposedValuationFrom[_mergerTarget]
|| proposedValuationFrom[_mergerTarget]
) {
targetReserveTotal[_mergerTarget] = FraactionInterface(_mergerTarget).reserveTotal();
} else {
targetReserveTotal[_mergerTarget] = _proposeValuation;
proposedValuation[_mergerTarget] = true;
}
bool checkType = FraactionInterface(_mergerTarget).checkExitTokenType();
if (exitInGhst == checkType) sameReserveCurrency[_mergerTarget] = checkType;
}
if (votersMerger[msg.sender][_mergerTarget] == true) {
if (balanceOf(msg.sender) != currentMergerBalance[msg.sender][_mergerTarget])
votesTotalMerger[_mergerTarget] -= currentMergerBalance[msg.sender][_mergerTarget];
} else {
votersMerger[msg.sender][_mergerTarget] = true;
}
if (balanceOf(msg.sender) != currentMergerBalance[msg.sender][_mergerTarget]) {
votesTotalMerger[_mergerTarget] += balanceOf(msg.sender);
currentMergerBalance[msg.sender][_mergerTarget] = balanceOf(msg.sender);
}
}
if (votesTotalMerger[_mergerTarget] * 1000 >= ISettings(settingsContract).minMergerVotePercentage() * totalSupply()) {
if (initiatedMergerFrom[_mergerTarget] == true) {
if (!proposedMergerTo[_mergerTarget] && mergerStatus == MergerStatus.INACTIVE) {
target = _mergerTarget;
mergerStatus = MergerStatus.ACTIVE;
merging = true;
FraactionInterface(target).confirmMerger();
emit MergerInitiated(_mergerTarget);
}
uint256[] memory realmsId = DiamondInterface(realmsContract).tokenIdsOfOwner(address(this));
uint32[] memory nftsId = DiamondInterface(diamondContract).tokenIdsOfOwner(address(this));
ItemIdIO[] memory itemsDiamond = DiamondInterface(diamondContract).itemBalances(address(this));
uint256[] memory itemsStaking = DiamondInterface(stakingContract).balanceOfAll(address(this));
bool checkTickets;
for (uint i = 0; i < itemsStaking.length; i++) {
if (itemsStaking[i] != 0) {
checkTickets = true;
break;
}
}
if (realmsId.length > 0 && split == 0 || split == 1) {
transferRealms();
} else if (nftsId.length > 0 && split == 0 || split == 2) {
transferNfts();
} else if (
itemsDiamond.length > 0 && split == 0 ||
split == 3 ||
checkTickets == true
)
{
transferItems();
} else if (!extNftsTransferred || split = 4) {
transferExternalNfts();
if (split == 0) extNftsTransferred = true;
} else if (!ext1155Transferred || split = 5) {
transferExternal1155();
if (split == 0) ext1155Transferred = true;
} else if (!extErc20Transferred || split = 6) {
transferExternalErc20();
if (split == 0) extErc20Transferred = true;
} else {
extNftsTransferred = false;
ext1155Transferred = false;
extErc20Transferred = false;
if (totalTreasuryInGhst > 0) ERC20lib.transferFrom(ghstContract, address(this), target, totalTreasuryInGhst);
if (totalTreasuryInMatic > 0) transferMaticOrWmatic(target, totalTreasuryInMatic);
totalTreasuryInGhst = 0;
totalTreasuryInMatic = 0;
uint256 bal = ERC20Upgradeable(ghstContract).balanceOf(address(this));
residualGhst = bal - currentBalanceInGhst;
residualMatic = address(this).balance - currentBalanceInMatic;
if (exitInGhst) {
redeemedCollateral[ghstContract].push(residualGhst);
if (collateralToRedeem[ghstContract] == 0) {
collateralToRedeem[ghstContract] = true;
collateralAvailable.push(ghstContract);
}
} else {
redeemedCollateral[thisContract].push(residualMatic);
if (collateralToRedeem[thisContract] == 0) {
collateralToRedeem[thisContract] = true;
collateralAvailable.push(thisContract);
}
}
mergerStatus == MergerStatus.ASSETSTRANSFERRED;
totalNumberExtAssets = nonTransferredAssets;
nonTransferredAssets = 0;
FraactionInterface(target).confirmAssetsTransferred();
emit MergerAssetsTransferred(address(this));
}
claimReward(msg.sender);
} else if (proposedMergerTo[_mergerTarget]) {
target = _mergerTarget;
mergerStatus = MergerStatus.ACTIVE;
timeMerger[target] = block.timestamp;
endMerger[target] = timeMerger[target] + ISettings(settingsContract).minMergerTime();
merging = true;
if (proposedValuation[target]) {
FraactionInterface(target).initiateMergerTo(targetReserveTotal[target], proposedTakeover[target]);
} else {
FraactionInterface(target).initiateMergerTo(, proposedTakeover[target]);
}
emit MergerInitiatedTo(target);
} else {
target = _mergerTarget;
mergerStatus = MergerStatus.ACTIVE;
uint256 takeover = proposedTakeover[target] ? true : proposedTakeoverFrom[target];
if (proposedValuation[target]) {
FraactionInterface(target).initiateMergerFrom(targetReserveTotal[target], takeover);
} else {
FraactionInterface(target).initiateMergerFrom(, takeover);
}
timeMerger[target] = block.timestamp;
endMerger[target] = timeMerger[target] + ISettings(settingsContract).minMergerTime();
delete votesTotalMerger[_mergerTarget];
emit MergerInitiated(target);
}
}
}
function finalizeMerger() external nonReentrant {
require(
mergerStatus == MergerStatus.ASSETSTRANSFERRED,
"finalizeMerger: items not transferred yet"
);
require(
balanceOf(msg.sender) > 0 ||
FraactionInterface(target).balanceOf(msg.sender) > 0,
"finalizeMerger: user not an owner of the FrAactionHub"
);
address[] memory ownersFrom = FraactionInterface(target).getOwners();
uint256 startIndex = 0;
uint256 endIndex = ownersFrom.length;
if (split == 0) {
maxOwnersArrayLength = ISettings(settingsContract).maxOwnersArrayLength();
uint256 agreedReserveTotal;
uint256 agreedReserveTotalFrom;
if (proposedValuationFrom[target]) {
agreedReserveTotalFrom = targetReserveTotal[target];
agreedReserveTotal = proposedValuationFrom[target];
} else {
agreedReserveTotalFrom = targetReserveTotal[target];
agreedReserveTotal = FraactionInterface(target).targetReserveTotal(address(this));
}
if (sameReserveCurrency[target]) {
newShareFrom = totalSupply() * agreedReserveTotalFrom / agreedReserveTotal;
} else {
if (exitInGhst) {
newShareFrom = totalSupply() * (agreedReserveTotalFrom * (ISettings(settingsContract).convertFundingPrice(1) / 10**8)) / agreedReserveTotal;
} else {
newShareFrom = totalSupply() * (agreedReserveTotalFrom * (ISettings(settingsContract).convertFundingPrice(0) / 10**8)) / agreedReserveTotal;
}
}
if (ownersFrom.length > maxOwnersArrayLength) {
if (ownersFrom.length % maxOwnersArrayLength > 0) {
multiple = ownersFrom.length / maxOwnersArrayLength + 1;
} else {
multiple = ownersFrom.length / maxOwnersArrayLength;
}
split = 7;
splitCounter++;
}
endIndex = maxOwnersArrayLength;
} else {
if (ownersFrom.length % maxOwnersArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxOwnersArrayLength + 1;
endIndex = ownersFrom.length;
} else {
startIndex = splitCounter * maxOwnersArrayLength + 1;
endIndex = (splitCounter + 1) * maxOwnersArrayLength;
}
splitCounter++;
}
bool existing;
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
merging = false;
totalTreasuryInGhst += FraactionInterface(target).totalTreasuryInGhst();
totalTreasuryInMatic += FraactionInterface(target).totalTreasuryInMatic();
FraactionInterface(target).confirmFinalizedMerger();
delete initiatedMergerTo[target];
delete proposedMergerFrom[target];
delete targetReserveTotal[target];
delete proposedTakeoverFrom;
delete proposedValuation;
delete proposedValuationFrom;
mergerStatus = MergerStatus.INACTIVE;
emit MergerFinalized(target);
}
if (endIndex > ownersFrom.length) endIndex = ownersFrom.length;
if (startIndex > ownersFrom.length) return;
uint256 tokenSupplyFrom = FraactionInterface(target).totalSupply();
for (uint i = startIndex; i < endIndex; i++) {
for (uint j = 0; j < ownersAddress.length; j++) {
if (ownersFrom[i] == ownersAddress[j]) {
existing = true;
}
}
if (existing == false) ownersAddress.push(ownersFrom[i]);
mint(
ownersFrom[i],
newShareFrom * FraactionInterface(target).balanceOf(ownersFrom[i]) / tokenSupplyFrom
);
}
claimReward(msg.sender);
}
function transferRealms() internal {
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedRealms[votedIndexRealms[votedIndex].length;
} else {
arrayLength = DiamondInterface(realmsContract).tokenIdsOfOwner(address(this)).length;
}
uint256[] memory realmsId = new uint256[](arrayLength);
if (demergerStatus == DemergerStatus.ACTIVE) {
realmsId = votedRealms[votedIndexRealms[votedIndex]];
} else {
realmsId = DiamondInterface(realmsContract).tokenIdsOfOwner(address(this));
}
uint256 startIndex;
uint256 endIndex = realmsId.length;
if (split == 0) {
maxRealmsArrayLength = ISettings(settingsContract).maxRealmsArrayLength();
if (realmsId.length > maxRealmsArrayLength) {
endIndex = maxRealmsArrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
if (realmsId.length % maxRealmsArrayLength > 0) {
multiple = realmsId.length / maxRealmsArrayLength + 1;
} else {
multiple = realmsId.length / maxRealmsArrayLength;
}
split = 1;
splitCounter++;
}
}
} else {
if (realmsId.length % maxRealmsArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxRealmsArrayLength + 1;
endIndex = realmsId.length;
} else {
startIndex = splitCounter * maxRealmsArrayLength + 1;
endIndex = (splitCounter + 1) * maxRealmsArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredRealms(transferTo);
}
if (_endIndex > realmsId.length) _endIndex = realmsId.length;
if (_startIndex > realmsId.length) return;
uint256[] memory batchIds = new uint256[](endIndex - startIndex + 1);
for (uint i = _startIndex; i < _endIndex; i++) {
batchIds[i] = realmsId[i];
}
RealmsInterface(realmsContract).safeBatchTransfer(address(this), target, batchIds, new bytes(0));
}
function transferNfts() internal {
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedNfts[votedIndexNfts[votedIndex].length;
} else {
arrayLength = DiamondInterface(diamondContract).tokenIdsOfOwner(address(this)).length;
}
uint256[] memory nftsIds = new uint256[](arrayLength);
if (demergerStatus == DemergerStatus.ACTIVE) {
nftIds = votedNfts[votedIndexNfts[votedIndex]];
} else {
nftIds = DiamondInterface(diamondContract).tokenIdsOfOwner(address(this));
}
uint256 startIndex;
uint256 endIndex = nftsIds.length;
if (split == 0) {
maxNftArrayLength = ISettings(settingsContract).maxNftArrayLength();
if (nftIds.length > maxNftArrayLength) {
endIndex = maxNftArrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
if (nftIds.length % maxNftArrayLength > 0) {
multiple = nftIds.length / maxNftArrayLength + 1;
} else {
multiple = nftIds.length / maxNftArrayLength;
}
split = 2;
splitCounter++;
}
}
} else {
if (nftIds.length % maxNftArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxNftArrayLength + 1;
endIndex = nftIds.length;
} else {
startIndex = splitCounter * maxNftArrayLength + 1;
endIndex = (splitCounter + 1) * maxNftArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredNfts(target);
}
if (endIndex > nftIds.length) endIndex = nftIds.length;
if (startIndex > nftIds.length) return;
uint256[] memory batchIds = new uint256[](endIndex - startIndex + 1);
for (uint i = startIndex; i < endIndex; i++) {
batchIds[i] = nftIds[i];
}
DiamondInterface(diamondContract).safeBatchTransferFrom(address(this), target, batchIds, new bytes(0));
}
function transferItems() internal {
require(
msg.sender == target,
"transferItems: caller not approved"
);
require(
mergerStatus == MergerStatus.ACTIVE ||
demergerStatus == DemergerStatus.ACTIVE,
"transferItems: merger, transfer or demerger not active"
);
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedItemsDemerger[votedIndexItems[votedIndex]].length;
} else {
ItemIdIO[] memory items = DiamondInterface(diamondContract).itemBalances(this.address);
arrayLength = items.length;
}
ItemIdIO[] memory items = new ItemIdIO[](arrayLength);
uint256[] memory ids = new uint256[](arrayLength);
uint256[] memory quantities = new uint256[](arrayLength);
uint256 startIndex;
uint256 endIndex = arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
ids = votedItems[votedIndexItems[votedIndex]];
quantities = votedItemsQuantity[votedIndexItemsQuantity[votedIndex]];
endIndex = ids.length;
} else {
items = DiamondInterface(diamondContract).itemBalances(this.address);
endIndex = items.length;
}
if (split == 0) {
maxItemsArrayLength = ISettings(settingsContract).maxItemsArrayLength();
if (arrayLength > maxItemsArrayLength) {
endIndex = maxItemsArrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
if (arrayLength % maxItemsArrayLength > 0) {
multiple = arrayLength / maxItemsArrayLength + 1;
} else {
multiple = arrayLength / maxItemsArrayLength;
}
split = 3;
splitCounter++;
}
}
{
bool exist;
uint256[] memory idsTickets = new uint256[](7);
uint256[] memory quantityTickets = new uint256[](7);
if (demergerStatus == DemergerStatus.ACTIVE) {
quantityTickets = votedTicketsQuantity[votedIndexTicketsQuantity[votedIndex]];
} else {
quantityTickets = DiamondInterface(stakingContract).balanceOfAll(this.address);
}
for (uint i = 0; i < idsTickets.length; i++) {
idsTickets[i] = i;
if (exist == false) {
if (quantityTickets[i] > 0) exist = true;
}
}
if (exist == true) {
IERC1155Upgradeable(stakingContract).safeBatchTransferFrom(address(this), target, idsTickets, quantityTickets, new bytes(0));
}
}
} else {
if (ids.length % maxItemsArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxItemsArrayLength + 1;
endIndex = ids.length;
} else {
startIndex = splitCounter * maxItemsArrayLength + 1;
endIndex = (splitCounter + 1) * maxItemsArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredItems(target);
}
if (endIndex > ids.length) endIndex = ids.length;
if (startIndex > ids.length) return;
uint256[] memory batchIds = new uint256[](endIndex - startIndex + 1);
uint256[] memory batchQuantities = new uint256[](endIndex - startIndex + 1);
for (uint i = startIndex; i < endIndex; i++) {
if (mergerStatus = MergerStatus.ACTIVE) {
batchIds[i] = items[i].itemId;
batchQuantities[i] = items[i].balance;
} else {
batchIds[i] = ids[i];
batchQuantities[i] = quantities[i];
}
}
IERC1155Upgradeable(stakingContract).safeBatchTransferFrom(address(this), target, batchIds, batchQuantities, new bytes(0));
}
function transferExternalErc20() internal {
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedExtErc20[votedIndexExtErc20[votedIndex]].length;
} else {
arrayLength = erc20Tokens.length;
}
uint256[] memory erc20Address = new uint256[](arrayLength);
uint256[] memory erc20Value = new uint256[](arrayLength);
if (demergerStatus == DemergerStatus.ACTIVE) {
erc20Value = votedExtErc20Value[votedIndexExtErc20[votedIndex]];
erc20Address = votedExtErc20Address[votedIndexExtErc20Address[votedIndex]];
} else {
for (uint i = 0; i < erc20Tokens.length; i++) {
erc20Value = ownedErc20[erc20Tokens[i]];
}
erc20Address = erc20Tokens;
}
uint256 startIndex;
uint256 endIndex = erc20Value.length;
if (split == 0) {
maxExtErc20ArrayLength = ISettings(settingsContract).maxExtErc20ArrayLength();
if (erc20Value.length > maxExtErc20ArrayLength) {
endIndex = maxExtErc20ArrayLength;
if (erc20Value.length % maxExtErc20ArrayLength > 0) {
multiple = erc20Value.length / maxExtErc20ArrayLength + 1;
} else {
multiple = erc20Value.length / maxExtErc20ArrayLength;
}
split = 6;
splitCounter++;
}
} else {
if (erc20Value.length % maxExtErc20ArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxExtErc20ArrayLength + 1;
endIndex = erc20Value.length;
} else {
startIndex = splitCounter * maxExtErc20ArrayLength + 1;
endIndex = (splitCounter + 1) * maxExtErc20ArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredExtErc20(target);
}
if (endIndex > erc20Value.length) endIndex = erc20Value.length;
if (startIndex > erc20Value.length) return;
uint256 assetCounter;
address replace;
for (uint i = startIndex; i < endIndex; i++) {
try LibERC20.transferFrom(erc20Address[i], addresse(this), target, erc20Value[i]) {
ownedErc20[erc20Address[i]] -= erc20Value[i];
if (ownedErc20[erc20Address[i]] == 0 && demergerStatus == DemergerStatus.ACTIVE) {
replace = erc20Tokens[erc20Tokens.length - 1];
erc20Tokens[erc20Index[erc20Address[i]]] = replace;
erc20Index[replace] = erc20Index[erc20Address[i]];
delete erc20Index[erc20Address[i]];
erc20Tokens.pop();
}
if (mergerStatus == MergerStatus.ACTIVE) delete erc20Index[erc20Address[i]];
} catch {
nonTransferredAssets++;
emit NonTransferredErc20(erc20Address[i], erc20Value[i]);
}
}
if (mergerStatus == MergerStatus.ACTIVE) extAssetsTansferred += assetCounter;
}
function transferExternalNfts() internal {
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedExtNfts[votedIndexExtNfts[votedIndex].length;
} else {
arrayLength = nfts.length;
}
uint256[] memory nftsAddress = new uint256[](arrayLength);
uint256[] memory nftsId = new uint256[](arrayLength);
if (demergerStatus == DemergerStatus.ACTIVE) {
nftsId = votedExtNfts[votedIndexExtNfts[votedIndex]];
nftsAddress = votedExtNftsAddress[votedIndexExtAddress[votedIndex]];
} else {
for (uint i = 0; i < nfts.length; i++) {
nftsId = nfts[i].id;
}
nftsAddress = nfts;
}
uint256 startIndex;
uint256 endIndex = nftsId.length;
if (split == 0) {
maxExtNftArrayLength = ISettings(settingsContract).maxExtNftArrayLength();
if (nftsId.length > maxExtNftArrayLength) {
endIndex = maxExtNftArrayLength;
if (nftsId.length % maxExtNftArrayLength > 0) {
multiple = nftsId.length / maxExtNftArrayLength + 1;
} else {
multiple = nftsId.length / maxExtNftArrayLength;
}
split = 4;
splitCounter++;
}
} else {
if (nftsId.length % maxExtNftArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxExtNftArrayLength + 1;
endIndex = nftsId.length;
} else {
startIndex = splitCounter * maxExtNftArrayLength + 1;
endIndex = (splitCounter + 1) * maxExtNftArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredExtNfts(target);
}
if (endIndex > nftsId.length) endIndex = nftsId.length;
if (startIndex > nftsId.length) return;
uint256 assetCounter;
address replace;
for (uint i = startIndex; i < endIndex; i++) {
try IERC721Upgradeable(nftsAddress[i]).safeTransferFrom(address(this), target, nftsId[i]) {
delete ownedNfts[nftAddress[i]][nftsId[i]];
if (demergerStatus == DemergerStatus.ACTIVE) {
replace = nfts[nfts.length - 1];
nfts[nftsIndex[nftsAddress[i]]] = replace;
nftsIndex[replace] = nftsIndex[nftsAddress[i]];
delete nftsIndex[nftsAddress[i]];
nfts.pop();
}
if (mergerStatus == MergerStatus.ACTIVE) delete nftsIndex[nftsAddress[i]];
} catch {
nonTransferredAssets++;
emit NonTransferredNfts(nftsAddress[i], nftsId[i]);
}
}
}
function transferExternal1155() internal {
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedExt1155Transfer[votedIndexExt1155[votedIndex]].length;
} else {
arrayLength = erc1155Tokens.length;
}
uint256[] memory ids1155 = new uint256[](arrayLength);
uint256[] memory quantity1155 = new uint256[](arrayLength);
address[] memory address1155 = new uint256[](arrayLength);
if (demergerStatus == DemergerStatus.ACTIVE) {
ids1155 = votedExt1155[votedIndexExt1155[votedIndex]];
quantity1155 = votedExt1155Quantity[votedIndexExt1155Quantity[votedIndex]];
address1155 = votedExt1155Address[votedIndexExt1155Address[votedIndex]];
} else {
for (uint i = 0; i < erc1155Tokens.length; i++) {
ids1155 = erc1155Tokens[i].id;
quantity1155 = erc1155Tokens[i].quantity;
}
address1155 = erc1155Tokens;
}
uint256 startIndex;
uint256 endIndex = ids1155.length;
if (split == 0) {
maxExt1155ArrayLength = ISettings(settingsContract).maxExt1155ArrayLength();
if (ids1155.length > maxExtItemsArrayLength) {
endIndex = maxExtItemsArrayLength;
if (ids1155.length % maxExtItemsArrayLength > 0) {
multiple = ids1155.length / maxExtItemsArrayLength + 1;
} else {
multiple = ids1155.length / maxExtItemsArrayLength;
}
split = 5;
splitCounter++;
}
} else {
if (ids1155.length % maxExtItemsArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxExtItemsArrayLength + 1;
endIndex = ids1155.length;
} else {
startIndex = splitCounter * maxExtItemsArrayLength + 1;
endIndex = (splitCounter + 1) * maxExtItemsArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredExt1155(target);
}
if (endIndex > ids1155.length) endIndex = ids1155.length;
if (startIndex > ids1155.length) return;
uint256 assetCounter;
for (uint i = startIndex; i < endIndex; i++) {
if (address1155[i] == address(0)) continue;
uint256 redundancyCounter;
redundancyCounter++;
address replace;
uint256[] memory indexRedundancy = new indexRedundancy[](endIndex - startIndex + 1);
for (uint j = i + 1; j < endIndex; j++) {
if (address1155[j] == address(0)) continue;
if (address1155[i] == address1155[j]) {
ownedErc1155[address1155[j]][ids1155[j]] -= quantity1155[j];
if (demergerStatus == DemergerStatus.ACTIVE && ownedErc1155[address1155[j]][ids1155[j]] == 0) {
erc1155Tokens[j] = erc1155Tokens[erc1155Tokens.length - 1];
erc1155Tokens.pop();
replace = erc1155Tokens[erc1155Tokens.length - 1];
erc1155Tokens[erc1155Index[address1155[i]]] = replace;
erc1155Index[replace] = erc1155Index[address1155[j]];
delete nftsIndex[address1155[j]];
erc1155Tokens.pop();
}
if (mergerStatus == MergerStatus.ACTIVE) delete erc1155Index[address1155[i]];
indexRedundancy[redundancyCounter] = j;
delete address1155[j];
redundancyCounter++;
}
uint256 indexCounter;
uint256[] memory batchIds = new uint256[](redundancyCounter);
uint256[] memory batchQuantity = new uint256[](redundancyCounter);
batchIds[indexCounter] = ids1155[i];
batchQuantity[indexCounter] = quantity1155[i];
indexCounter++;
for (uint k = 1; k < redundancyCounter; k++) {
batchIds[indexCounter] = ids1155[indexRedundancy[k]];
batchQuantity[indexCounter] = quantity1155[indexRedundancy[k]];
indexCounter++;
}
try IERC1155Upgradeable(address1155[i]).safeBatchTransferFrom(address(this), target, batchIds, batchQuantity, new bytes(0)) {
ownedErc1155[address1155[i]][ids1155[i]] -= quantity1155[i];
if (demergerStatus == DemergerStatus.ACTIVE && ownedErc1155[address1155[i]][ids1155[i]] == 0) {
erc1155Tokens[i] = erc1155Tokens[erc1155Tokens.length - 1];
erc1155Tokens.pop();
replace = erc1155Tokens[erc1155Tokens.length - 1];
erc1155Tokens[erc1155Index[address1155[i]]] = replace;
erc1155Index[replace] = erc1155Index[address1155[i]];
delete nftsIndex[address1155[i]];
erc1155Tokens.pop();
}
} catch {
nonTransferredAssets += redundancyCounter;
emit NonTransferredErc1155(address1155[i], batchIds, batchQuantity);
}
redundancyCounter = 0;
}
}
}
function voteForDemerger(
uint256[] calldata _nftsId,
uint256[] calldata _extNftsId,
uint256[] calldata _ext1155Id,
uint256[] calldata _realmsId,
uint256[] calldata _itemsId,
uint256[] calldata _itemsQuantity,
uint256[] calldata _extErc20Value,
uint256[] calldata _ext1155Quantity,
uint256[7] calldata _ticketsQuantity,
address[] calldata _extErc20Address,
address[] calldata _extNftsAddress,
address[] calldata _ext1155Address,
uint256 _idToVoteFor,
string calldata _name,
string calldata _symbol
) external nonReentrant {
require(
fundingStatus == FundingStatus.INACTIVE,
"voteForDemerger: FrAactionHub not fractionalized yet"
);
require(
balanceOf(msg.sender) > 0,
"voteForDemerger: user not an owner of the FrAactionHub"
);
require(
demergerStatus == DemergerStatus.INACTIVE,
"voteForDemerger: user not an owner of the FrAactionHub"
);
require(
mergerStatus == MergerStatus.INACTIVE,
"voteForDemerger: active merger"
);
require(
_itemsId.length == _itemsQuantity.length &&
_extNftsId.length == _extNftsAddress.length &&
_ext1155Id.length == _ext1155Address.length &&
_ext1155Address.length == _ext1155Quantity.length &&,
"voteForDemerger: input arrays lengths are not matching"
);
require(
_nftsId.length +
_realmsId.length +
_itemsId.length +
_itemsQuantity.length +
_ticketsQuantity.length +
_extNftsId.length +
_extNftsAddress.length +
_ext1155Id.length +
_ext1155Quantity.length +
_ext1155Address.length +
=< ISettings(settingsContract).MaxTransferLimit(),
"voteForDemerger: cannot transfer more than the GovSettings allowed limit"
);
if (_nftsId.length > 0 ||
_realmsId.length > 0 ||
_itemsId.length > 0 ||
_ticketsId.length > 0 ||
_extNftsId.length > 0 ||
_ext1155Id.length > 0
) {
require(
_idToVoteFor == votedIndex,
"voteFordemerger: user submitting a new demerger has to vote for it"
);
ownershipCheck(
_nftsId,
_realmsId,
_itemsId,
_itemsQuantity,
_ticketsQuantity,
true
);
ownershipCheckExt(
_extNftsId,
_ext1155Id,
_extErc20Value,
_ext1155Quantity,
_extErc20Address,
_extNftsAddress,
_ext1155Address,
true
);
votedIndex++;
}
if (votersDemerger[msg.sender][_idToVoteFor] == true) {
if (balanceOf(msg.sender) != currentDemergerBalance[msg.sender][_idToVoteFor])
votesTotalDemerger[_idToVoteFor] -= currentDemergerBalance[msg.sender][_idToVoteFor];
} else {
votersDemerger[msg.sender][_idToVoteFor] = true;
}
if (_name != "" && _symbol != "") {
if (demergerName[_idToVoteFor] == "" && demergerSymbol[_idToVoteFor] == "") {
demergerName[_idToVoteFor] = _name;
demergerSymbol[_idToVoteFor] = _symbol;
}
}
if (balanceOf(msg.sender) != currentDemergerBalance[msg.sender][_idToVoteFor]) {
votesTotalDemerger[_idToVoteFor] += balanceOf(msg.sender);
currentDemergerBalance[msg.sender][_idToVoteFor] = balanceOf(msg.sender);
}
if (votesTotalDemerger[_idToVoteFor] * 1000 >= ISettings(settingsContract).minDemergerVotePercentage() * totalSupply()) {
ownershipCheck(
_nftsId,
_realmsId,
_itemsId,
_itemsQuantity,
_ticketsQuantity,
false
);
ownershipCheckExt(
_extNftsId,
_ext1155Id,
_extErc20Value,
_ext1155Quantity,
_extErc20Address,
_extNftsAddress,
_ext1155Address,
false
);
address fraactionFactoryContract = ISettings(settingsContract).fraactionFactoryContract();
(bool success, bytes memory returnData) =
fraactionFactoryContract.call(
abi.encodeWithSignature(
"startFraactionHub(
string,
string,
address
)",
demergerName[_idToVoteFor],
demergerSymbol[_idToVoteFor],
address(this)
)
);
require(
success,
string(
abi.encodePacked(
"voteForDemerger: mergerFrom order failed: ",
returnData
)
)
);
target = abi.decode(returnData, (address));
votedIndex = _idToVoteFor;
demergerStatus = DemergerStatus.ACTIVE;
emit DemergerActive(target, demergerName[_idToVoteFor], demergerSymbol[_idToVoteFor]);
claimReward(msg.sender);
}
}
function demergeTo() external nonReentrant {
require(
demergerStatus == DemergerStatus.ACTIVE,
"demergeTo: demerger not active"
);
if (!realmsTransferred || split = 1) {
transferRealms();
if (split == 0) realmsTransferred = true;
} else if (!nftsTransferred || split = 2) {
transferNfts();
if (split == 0) nftsTransferred = true;
} else if (!itemsTransferred || split = 3) {
transferItems();
if (split == 0) itemsTransferred = true;
} else if (!extNftsTransferred || split = 4) {
transferExternalNfts();
if (split == 0) extNftsTransferred = true;
} else if (!ext1155Transferred || split = 5) {
transferExternal1155();
if (split == 0) ext1155Transferred = true;
} else if (!extErc20Transferred || split = 6) {
transferExternalErc20();
if (split == 0) extErc20Transferred = true;
} else {
demergerStatus = DemergerStatus.INACTIVE;
FraactionInterface(target).confirmDemerger();
realmsTransferred = false;
nftsTransferred = false;
itemsTransferred = false;
extNftsTransferred = false;
ext1155Transferred = false;
extErc20Transferred = false;
DemergerAssetsTransferred(address(this));
}
claimReward(msg.sender);
}
function finalizeDemerger() external nonReentrant {
require(
demergerStatus == DemergerStatus.ASSETSTRANSFERRED,
"finalizeDemerger: demerger assets not transferred yet"
);
address[] memory ownersFrom = FraactionInterface(target).getOwners();
uint256 startIndex = 0;
uint256 endIndex = ownersFrom.length;
if (split == 0) {
maxOwnersArrayLength = ISettings(settingsContract).maxOwnersArrayLength();
if (ownersFrom.length > maxOwnersArrayLength) {
if (ownersFrom.length % maxOwnersArrayLength > 0) {
multiple = ownersFrom.length / maxOwnersArrayLength + 1;
} else {
multiple = ownersFrom.length / maxOwnersArrayLength;
}
split = 7;
splitCounter++;
}
endIndex = maxOwnersArrayLength;
} else {
if (ownersFrom.length % maxOwnersArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxOwnersArrayLength + 1;
endIndex = ownersFrom.length;
} else {
startIndex = splitCounter * maxOwnersArrayLength + 1;
endIndex = (splitCounter + 1) * maxOwnersArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
demergerStatus = DemergerStatus.INACTIVE;
target = address(0);
emit DemergerFinalized(target);
}
if (endIndex > ownersFrom.length) endIndex = ownersFrom.length;
if (startIndex > ownersFrom.length) return;
bool existing;
for (uint i = startIndex; i < endIndex; i++) {
ownersAddress.push(ownersFrom[i]);
mint(
ownersFrom[i],
FraactionInterface(target).balanceOf(ownersFrom[i])
);
}
claimReward(msg.sender);
}
function confirmDemerger() external {
require(
msg.sender == target,
"confirmDemerger: caller is not the demerger parent contract"
);
require(
demergerStatus == DemergerStatus.ACTIVE,
"confirmDemerger: demerger is not active
);
demergerStatus = DemergerStatus.ASSETSTRANSFERRED;
DemergerAssetsTransferred(address(this));
}
function ownershipCheck(
uint256[] memory _nftsId,
uint256[] memory _realmsId,
uint256[] memory _itemsId,
uint256[] memory _itemsQuantity,
uint256[7] memory _ticketsQuantity,
bool _saveParams
) internal {
uint256 counterOwned;
if (_nftsId.length > 0) {
uint32[] memory nftsId = DiamondInterface(diamondContract).tokenIdsOfOwner(address(this));
for (uint i = 0; i < _nftsId.length; i++) {
for (uint j = 0; j < nftsId.length; j++) {
if (_nftsId[i] == nftsId[j]) {
counterOwned++;
break;
}
}
}
}
if (_realmsId.length > 0) {
uint32[] memory realmsId = DiamondInterface(realmsContract).tokenIdsOfOwner(address(this));
for (uint i = 0; i < _realmsId.length; i++) {
for (uint j = 0; j < realmsId.length; j++) {
if (_realmsId[i] == realmsId[j]) {
counterOwned++;
break;
}
}
}
}
if (_itemsId.length > 0) {
ItemIdIO[] memory balance = DiamondInterface(diamondContract).itemBalances(address(this));
for (uint i = 0; i < _itemsId.length; i++) {
require(
_itemsQuantity[i] > 0,
"ownershipCheck: invalid item quantity"
);
for (uint j = 0; j < balance.length; j++) {
if (_itemsId[i] == balance[j].itemId) {
require(
_itemsQuantity[i] <= balance[j].balance,
"ownershipCheck: proposed item quantities have to be equal or inferior to the owned items quantities"
);
counterOwned++;
break;
}
}
}
}
if (_ticketsQuantity.length > 0) {
bool check;
uint256[] memory ticketsCurrentQuantity = DiamondInterface(stakingContract).balanceOfAll(address(this));
for (uint i = 0; i < _ticketsQuantity.length; i++) {
if (_ticketsQuantity[i] == 0) check = true;
require(
_ticketsQuantity[i] <= ticketsCurrentQuantity[i],
"ownershipCheck: proposed tickets quantities have to be equal or inferior to the owned tickets quantities"
);
counterOwned++;
}
require(
!check,
"ownershipCheck: a ticket quantity has to be provided"
);
}
require(
counterOwned == _nftsId.length + _realmsId.length + _itemsId.length + _ticketsQuantity.length,
"ownershipCheck: one token or more is not owned by the FrAactionHub"
);
if (_saveParams) {
if (_nftsId.length > 0) {
votedIndexNfts[votedIndex] = votedNfts.length;
votedNfts.push(_nftsId);
}
if (_realmsId.length > 0) {
votedIndexRealms[votedIndex] = votedRealms.length;
votedRealms.push(_realmsId);
}
if (_itemsId.length > 0) {
votedIndexItems[votedIndex] = votedItems.length;
votedItems.push(_itemsId);
votedIndexItemsQuantity[votedIndex] = votedItemsQuantity.length;
votedItemsQuantity.push(_itemsQuantity);
}
if (_ticketsQuantity.length > 0) {
votedIndexTicketsQuantity[votedIndex] = votedTicketsQuantity.length;
votedTicketsQuantity.push(_ticketsQuantity);
}
}
}
function ownershipCheckExt(
uint256[] memory _extNftsId,
uint256[] memory _ext1155Id,
uint256[] memory _extErc20Value,
uint256[] memory _ext1155Quantity,
address[] memory _extErc20Address,
address[] memory _extNftsAddress,
address[] memory _ext1155Address,
bool _saveParams
) internal {
uint256 counterOwned;
if (_extNftsId.length > 0) {
for (uint i = 0; i < _extNftsId.length; i++) {
require(
_extNftsAddress[i] != address(0),
"ownershipCheckExt: invalid NFT address"
);
if (ownedNfts[_extNftsAddress[i]][_extNftsId[i]] == true) counterOwned++;
}
}
if (_extErc20Value.length > 0) {
for (uint i = 0; i < _extErc20Value.length; i++) {
require(
_extErc20Value[i] > 0 && _extErc20Address[i] != address(0),
"ownershipCheckExt: invalid item quantity or address"
);
require(
ownedErc20[_extErc20Address[i]] <= _extErc20Value[i],
"ownershipCheckExt: proposed item quantities have to be equal or inferior to the owned items quantities"
);
counterOwned++;
}
}
if (_ext1155Id.length > 0) {
for (uint i = 0; i < _ext1155Id.length; i++) {
require(
_ext1155Quantity[i] > 0 && _ext1155Address[i] != address(0),
"ownershipCheckExt: invalid item quantity or address"
);
require(
ownedErc1155[_ext1155Address[i]][_ext1155Id[i]] <= _ext1155Quantity[i],
"ownershipCheckExt: proposed item quantities have to be equal or inferior to the owned items quantities"
);
counterOwned++;
}
}
require(
counterOwned == _extErc20Value.length + _extNftsId.length + _ext1155Id.length,
"ownershipCheckExt: one token or more is not owned by the FrAactionHub"
);
}
if (_saveParams) {
if (_extErc20Value.length > 0) {
votedIndexExtErc20Value[votedIndex] = votedExtErc20Value.length;
votedExtErc20Value.push(_extErc20Value);
votedIndexExtErc20Address[votedIndex] = votedExtErc20Address.length;
votedExtErc20Address.push(_extErc20Address);
}
if (_extNftsId.length > 0) {
votedIndexExtNfts[votedIndex] = votedExtNfts.length;
votedExtNfts.push(_extNftsId);
votedIndexExtAddress[votedIndex] = votedExtAddress.length;
votedExtAddress.push(_extNftsAddress);
}
if (_ext1155Id.length > 0) {
votedIndexExt1155[votedIndex] = votedExt1155.length;
votedExt1155.push(_ext1155Id);
votedIndexExt1155Quantity[votedIndex] = votedExt1155Quantity.length;
votedExt1155Quantity.push(_ext1155Quantity);
votedIndexExt1155Address[votedIndex] = votedExt1155Address.length;
votedExt1155Address.push(_ext1155Address);
}
}
}
/// @notice a function for an end user to update their desired sale price
/// @param _new the desired price in GHST
function updateUserPrice(uint256 _new) external {
require(
balanceOf(msg.sender) > 0,
"updateUserPrice: user not an owner of the FrAactionHub"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"updatePrice: auction live cannot update price"
);
require(
initialized == true,
"updatePrice: FrAactionHub not fractionalized yet"
);
uint256 old = userPrices[msg.sender];
require(
_new != old,
"updatePrice:not an update"
);
uint256 weight = balanceOf(msg.sender);
if (votingTokens == 0) {
votingTokens = weight;
reserveTotal = weight * _new;
}
// they are the only one voting
else if (weight == votingTokens && old != 0) {
reserveTotal = weight * _new;
}
// previously they were not voting
else if (old == 0) {
uint256 averageReserve = reserveTotal / votingTokens;
uint256 reservePriceMin = averageReserve * ISettings(settingsContract).minReserveFactor() / 1000;
require(
_new >= reservePriceMin,
"updatePrice:reserve price too low"
);
uint256 reservePriceMax = averageReserve * ISettings(settingsContract).maxReserveFactor() / 1000;
require(
_new <= reservePriceMax,
"update:reserve price too high"
);
votingTokens += weight;
reserveTotal += weight * _new;
}
// they no longer want to vote
else if (_new == 0) {
votingTokens -= weight;
reserveTotal -= weight * old;
}
// they are updating their vote
else {
uint256 averageReserve = (reserveTotal - (old * weight)) / (votingTokens - weight);
uint256 reservePriceMin = averageReserve * ISettings(settingsContract).minReserveFactor() / 1000;
require(
_new >= reservePriceMin,
"updatePrice:reserve price too low"
);
uint256 reservePriceMax = averageReserve * ISettings(settingsContract).maxReserveFactor() / 1000;
require(
_new <= reservePriceMax,
"updatePrice:reserve price too high"
);
reserveTotal = reserveTotal + (weight * _new) - (weight * old);
}
userPrices[msg.sender] = _new;
emit PriceUpdate(msg.sender, _new);
}
/// @notice an external function to decrease an Aavegotchi staked collateral amount
function voteForStakeDecrease(uint256 _tokenId, uint256 _stakeAmount) external nonReentrant {
require(
balanceOf(msg.sender) > 0,
"VoteForStakeDecrease: user not an owner of the FrAactionHub"
);
require(
_stakeAmount < DiamondInterface(diamondContract).collateralBalance(_tokenId).balance_,
"VoteForStakeDecrease: stake amount greater than the total contributed amount"
);
require(
_stakeAmount > 0,
"VoteForStakeDecrease: staked amount must be greater than 0"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"VoteForStakeDecrease: an auction is live"
);
require(
_stakeAmount < DiamondInterface(diamondContract).getAavegotchi(_tokenId).minimumStake,
"VoteForStakeDecrease: amount has to be lower than the minimum stake"
);
if (decreaseNumber[_tokenId][_stakeAmount] != decreaseCurrentNumber[msg.sender][_tokenId][_stakeAmount]) {
votersDecrease[msg.sender][_tokenId][_stakeAmount] = 0;
currentDecreaseBalance[msg.sender][_tokenId][_stakeAmount] = 0;
}
votesTotalDecrease[_tokenId][_stakeAmount] += balanceOf(msg.sender) - currentDecreaseBalance[msg.sender][_tokenId][_stakeAmount];
currentDecreaseBalance[msg.sender][_tokenId][_stakeAmount] = balanceOf(msg.sender);
if (decreaseStaking[_tokenId][_stakeAmount] == 0) decreaseStaking[_tokenId][_stakeAmount] = _stakeAmount;
if (decreaseNumber != decreaseCurrentNumber[msg.sender]) decreaseCurrentNumber[msg.sender][_tokenId][_stakeAmount] = decreaseNumber;
if (votesTotalDecrease[_tokenId][_stakeAmount] * 1000 >= ISettings(settingsContract).minDecreaseVotePercentage() * totalSupply()) {
address collateral = DiamondInterface(diamondContract).collateralBalance(_tokenId).collateralType_;
(bool success, bytes memory returnData) =
diamondContract.call(
abi.encodeWithSignature("decreaseStake(uint256,uint256)",
_tokenId,
decreaseStaking[_tokenId]
)
);
require(
success,
string(
abi.encodePacked(
"VoteForStakeDecrease: staking order failed: ",
returnData
)
)
);
redeemedCollateral[collateral].push(decreaseStaking[_tokenId][_stakeAmount]);
if (collateralToRedeem[collateral] == 0) {
collateralToRedeem[collateral] = true;
collateralAvailable.push(collateral);
}
decreaseStaking[_tokenId][_stakeAmount] = 0;
emit StakeDecreased(
_tokenId,
decreaseStaking[_tokenId][_stakeAmount]
);
claimed[_contributor] = false;
if (allClaimed == true) allClaimed = false;
}
}
/// @notice a function to vote for opening an already purchased and closed portal
function voteForOpenPortal(uint256 _tokenId) external {
require(
initialized == true,
"voteForOpenPortal: cannot vote if an auction is ended"
);
require(
balanceOf(msg.sender) > 0,
"voteForOpenPortal: user not an owner of the NFT"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"voteForOpenPortal: auction live cannot update price"
);
AavegotchiInfo memory gotchi = getAavegotchi(_tokenId);
require(
gotchi.status == 0,
"voteForOpenPortal: portal already open"
);
if (votersOpen[msg.sender][_tokenId] == true) {
votesTotalOpen[_tokenId] -= currentOpenBalance[msg.sender][_tokenId];
} else {
votersOpen[msg.sender][_tokenId] = true;
}
votesTotalOpen[_tokenId] += balanceOf(msg.sender);
currentOpenBalance[msg.sender][_tokenId] = balanceOf(msg.sender);
if (votesTotalOpen[_tokenId] * 1000 >= ISettings(settingsContract).minOpenVotePercentage() * totalSupply()) {
DiamondInterface(diamondContract).openPortals(_tokenId);
emit OpenPortal(_tokenId);
assets[tokenIdToAssetIndex[_tokenId]].category = 1;
votesTotalOpen[_tokenId] = 0;
}
}
/// @notice vote for an Aavegotchi to be summoned
function voteForAavegotchi(uint256 _tokenId, uint256 _option) external {
AavegotchiInfo memory gotchi = getAavegotchi(_tokenId);
require(
gotchi.status == 2,
"voteForAavegotchi: portal not open yet or Aavegotchi already summoned"
);
require(_option < 10,
"voteForAavegotchi: only 10 options available"
);
require(balanceOf(msg.sender) > 0,
"voteForAavegotchi: only owners can vote"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"voteForAavegotchi: auction live cannot update price"
);
if (votersAavegotchi[msg.sender][_tokenId] == true) {
votesAavegotchi[_tokenId][currentAavegotchiVote[msg.sender][_tokenId]] -= currentAavegotchiBalance[msg.sender][_tokenId];
votesTotalAavegotchi -= currentAavegotchiBalance[msg.sender][_tokenId];
} else {
votersAavegotchi[msg.sender][_tokenId] = true;
}
if (votesAavegotchi[_tokenId][_option] == 0) votedAavegotchi[_tokenId].push(_option);
votesAavegotchi[_tokenId][_option] += balanceOf(msg.sender);
votesTotalAavegotchi[_tokenId] += balanceOf(msg.sender);
currentAavegotchiVote[msg.sender][_tokenId] = _option;
currentAavegotchiBalance[msg.sender][_tokenId] = balanceOf(msg.sender);
uint256 winner;
uint256 result;
if (votesTotalAavegotchi[_tokenId] * 1000 >= ISettings(settingsContract).minAavegotchiVotePercentage() * totalSupply()) {
for (uint i = 0; i < votedAavegotchi[_tokenId].length; i++) {
if (votesAavegotchi[_tokenId][votedAavegotchi[_tokenId][i]] > result) {
result = votesAavegotchi[_tokenId][votedAavegotchi[i]];
winner = votedAavegotchi[_tokenId][i];
}
votesAavegotchi[_tokenId][votedAavegotchi[_tokenId][i]] = 0;
}
aavegotchi[_tokenId] = winner;
PortalAavegotchiTraitsIO[] memory portalInfo = DiamondInterface(diamondContract).portalAavegotchiTraits(_tokenId);
address collateral = portalInfo[_option].collateral;
DiamondInterface(collateral).approve(diamondContract, MAX_INT);
emit AppointedAavegotchi(_tokenId, aavegotchi[_tokenId]);
delete votedAavegotchi[_tokenId];
votesTotalAavegotchi[_tokenId] = 0;
}
}
/// @notice vote for naming an Aavegotchi
function voteForName(uint256 _tokenId, string calldata _name) external {
require(balanceOf(msg.sender) > 0,
"voteForName: only owners can vote"
);
AavegotchiInfo memory gotchi = getAavegotchi(_tokenId);
require(
gotchi.status == 3,
"voteForName: Aavegotchi not summoned yet"
);
require(DiamondInterface(diamondContract).aavegotchiNameAvailable(_name),
"voteForName: Aavegotchi name not available"
);
if (nameNumber[_tokenId] != nameCurrentNumber[msg.sender][_tokenId]) {
votersName[msg.sender][_tokenId] = 0;
currentNameVote[msg.sender][_tokenId] = 0;
currentNameBalance[msg.sender][_tokenId] = 0;
}
if (votersName[msg.sender][_tokenId] == true) {
votesName[_tokenId][currentNameVote[msg.sender][_tokenId]] -= currentNameBalance[msg.sender][_tokenId];
votesTotalName -= currentNameBalance[msg.sender][_tokenId];
} else {
votersName[msg.sender][_tokenId] = true;
}
if (votesName[_tokenId][_name] == 0) votedName[_tokenId].push(_name);
votesName[_tokenId][_name] += balanceOf(msg.sender);
votesTotalName[_tokenId] += balanceOf(msg.sender);
currentNameVote[msg.sender][_tokenId] = _name;
currentNameBalance[msg.sender][_tokenId] = balanceOf(msg.sender);
if (nameNumber[_tokenId] != nameCurrentNumber[msg.sender][_tokenId])
nameCurrentNumber[msg.sender][_tokenId] = nameNumber[_tokenId];
string memory winner;
uint256 result;
if (votesTotalName[_tokenId] * 1000 >= ISettings(settingsContract).minNameVotePercentage() * totalSupply()) {
for (uint i = 0; i < votedName[_tokenId].length; i++) {
if (votesName[_tokenId][votedName[_tokenId][i]] > result) {
result = votesName[_tokenId][votedName[i]];
winner = votedName[_tokenId][i];
}
votesName[_tokenId][votedName[_tokenId][i]] = 0;
votedName[_tokenId][i] = 0;
}
name[_tokenId] = winner;
DiamondInterface(diamondContract).setAavegotchiName(_tokenId, name[_tokenId]);
emit Named(_tokenId, name[_tokenId]);
votesTotalName[_tokenId] = 0;
nameNumber[_tokenId]++:
}
}
/// @notice vote for spending available skill points on an Aavegotchi
function voteForSkills(uint256 _tokenId, int16[4] calldata _values) external {
require(balanceOf(msg.sender) > 0,
"voteForSkills: only owners can vote"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"voteForSkills: auction live cannot update price"
);
uint256 total;
for (uint i = 0; i < _values.length; i++) {
if (_values[i] < 0) {
total += -(_values[i]);
} else {
total += _values[i];
}
}
require(total > 0,
"voteForSkills: must allocate at least 1 skill point"
);
require(DiamondInterface(diamondContract).availableSkillPoints(_tokenId) > total,
"voteForSkills: not enough available skill points"
);
if (skillNumber[_tokenId] != skillCurrentNumber[msg.sender][_tokenId]) {
votersSkill[msg.sender][_tokenId] = 0;
currentSkillBalance[msg.sender][_tokenId] = 0;
}
if (votersSkill[msg.sender][_tokenId] == true) {
votesSkill[_tokenId][currentSkillVote[msg.sender][_tokenId]] -= currentSkillBalance[msg.sender][_tokenId];
votesTotalSkill -= currentSkillBalance[msg.sender][_tokenId];
} else {
votersSkill[msg.sender][_tokenId] = true;
}
uint256 counter;
if (skillVoting[_tokenId] == false) {
votedSkill[_tokenId].push(_values);
votesSkill[_tokenId][0] += balanceOf(msg.sender);
currentSkillVote[msg.sender][_tokenId] = 0;
skillVoting[_tokenId] = true;
} else if (skillVoting == true) {
for (uint i = 0; i < votedSkill.length; i++) {
for (uint j = 0; j < _values.length; j++) {
if (votedSkill[i][j] == _values[j]) counter++;
}
if (counter == 4) {
votesSkill[_tokenId][i] += balanceOf(msg.sender);
currentSkillVote[msg.sender][_tokenId] = i;
break;
}
}
} else if (counter != 4) {
votedSkill[_tokenId].push(_values);
skillIndex++;
votesSkill[_tokenId][skillIndex] += balanceOf(msg.sender);
currentSkillVote[msg.sender][_tokenId] = skillIndex;
}
votesTotalSkill[_tokenId] += balanceOf(msg.sender);
currentSkillBalance[msg.sender][_tokenId] = balanceOf(msg.sender);
if (skillNumber[_tokenId] != skillCurrentNumber[msg.sender][_tokenId])
skillCurrentNumber[msg.sender][_tokenId] = skillNumber[_tokenId];
uint256 winner;
uint256 result;
if (votesTotalSkill[_tokenId] * 1000 >= ISettings(settingsContract).minSkillVotePercentage() * totalSupply()) {
for (uint i = 0; i < votedSkill[_tokenId].length; i++) {
if (votesSkill[_tokenId][i] > result) {
result = votesSkill[_tokenId][i];
winner = i;
}
votesSkill[_tokenId][i] = 0;
}
DiamondInterface(diamondContract).spendSkillPoints(_tokenId, votedSkill[_tokenId][winner]);
emit SkilledUp(_tokenId, votedSkill[_tokenId][winner]);
delete votedSkill[_tokenId];
skillNumber[_tokenId]++;
votesTotalSkill[_tokenId] = 0;
}
}
/// @notice vote for equipping an Aavegotchi with the selected items in the parameter _wearablesToEquip
function equipWearables(uint256 _tokenId, int16[16] calldata _wearablesToEquip) external {
require(balanceOf(msg.sender) > 0,
"equipWearables: only owners can use this function"
);
require(
auctionStatus == AuctionStatus.INACTIVE,
"equipWearables: auction live cannot equipe wearables"
);
if (fundingStatus = FundingStatus.SUBMITTED) {
require(
_tokenId != listingId,
"equipWearables: cannot equip a type of item being purchased"
);
}
DiamondInterface(diamondContract).equipWearables(_tokenId, _wearablesToEquip);
emit Equipped(_tokenId, _values);
}
/// @notice vote for using consumables on one or several Aavegotchis
function useConsumables(
uint256 _tokenId,
uint256[] calldata _itemIds,
uint256[] calldata _quantities
) external {
require(balanceOf(msg.sender) > 0,
"useConsumables: only owners can use this function"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"useConsumables: auction live cannot use consumables"
);
DiamondInterface(diamondContract).useConsumables(_tokenId, _itemIds, _quantities);
emit ConsumablesUsed(_tokenId, _itemIds, _quantities);
}
/// @notice vote for and appoint a new Player to play with the FrAactionHub's Aavegotchi(s) on behalf of the other owners
function voteForPlayer(address _player) external {
require(
balanceOf(_player) > 0,
"voteForPlayer: player not an owner of the FrAactionHub"
);
require(
finalAuctionStatus != FinalAuctionStatus.ENDED,
"voteForPlayer: cannot vote if an auction is ended"
);
require(
initialized == true,
"voteForPlayer: FrAactionHub not fractionalized yet"
);
require(
balanceOf(msg.sender) > 0,
"voteForPlayer: user not an owner of the NFT"
);
require(
gameType == 0, // 0 is for Delegated FrAactionHub, 1 for Collective FrAactionHub
"voteForPlayer: this FrAactionHub was set as Collective by its creator"
);
if (playerNumber != playerCurrentNumber[msg.sender]) {
votersPlayer[msg.sender] = 0;
currentPlayerVote[msg.sender] = 0;
currentPlayerBalance[msg.sender] = 0;
}
if (votersPlayer[msg.sender] == true) {
votesPlayer[currentPlayerVote[msg.sender]] -= currentPlayerBalance[msg.sender];
votesTotalPlayer -= currentPlayerBalance[msg.sender];
} else {
votersPlayer[msg.sender] = true;
}
votesPlayer[_player] += balanceOf(msg.sender);
votesTotalPlayer += balanceOf(msg.sender);
currentPlayerVote[msg.sender] = _player;
currentPlayerBalance[msg.sender] = balanceOf(msg.sender);
if (playerNumber != playerCurrentNumber[msg.sender]) playerCurrentNumber[msg.sender] = playerNumber;
address winner;
uint256 result;
if (votesTotalPlayer * 1000 >= ISettings(settingsContract).minPlayerVotePercentage() * totalSupply()) {
for (uint i = 0; i < ownersAddress.length; i++) {
if (votesPlayer[ownersAddress[i]] > result) {
result = votesPlayer[ownersAddress[i]];
winner = ownersAddress[i];
}
if (votesPlayer[ownersAddress[i]] != 0) votesPlayer[ownersAddress[i]] = 0;
}
player = winner;
playerNumber++;
votesTotalPlayer = 0;
DiamondInterface(diamondContract).setApprovalForAll(player, true);
emit AppointedPlayer(player);
}
}
function voteForDestruction(uint256 _tokenId, uint256 _xpToId) external {
require(balanceOf(msg.sender) > 0,
"voteForDestruction: only owners can vote"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"voteForDestruction: auction live cannot update price"
);
if (destroyNumber[_tokenId] != destroyCurrentNumber[msg.sender][_tokenId]) {
votersDestroy[msg.sender][_tokenId] = 0;
currentDestroyBalance[msg.sender][_tokenId] = 0;
}
if (votersDestroy[msg.sender][_tokenId] == true) {
votesTotalDestroy[_tokenId] -= currentDestroyBalance[msg.sender][_tokenId];
} else {
votersDestroy[msg.sender][_tokenId] = true;
}
votesTotalDestroy[_tokenId] += balanceOf(msg.sender);
currentDestroyBalance[msg.sender][_tokenId] = balanceOf(msg.sender);
if (xpToId[_tokenId] == 0) xpToId[tokenId] = _xpToId;
if (destroyNumber[_tokenId] != destroyCurrentNumber[msg.sender][_tokenId])
destroyCurrentNumber[msg.sender][_tokenId] = destroyNumber[_tokenId];
if (votesTotalDestroy[_tokenId] * 1000 >= ISettings(settingsContract).minDestroyVotePercentage() * totalSupply()) {
address collateral = DiamondInterface(diamondContract).collateralBalance(_tokenId).collateralType_;
uint256 balance = DiamondInterface(diamondContract).collateralBalance(_tokenId).balance_;
(bool success, bytes memory returnData) =
diamondContract.call(
abi.encodeWithSignature("decreaseAndDestroy(uint256,uint256)",
_tokenId,
xpToId
)
);
require(
success,
string(
abi.encodePacked(
"voteForDestruction: staking order failed: ",
returnData
)
)
);
redeemedCollateral[collateral].push(balance);
if (collateralToRedeem[collateral] == 0) {
collateralToRedeem[collateral] = true;
collateralAvailable.push(collateral);
}
emit Destroy(_tokenId);
destroyNumber[_tokenId]++;
votesTotalDestroy[_tokenId] = 0;
}
}
/// @notice an internal function used to register receiver previous FractionHub token balance, to be used in the _afterTokenTransfer function
/// @param _from the ERC20 token sender
/// @param _to the ERC20 token receiver
/// @param _amount the ERC20 token amount
function _beforeTokenTransfer(address _from, address _to, uint256 _amount) internal virtual override {
require (split != 7 && split != 8,
"beforeTokenTransfer: cannot transfer because ownership transfer or claimAll ongoing"
);
beforeTransferToBalance = balanceOf(_to);
}
/// @notice an internal function used to update the ownership register and update sender and receivers price after each FractionHub token transfer
/// @param _from the ERC20 token sender
/// @param _to the ERC20 token receiver
/// @param _amount the ERC20 token amount
function _afterTokenTransfer(address _from, address _to, uint256 _amount) internal virtual override {
address replace;
if (balanceOf(_from) == 0) {
if (beforeTransferToBalance == 0) {
replace = ownersAddress[ownersAddress.length - 1];
ownersAddress[ownerAddressIndex[_from]] = replace;
ownersAddress.pop();
ownerAddressIndex[replace] = ownerAddressIndex[_from];
delete ownerAddressIndex[_from];
} else {
ownersAddress[ownerAddressIndex[_from]] = _to;
ownerAddressIndex[_to] = ownerAddressIndex[_from];
delete ownerAddressIndex[_from];
}
}
if (balanceOf(_from) != 0 && beforeTransferToBalance == 0) {
ownersAddress.push(_to);
}
if (_from != address(0)) {
uint256 fromPrice = userPrices[_from];
uint256 toPrice = userPrices[_to];
// only do something if users have different reserve price
if (toPrice != fromPrice) {
// new holder is not a voter
if (toPrice == 0) {
// removing old holder's reserve price
votingTokens -= _amount;
reserveTotal -= _amount * fromPrice;
}
// old holder is not a voter
else if (fromPrice == 0) {
votingTokens += _amount;
reserveTotal += _amount * toPrice;
}
// both holders are voters
else {
reserveTotal = reserveTotal + (_amount * toPrice) - (_amount * fromPrice);
}
}
}
}
} | they no longer want to vote | else if (_new == 0) {
votingTokens -= weight;
reserveTotal -= weight * old;
}
| 5,359,749 | [
1,
451,
402,
1158,
7144,
2545,
358,
12501,
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,
469,
309,
261,
67,
2704,
422,
374,
13,
288,
203,
5411,
331,
17128,
5157,
3947,
3119,
31,
203,
5411,
20501,
5269,
3947,
3119,
380,
1592,
31,
203,
3639,
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
]
|
./partial_match/5/0x423DBa410C9d51fae8C34aFF803fbe1a356845dD/sources/lib/dss-test/lib/dss-interfaces/src/dss/FaucetAbstract.sol | ERROR: type should be string, got " https:github.com/makerdao/token-faucet/blob/master/src/RestrictedTokenFaucet.sol" | interface FaucetAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function list(address) external view returns (uint256);
function hope(address) external;
function nope(address) external;
function amt(address) external view returns (uint256);
function done(address, address) external view returns (bool);
function gulp(address) external;
function gulp(address, address[] calldata) external;
function shut(address) external;
function undo(address, address) external;
function setAmt(address, uint256) external;
pragma solidity >=0.5.12;
}
| 16,837,832 | [
1,
4528,
30,
6662,
18,
832,
19,
29261,
2414,
83,
19,
2316,
17,
507,
5286,
278,
19,
10721,
19,
7525,
19,
4816,
19,
18784,
1345,
29634,
5286,
278,
18,
18281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5831,
478,
69,
5286,
278,
7469,
288,
203,
565,
445,
341,
14727,
12,
2867,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
21187,
12,
2867,
13,
3903,
31,
203,
565,
445,
17096,
12,
2867,
13,
3903,
31,
203,
565,
445,
666,
12,
2867,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
27370,
12,
2867,
13,
3903,
31,
203,
565,
445,
1158,
347,
12,
2867,
13,
3903,
31,
203,
565,
445,
25123,
12,
2867,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
2731,
12,
2867,
16,
1758,
13,
3903,
1476,
1135,
261,
6430,
1769,
203,
565,
445,
18568,
12,
2867,
13,
3903,
31,
203,
565,
445,
18568,
12,
2867,
16,
1758,
8526,
745,
892,
13,
3903,
31,
203,
565,
445,
9171,
12,
2867,
13,
3903,
31,
203,
565,
445,
15436,
12,
2867,
16,
1758,
13,
3903,
31,
203,
565,
445,
444,
31787,
12,
2867,
16,
2254,
5034,
13,
3903,
31,
203,
683,
9454,
18035,
560,
1545,
20,
18,
25,
18,
2138,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/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);
}
/**
* @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.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit 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 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 SignedSafeMath
* @dev Signed math operations with safety checks that revert on error
*/
library SignedSafeMath {
int256 constant private INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// 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;
}
require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below
int256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0); // Solidity only automatically asserts when dividing by 0
require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
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.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
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(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
// The functionality that all derivative contracts expose to the admin.
interface AdminInterface {
// Initiates the shutdown process, in case of an emergency.
function emergencyShutdown() external;
// A core contract method called immediately before or after any financial transaction. It pays fees and moves money
// between margin accounts to make sure they reflect the NAV of the contract.
function remargin() external;
}
contract ExpandedIERC20 is IERC20 {
// Burns a specific amount of tokens. Burns the sender's tokens, so it is safe to leave this method permissionless.
function burn(uint value) external;
// Mints tokens and adds them to the balance of the `to` address.
// Note: this method should be permissioned to only allow designated parties to mint tokens.
function mint(address to, uint value) external;
}
// This interface allows derivative contracts to pay Oracle fees for their use of the system.
interface StoreInterface {
// Pays Oracle fees in ETH to the store. To be used by contracts whose margin currency is ETH.
function payOracleFees() external payable;
// Pays Oracle fees in the margin currency, erc20Address, to the store. To be used if the margin currency is an
// ERC20 token rather than ETH. All approved tokens are transfered.
function payOracleFeesErc20(address erc20Address) external;
// Computes the Oracle fees that a contract should pay for a period. `pfc` is the "profit from corruption", or the
// maximum amount of margin currency that a token sponsor could extract from the contract through corrupting the
// price feed in their favor.
function computeOracleFees(uint startTime, uint endTime, uint pfc) external view returns (uint feeAmount);
}
interface ReturnCalculatorInterface {
// Computes the return between oldPrice and newPrice.
function computeReturn(int oldPrice, int newPrice) external view returns (int assetReturn);
// Gets the effective leverage for the return calculator.
// Note: if this parameter doesn't exist for this calculator, this method should return 1.
function leverage() external view returns (int _leverage);
}
// This interface allows contracts to query unverified prices.
interface PriceFeedInterface {
// Whether this PriceFeeds provides prices for the given identifier.
function isIdentifierSupported(bytes32 identifier) external view returns (bool isSupported);
// Gets the latest time-price pair at which a price was published. The transaction will revert if no prices have
// been published for this identifier.
function latestPrice(bytes32 identifier) external view returns (uint publishTime, int price);
// An event fired when a price is published.
event PriceUpdated(bytes32 indexed identifier, uint indexed time, int price);
}
contract AddressWhitelist is Ownable {
enum Status { None, In, Out }
mapping(address => Status) private whitelist;
address[] private whitelistIndices;
// Adds an address to the whitelist
function addToWhitelist(address newElement) external onlyOwner {
// Ignore if address is already included
if (whitelist[newElement] == Status.In) {
return;
}
// Only append new addresses to the array, never a duplicate
if (whitelist[newElement] == Status.None) {
whitelistIndices.push(newElement);
}
whitelist[newElement] = Status.In;
emit AddToWhitelist(newElement);
}
// Removes an address from the whitelist.
function removeFromWhitelist(address elementToRemove) external onlyOwner {
if (whitelist[elementToRemove] != Status.Out) {
whitelist[elementToRemove] = Status.Out;
emit RemoveFromWhitelist(elementToRemove);
}
}
// Checks whether an address is on the whitelist.
function isOnWhitelist(address elementToCheck) external view returns (bool) {
return whitelist[elementToCheck] == Status.In;
}
// Gets all addresses that are currently included in the whitelist
// Note: This method skips over, but still iterates through addresses.
// It is possible for this call to run out of gas if a large number of
// addresses have been removed. To prevent this unlikely scenario, we can
// modify the implementation so that when addresses are removed, the last addresses
// in the array is moved to the empty index.
function getWhitelist() external view returns (address[] memory activeWhitelist) {
// Determine size of whitelist first
uint activeCount = 0;
for (uint i = 0; i < whitelistIndices.length; i++) {
if (whitelist[whitelistIndices[i]] == Status.In) {
activeCount++;
}
}
// Populate whitelist
activeWhitelist = new address[](activeCount);
activeCount = 0;
for (uint i = 0; i < whitelistIndices.length; i++) {
address addr = whitelistIndices[i];
if (whitelist[addr] == Status.In) {
activeWhitelist[activeCount] = addr;
activeCount++;
}
}
}
event AddToWhitelist(address indexed addedAddress);
event RemoveFromWhitelist(address indexed removedAddress);
}
contract Withdrawable is Ownable {
// Withdraws ETH from the contract.
function withdraw(uint amount) external onlyOwner {
msg.sender.transfer(amount);
}
// Withdraws ERC20 tokens from the contract.
function withdrawErc20(address erc20Address, uint amount) external onlyOwner {
IERC20 erc20 = IERC20(erc20Address);
require(erc20.transfer(msg.sender, amount));
}
}
// This interface allows contracts to query a verified, trusted price.
interface OracleInterface {
// Requests the Oracle price for an identifier at a time. Returns the time at which a price will be available.
// Returns 0 is the price is available now, and returns 2^256-1 if the price will never be available. Reverts if
// the Oracle doesn't support this identifier. Only contracts registered in the Registry are authorized to call this
// method.
function requestPrice(bytes32 identifier, uint time) external returns (uint expectedTime);
// Checks whether a price has been resolved.
function hasPrice(bytes32 identifier, uint time) external view returns (bool hasPriceAvailable);
// Returns the Oracle price for identifier at a time. Reverts if the Oracle doesn't support this identifier or if
// the Oracle doesn't have a price for this time. Only contracts registered in the Registry are authorized to call
// this method.
function getPrice(bytes32 identifier, uint time) external view returns (int price);
// Returns whether the Oracle provides verified prices for the given identifier.
function isIdentifierSupported(bytes32 identifier) external view returns (bool isSupported);
// An event fired when a request for a (identifier, time) pair is made.
event VerifiedPriceRequested(bytes32 indexed identifier, uint indexed time);
// An event fired when a verified price is available for a (identifier, time) pair.
event VerifiedPriceAvailable(bytes32 indexed identifier, uint indexed time, int price);
}
interface RegistryInterface {
struct RegisteredDerivative {
address derivativeAddress;
address derivativeCreator;
}
// Registers a new derivative. Only authorized derivative creators can call this method.
function registerDerivative(address[] calldata counterparties, address derivativeAddress) external;
// Adds a new derivative creator to this list of authorized creators. Only the owner of this contract can call
// this method.
function addDerivativeCreator(address derivativeCreator) external;
// Removes a derivative creator to this list of authorized creators. Only the owner of this contract can call this
// method.
function removeDerivativeCreator(address derivativeCreator) external;
// Returns whether the derivative has been registered with the registry (and is therefore an authorized participant
// in the UMA system).
function isDerivativeRegistered(address derivative) external view returns (bool isRegistered);
// Returns a list of all derivatives that are associated with a particular party.
function getRegisteredDerivatives(address party) external view returns (RegisteredDerivative[] memory derivatives);
// Returns all registered derivatives.
function getAllRegisteredDerivatives() external view returns (RegisteredDerivative[] memory derivatives);
// Returns whether an address is authorized to register new derivatives.
function isDerivativeCreatorAuthorized(address derivativeCreator) external view returns (bool isAuthorized);
}
contract Registry is RegistryInterface, Withdrawable {
using SafeMath for uint;
// Array of all registeredDerivatives that are approved to use the UMA Oracle.
RegisteredDerivative[] private registeredDerivatives;
// This enum is required because a WasValid state is required to ensure that derivatives cannot be re-registered.
enum PointerValidity {
Invalid,
Valid,
WasValid
}
struct Pointer {
PointerValidity valid;
uint128 index;
}
// Maps from derivative address to a pointer that refers to that RegisteredDerivative in registeredDerivatives.
mapping(address => Pointer) private derivativePointers;
// Note: this must be stored outside of the RegisteredDerivative because mappings cannot be deleted and copied
// like normal data. This could be stored in the Pointer struct, but storing it there would muddy the purpose
// of the Pointer struct and break separation of concern between referential data and data.
struct PartiesMap {
mapping(address => bool) parties;
}
// Maps from derivative address to the set of parties that are involved in that derivative.
mapping(address => PartiesMap) private derivativesToParties;
// Maps from derivative creator address to whether that derivative creator has been approved to register contracts.
mapping(address => bool) private derivativeCreators;
modifier onlyApprovedDerivativeCreator {
require(derivativeCreators[msg.sender]);
_;
}
function registerDerivative(address[] calldata parties, address derivativeAddress)
external
onlyApprovedDerivativeCreator
{
// Create derivative pointer.
Pointer storage pointer = derivativePointers[derivativeAddress];
// Ensure that the pointer was not valid in the past (derivatives cannot be re-registered or double
// registered).
require(pointer.valid == PointerValidity.Invalid);
pointer.valid = PointerValidity.Valid;
registeredDerivatives.push(RegisteredDerivative(derivativeAddress, msg.sender));
// No length check necessary because we should never hit (2^127 - 1) derivatives.
pointer.index = uint128(registeredDerivatives.length.sub(1));
// Set up PartiesMap for this derivative.
PartiesMap storage partiesMap = derivativesToParties[derivativeAddress];
for (uint i = 0; i < parties.length; i = i.add(1)) {
partiesMap.parties[parties[i]] = true;
}
address[] memory partiesForEvent = parties;
emit RegisterDerivative(derivativeAddress, partiesForEvent);
}
function addDerivativeCreator(address derivativeCreator) external onlyOwner {
if (!derivativeCreators[derivativeCreator]) {
derivativeCreators[derivativeCreator] = true;
emit AddDerivativeCreator(derivativeCreator);
}
}
function removeDerivativeCreator(address derivativeCreator) external onlyOwner {
if (derivativeCreators[derivativeCreator]) {
derivativeCreators[derivativeCreator] = false;
emit RemoveDerivativeCreator(derivativeCreator);
}
}
function isDerivativeRegistered(address derivative) external view returns (bool isRegistered) {
return derivativePointers[derivative].valid == PointerValidity.Valid;
}
function getRegisteredDerivatives(address party) external view returns (RegisteredDerivative[] memory derivatives) {
// This is not ideal - we must statically allocate memory arrays. To be safe, we make a temporary array as long
// as registeredDerivatives. We populate it with any derivatives that involve the provided party. Then, we copy
// the array over to the return array, which is allocated using the correct size. Note: this is done by double
// copying each value rather than storing some referential info (like indices) in memory to reduce the number
// of storage reads. This is because storage reads are far more expensive than extra memory space (~100:1).
RegisteredDerivative[] memory tmpDerivativeArray = new RegisteredDerivative[](registeredDerivatives.length);
uint outputIndex = 0;
for (uint i = 0; i < registeredDerivatives.length; i = i.add(1)) {
RegisteredDerivative storage derivative = registeredDerivatives[i];
if (derivativesToParties[derivative.derivativeAddress].parties[party]) {
// Copy selected derivative to the temporary array.
tmpDerivativeArray[outputIndex] = derivative;
outputIndex = outputIndex.add(1);
}
}
// Copy the temp array to the return array that is set to the correct size.
derivatives = new RegisteredDerivative[](outputIndex);
for (uint j = 0; j < outputIndex; j = j.add(1)) {
derivatives[j] = tmpDerivativeArray[j];
}
}
function getAllRegisteredDerivatives() external view returns (RegisteredDerivative[] memory derivatives) {
return registeredDerivatives;
}
function isDerivativeCreatorAuthorized(address derivativeCreator) external view returns (bool isAuthorized) {
return derivativeCreators[derivativeCreator];
}
event RegisterDerivative(address indexed derivativeAddress, address[] parties);
event AddDerivativeCreator(address indexed addedDerivativeCreator);
event RemoveDerivativeCreator(address indexed removedDerivativeCreator);
}
contract Testable is Ownable {
// Is the contract being run on the test network. Note: this variable should be set on construction and never
// modified.
bool public isTest;
uint private currentTime;
constructor(bool _isTest) internal {
isTest = _isTest;
if (_isTest) {
currentTime = now; // solhint-disable-line not-rely-on-time
}
}
modifier onlyIfTest {
require(isTest);
_;
}
function setCurrentTime(uint _time) external onlyOwner onlyIfTest {
currentTime = _time;
}
function getCurrentTime() public view returns (uint) {
if (isTest) {
return currentTime;
} else {
return now; // solhint-disable-line not-rely-on-time
}
}
}
contract ContractCreator is Withdrawable {
Registry internal registry;
address internal oracleAddress;
address internal storeAddress;
address internal priceFeedAddress;
constructor(address registryAddress, address _oracleAddress, address _storeAddress, address _priceFeedAddress)
public
{
registry = Registry(registryAddress);
oracleAddress = _oracleAddress;
storeAddress = _storeAddress;
priceFeedAddress = _priceFeedAddress;
}
function _registerContract(address[] memory parties, address contractToRegister) internal {
registry.registerDerivative(parties, contractToRegister);
}
}
library TokenizedDerivativeParams {
enum ReturnType {
Linear,
Compound
}
struct ConstructorParams {
address sponsor;
address admin;
address oracle;
address store;
address priceFeed;
uint defaultPenalty; // Percentage of margin requirement * 10^18
uint supportedMove; // Expected percentage move in the underlying price that the long is protected against.
bytes32 product;
uint fixedYearlyFee; // Percentage of nav * 10^18
uint disputeDeposit; // Percentage of margin requirement * 10^18
address returnCalculator;
uint startingTokenPrice;
uint expiry;
address marginCurrency;
uint withdrawLimit; // Percentage of derivativeStorage.shortBalance * 10^18
ReturnType returnType;
uint startingUnderlyingPrice;
uint creationTime;
}
}
// TokenizedDerivativeStorage: this library name is shortened due to it being used so often.
library TDS {
enum State {
// The contract is active, and tokens can be created and redeemed. Margin can be added and withdrawn (as long as
// it exceeds required levels). Remargining is allowed. Created contracts immediately begin in this state.
// Possible state transitions: Disputed, Expired, Defaulted.
Live,
// Disputed, Expired, Defaulted, and Emergency are Frozen states. In a Frozen state, the contract is frozen in
// time awaiting a resolution by the Oracle. No tokens can be created or redeemed. Margin cannot be withdrawn.
// The resolution of these states moves the contract to the Settled state. Remargining is not allowed.
// The derivativeStorage.externalAddresses.sponsor has disputed the price feed output. If the dispute is valid (i.e., the NAV calculated from the
// Oracle price differs from the NAV calculated from the price feed), the dispute fee is added to the short
// account. Otherwise, the dispute fee is added to the long margin account.
// Possible state transitions: Settled.
Disputed,
// Contract expiration has been reached.
// Possible state transitions: Settled.
Expired,
// The short margin account is below its margin requirement. The derivativeStorage.externalAddresses.sponsor can choose to confirm the default and
// move to Settle without waiting for the Oracle. Default penalties will be assessed when the contract moves to
// Settled.
// Possible state transitions: Settled.
Defaulted,
// UMA has manually triggered a shutdown of the account.
// Possible state transitions: Settled.
Emergency,
// Token price is fixed. Tokens can be redeemed by anyone. All short margin can be withdrawn. Tokens can't be
// created, and contract can't remargin.
// Possible state transitions: None.
Settled
}
// The state of the token at a particular time. The state gets updated on remargin.
struct TokenState {
int underlyingPrice;
int tokenPrice;
uint time;
}
// The information in the following struct is only valid if in the midst of a Dispute.
struct Dispute {
int disputedNav;
uint deposit;
}
struct WithdrawThrottle {
uint startTime;
uint remainingWithdrawal;
}
struct FixedParameters {
// Fixed contract parameters.
uint defaultPenalty; // Percentage of margin requirement * 10^18
uint supportedMove; // Expected percentage move that the long is protected against.
uint disputeDeposit; // Percentage of margin requirement * 10^18
uint fixedFeePerSecond; // Percentage of nav*10^18
uint withdrawLimit; // Percentage of derivativeStorage.shortBalance*10^18
bytes32 product;
TokenizedDerivativeParams.ReturnType returnType;
uint initialTokenUnderlyingRatio;
uint creationTime;
string symbol;
}
struct ExternalAddresses {
// Other addresses/contracts
address sponsor;
address admin;
address apDelegate;
OracleInterface oracle;
StoreInterface store;
PriceFeedInterface priceFeed;
ReturnCalculatorInterface returnCalculator;
IERC20 marginCurrency;
}
struct Storage {
FixedParameters fixedParameters;
ExternalAddresses externalAddresses;
// Balances
int shortBalance;
int longBalance;
State state;
uint endTime;
// The NAV of the contract always reflects the transition from (`prev`, `current`).
// In the case of a remargin, a `latest` price is retrieved from the price feed, and we shift `current` -> `prev`
// and `latest` -> `current` (and then recompute).
// In the case of a dispute, `current` might change (which is why we have to hold on to `prev`).
TokenState referenceTokenState;
TokenState currentTokenState;
int nav; // Net asset value is measured in Wei
Dispute disputeInfo;
// Only populated once the contract enters a frozen state.
int defaultPenaltyAmount;
WithdrawThrottle withdrawThrottle;
}
}
library TokenizedDerivativeUtils {
using TokenizedDerivativeUtils for TDS.Storage;
using SafeMath for uint;
using SignedSafeMath for int;
uint private constant SECONDS_PER_DAY = 86400;
uint private constant SECONDS_PER_YEAR = 31536000;
uint private constant INT_MAX = 2**255 - 1;
uint private constant UINT_FP_SCALING_FACTOR = 10**18;
int private constant INT_FP_SCALING_FACTOR = 10**18;
modifier onlySponsor(TDS.Storage storage s) {
require(msg.sender == s.externalAddresses.sponsor);
_;
}
modifier onlyAdmin(TDS.Storage storage s) {
require(msg.sender == s.externalAddresses.admin);
_;
}
modifier onlySponsorOrAdmin(TDS.Storage storage s) {
require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.admin);
_;
}
modifier onlySponsorOrApDelegate(TDS.Storage storage s) {
require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.apDelegate);
_;
}
// Contract initializer. Should only be called at construction.
// Note: Must be a public function because structs cannot be passed as calldata (required data type for external
// functions).
function _initialize(
TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params, string memory symbol) public {
s._setFixedParameters(params, symbol);
s._setExternalAddresses(params);
// Keep the starting token price relatively close to FP_SCALING_FACTOR to prevent users from unintentionally
// creating rounding or overflow errors.
require(params.startingTokenPrice >= UINT_FP_SCALING_FACTOR.div(10**9));
require(params.startingTokenPrice <= UINT_FP_SCALING_FACTOR.mul(10**9));
// TODO(mrice32): we should have an ideal start time rather than blindly polling.
(uint latestTime, int latestUnderlyingPrice) = s.externalAddresses.priceFeed.latestPrice(s.fixedParameters.product);
// If nonzero, take the user input as the starting price.
if (params.startingUnderlyingPrice != 0) {
latestUnderlyingPrice = _safeIntCast(params.startingUnderlyingPrice);
}
require(latestUnderlyingPrice > 0);
require(latestTime != 0);
// Keep the ratio in case it's needed for margin computation.
s.fixedParameters.initialTokenUnderlyingRatio = params.startingTokenPrice.mul(UINT_FP_SCALING_FACTOR).div(_safeUintCast(latestUnderlyingPrice));
require(s.fixedParameters.initialTokenUnderlyingRatio != 0);
// Set end time to max value of uint to implement no expiry.
if (params.expiry == 0) {
s.endTime = ~uint(0);
} else {
require(params.expiry >= latestTime);
s.endTime = params.expiry;
}
s.nav = s._computeInitialNav(latestUnderlyingPrice, latestTime, params.startingTokenPrice);
s.state = TDS.State.Live;
}
function _depositAndCreateTokens(TDS.Storage storage s, uint marginForPurchase, uint tokensToPurchase) external onlySponsorOrApDelegate(s) {
s._remarginInternal();
int newTokenNav = _computeNavForTokens(s.currentTokenState.tokenPrice, tokensToPurchase);
if (newTokenNav < 0) {
newTokenNav = 0;
}
uint positiveTokenNav = _safeUintCast(newTokenNav);
// Get any refund due to sending more margin than the argument indicated (should only be able to happen in the
// ETH case).
uint refund = s._pullSentMargin(marginForPurchase);
// Subtract newTokenNav from amount sent.
uint depositAmount = marginForPurchase.sub(positiveTokenNav);
// Deposit additional margin into the short account.
s._depositInternal(depositAmount);
// The _createTokensInternal call returns any refund due to the amount sent being larger than the amount
// required to purchase the tokens, so we add that to the running refund. This should be 0 in this case,
// but we leave this here in case of some refund being generated due to rounding errors or any bugs to ensure
// the sender never loses money.
refund = refund.add(s._createTokensInternal(tokensToPurchase, positiveTokenNav));
// Send the accumulated refund.
s._sendMargin(refund);
}
function _redeemTokens(TDS.Storage storage s, uint tokensToRedeem) external {
require(s.state == TDS.State.Live || s.state == TDS.State.Settled);
require(tokensToRedeem > 0);
if (s.state == TDS.State.Live) {
require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.apDelegate);
s._remarginInternal();
require(s.state == TDS.State.Live);
}
ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this));
uint initialSupply = _totalSupply();
require(initialSupply > 0);
_pullAuthorizedTokens(thisErc20Token, tokensToRedeem);
thisErc20Token.burn(tokensToRedeem);
emit TokensRedeemed(s.fixedParameters.symbol, tokensToRedeem);
// Value of the tokens is just the percentage of all the tokens multiplied by the balance of the investor
// margin account.
uint tokenPercentage = tokensToRedeem.mul(UINT_FP_SCALING_FACTOR).div(initialSupply);
uint tokenMargin = _takePercentage(_safeUintCast(s.longBalance), tokenPercentage);
s.longBalance = s.longBalance.sub(_safeIntCast(tokenMargin));
assert(s.longBalance >= 0);
s.nav = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply());
s._sendMargin(tokenMargin);
}
function _dispute(TDS.Storage storage s, uint depositMargin) external onlySponsor(s) {
require(
s.state == TDS.State.Live,
"Contract must be Live to dispute"
);
uint requiredDeposit = _safeUintCast(_takePercentage(s._getRequiredMargin(s.currentTokenState), s.fixedParameters.disputeDeposit));
uint sendInconsistencyRefund = s._pullSentMargin(depositMargin);
require(depositMargin >= requiredDeposit);
uint overpaymentRefund = depositMargin.sub(requiredDeposit);
s.state = TDS.State.Disputed;
s.endTime = s.currentTokenState.time;
s.disputeInfo.disputedNav = s.nav;
s.disputeInfo.deposit = requiredDeposit;
// Store the default penalty in case the dispute pushes the sponsor into default.
s.defaultPenaltyAmount = s._computeDefaultPenalty();
emit Disputed(s.fixedParameters.symbol, s.endTime, s.nav);
s._requestOraclePrice(s.endTime);
// Add the two types of refunds:
// 1. The refund for ETH sent if it was > depositMargin.
// 2. The refund for depositMargin > requiredDeposit.
s._sendMargin(sendInconsistencyRefund.add(overpaymentRefund));
}
function _withdraw(TDS.Storage storage s, uint amount) external onlySponsor(s) {
// Remargin before allowing a withdrawal, but only if in the live state.
if (s.state == TDS.State.Live) {
s._remarginInternal();
}
// Make sure either in Live or Settled after any necessary remargin.
require(s.state == TDS.State.Live || s.state == TDS.State.Settled);
// If the contract has been settled or is in prefunded state then can
// withdraw up to full balance. If the contract is in live state then
// must leave at least the required margin. Not allowed to withdraw in
// other states.
int withdrawableAmount;
if (s.state == TDS.State.Settled) {
withdrawableAmount = s.shortBalance;
} else {
// Update throttling snapshot and verify that this withdrawal doesn't go past the throttle limit.
uint currentTime = s.currentTokenState.time;
if (s.withdrawThrottle.startTime <= currentTime.sub(SECONDS_PER_DAY)) {
// We've passed the previous s.withdrawThrottle window. Start new one.
s.withdrawThrottle.startTime = currentTime;
s.withdrawThrottle.remainingWithdrawal = _takePercentage(_safeUintCast(s.shortBalance), s.fixedParameters.withdrawLimit);
}
int marginMaxWithdraw = s.shortBalance.sub(s._getRequiredMargin(s.currentTokenState));
int throttleMaxWithdraw = _safeIntCast(s.withdrawThrottle.remainingWithdrawal);
// Take the smallest of the two withdrawal limits.
withdrawableAmount = throttleMaxWithdraw < marginMaxWithdraw ? throttleMaxWithdraw : marginMaxWithdraw;
// Note: this line alone implicitly ensures the withdrawal throttle is not violated, but the above
// ternary is more explicit.
s.withdrawThrottle.remainingWithdrawal = s.withdrawThrottle.remainingWithdrawal.sub(amount);
}
// Can only withdraw the allowed amount.
require(
withdrawableAmount >= _safeIntCast(amount),
"Attempting to withdraw more than allowed"
);
// Transfer amount - Note: important to `-=` before the send so that the
// function can not be called multiple times while waiting for transfer
// to return.
s.shortBalance = s.shortBalance.sub(_safeIntCast(amount));
emit Withdrawal(s.fixedParameters.symbol, amount);
s._sendMargin(amount);
}
function _acceptPriceAndSettle(TDS.Storage storage s) external onlySponsor(s) {
// Right now, only confirming prices in the defaulted state.
require(s.state == TDS.State.Defaulted);
// Remargin on agreed upon price.
s._settleAgreedPrice();
}
function _setApDelegate(TDS.Storage storage s, address _apDelegate) external onlySponsor(s) {
s.externalAddresses.apDelegate = _apDelegate;
}
// Moves the contract into the Emergency state, where it waits on an Oracle price for the most recent remargin time.
function _emergencyShutdown(TDS.Storage storage s) external onlyAdmin(s) {
require(s.state == TDS.State.Live);
s.state = TDS.State.Emergency;
s.endTime = s.currentTokenState.time;
s.defaultPenaltyAmount = s._computeDefaultPenalty();
emit EmergencyShutdownTransition(s.fixedParameters.symbol, s.endTime);
s._requestOraclePrice(s.endTime);
}
function _settle(TDS.Storage storage s) external {
s._settleInternal();
}
function _createTokens(TDS.Storage storage s, uint marginForPurchase, uint tokensToPurchase) external onlySponsorOrApDelegate(s) {
// Returns any refund due to sending more margin than the argument indicated (should only be able to happen in
// the ETH case).
uint refund = s._pullSentMargin(marginForPurchase);
// The _createTokensInternal call returns any refund due to the amount sent being larger than the amount
// required to purchase the tokens, so we add that to the running refund.
refund = refund.add(s._createTokensInternal(tokensToPurchase, marginForPurchase));
// Send the accumulated refund.
s._sendMargin(refund);
}
function _deposit(TDS.Storage storage s, uint marginToDeposit) external onlySponsor(s) {
// Only allow the s.externalAddresses.sponsor to deposit margin.
uint refund = s._pullSentMargin(marginToDeposit);
s._depositInternal(marginToDeposit);
// Send any refund due to sending more margin than the argument indicated (should only be able to happen in the
// ETH case).
s._sendMargin(refund);
}
// Returns the expected net asset value (NAV) of the contract using the latest available Price Feed price.
function _calcNAV(TDS.Storage storage s) external view returns (int navNew) {
(TDS.TokenState memory newTokenState, ) = s._calcNewTokenStateAndBalance();
navNew = _computeNavForTokens(newTokenState.tokenPrice, _totalSupply());
}
// Returns the expected value of each the outstanding tokens of the contract using the latest available Price Feed
// price.
function _calcTokenValue(TDS.Storage storage s) external view returns (int newTokenValue) {
(TDS.TokenState memory newTokenState,) = s._calcNewTokenStateAndBalance();
newTokenValue = newTokenState.tokenPrice;
}
// Returns the expected balance of the short margin account using the latest available Price Feed price.
function _calcShortMarginBalance(TDS.Storage storage s) external view returns (int newShortMarginBalance) {
(, newShortMarginBalance) = s._calcNewTokenStateAndBalance();
}
function _calcExcessMargin(TDS.Storage storage s) external view returns (int newExcessMargin) {
(TDS.TokenState memory newTokenState, int newShortMarginBalance) = s._calcNewTokenStateAndBalance();
// If the contract is in/will be moved to a settled state, the margin requirement will be 0.
int requiredMargin = newTokenState.time >= s.endTime ? 0 : s._getRequiredMargin(newTokenState);
return newShortMarginBalance.sub(requiredMargin);
}
function _getCurrentRequiredMargin(TDS.Storage storage s) external view returns (int requiredMargin) {
if (s.state == TDS.State.Settled) {
// No margin needs to be maintained when the contract is settled.
return 0;
}
return s._getRequiredMargin(s.currentTokenState);
}
function _canBeSettled(TDS.Storage storage s) external view returns (bool canBeSettled) {
TDS.State currentState = s.state;
if (currentState == TDS.State.Settled) {
return false;
}
// Technically we should also check if price will default the contract, but that isn't a normal flow of
// operations that we want to simulate: we want to discourage the sponsor remargining into a default.
(uint priceFeedTime, ) = s._getLatestPrice();
if (currentState == TDS.State.Live && (priceFeedTime < s.endTime)) {
return false;
}
return s.externalAddresses.oracle.hasPrice(s.fixedParameters.product, s.endTime);
}
function _getUpdatedUnderlyingPrice(TDS.Storage storage s) external view returns (int underlyingPrice, uint time) {
(TDS.TokenState memory newTokenState, ) = s._calcNewTokenStateAndBalance();
return (newTokenState.underlyingPrice, newTokenState.time);
}
function _calcNewTokenStateAndBalance(TDS.Storage storage s) internal view returns (TDS.TokenState memory newTokenState, int newShortMarginBalance)
{
// TODO: there's a lot of repeated logic in this method from elsewhere in the contract. It should be extracted
// so the logic can be written once and used twice. However, much of this was written post-audit, so it was
// deemed preferable not to modify any state changing code that could potentially introduce new security
// bugs. This should be done before the next contract audit.
if (s.state == TDS.State.Settled) {
// If the contract is Settled, just return the current contract state.
return (s.currentTokenState, s.shortBalance);
}
// Grab the price feed pricetime.
(uint priceFeedTime, int priceFeedPrice) = s._getLatestPrice();
bool isContractLive = s.state == TDS.State.Live;
bool isContractPostExpiry = priceFeedTime >= s.endTime;
// If the time hasn't advanced since the last remargin, short circuit and return the most recently computed values.
if (isContractLive && priceFeedTime <= s.currentTokenState.time) {
return (s.currentTokenState, s.shortBalance);
}
// Determine which previous price state to use when computing the new NAV.
// If the contract is live, we use the reference for the linear return type or if the contract will immediately
// move to expiry.
bool shouldUseReferenceTokenState = isContractLive &&
(s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear || isContractPostExpiry);
TDS.TokenState memory lastTokenState = shouldUseReferenceTokenState ? s.referenceTokenState : s.currentTokenState;
// Use the oracle settlement price/time if the contract is frozen or will move to expiry on the next remargin.
(uint recomputeTime, int recomputePrice) = !isContractLive || isContractPostExpiry ?
(s.endTime, s.externalAddresses.oracle.getPrice(s.fixedParameters.product, s.endTime)) :
(priceFeedTime, priceFeedPrice);
// Init the returned short balance to the current short balance.
newShortMarginBalance = s.shortBalance;
// Subtract the oracle fees from the short balance.
newShortMarginBalance = isContractLive ?
newShortMarginBalance.sub(
_safeIntCast(s._computeExpectedOracleFees(s.currentTokenState.time, recomputeTime))) :
newShortMarginBalance;
// Compute the new NAV
newTokenState = s._computeNewTokenState(lastTokenState, recomputePrice, recomputeTime);
int navNew = _computeNavForTokens(newTokenState.tokenPrice, _totalSupply());
newShortMarginBalance = newShortMarginBalance.sub(_getLongDiff(navNew, s.longBalance, newShortMarginBalance));
// If the contract is frozen or will move into expiry, we need to settle it, which means adding the default
// penalty and dispute deposit if necessary.
if (!isContractLive || isContractPostExpiry) {
// Subtract default penalty (if necessary) from the short balance.
bool inDefault = !s._satisfiesMarginRequirement(newShortMarginBalance, newTokenState);
if (inDefault) {
int expectedDefaultPenalty = isContractLive ? s._computeDefaultPenalty() : s._getDefaultPenalty();
int defaultPenalty = (newShortMarginBalance < expectedDefaultPenalty) ?
newShortMarginBalance :
expectedDefaultPenalty;
newShortMarginBalance = newShortMarginBalance.sub(defaultPenalty);
}
// Add the dispute deposit to the short balance if necessary.
if (s.state == TDS.State.Disputed && navNew != s.disputeInfo.disputedNav) {
int depositValue = _safeIntCast(s.disputeInfo.deposit);
newShortMarginBalance = newShortMarginBalance.add(depositValue);
}
}
}
function _computeInitialNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime, uint startingTokenPrice)
internal
returns (int navNew)
{
int unitNav = _safeIntCast(startingTokenPrice);
s.referenceTokenState = TDS.TokenState(latestUnderlyingPrice, unitNav, latestTime);
s.currentTokenState = TDS.TokenState(latestUnderlyingPrice, unitNav, latestTime);
// Starting NAV is always 0 in the TokenizedDerivative case.
navNew = 0;
}
function _remargin(TDS.Storage storage s) external onlySponsorOrAdmin(s) {
s._remarginInternal();
}
function _withdrawUnexpectedErc20(TDS.Storage storage s, address erc20Address, uint amount) external onlySponsor(s) {
if(address(s.externalAddresses.marginCurrency) == erc20Address) {
uint currentBalance = s.externalAddresses.marginCurrency.balanceOf(address(this));
int totalBalances = s.shortBalance.add(s.longBalance);
assert(totalBalances >= 0);
uint withdrawableAmount = currentBalance.sub(_safeUintCast(totalBalances)).sub(s.disputeInfo.deposit);
require(withdrawableAmount >= amount);
}
IERC20 erc20 = IERC20(erc20Address);
require(erc20.transfer(msg.sender, amount));
}
function _setExternalAddresses(TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params) internal {
// Note: not all "ERC20" tokens conform exactly to this interface (BNB, OMG, etc). The most common way that
// tokens fail to conform is that they do not return a bool from certain state-changing operations. This
// contract was not designed to work with those tokens because of the additional complexity they would
// introduce.
s.externalAddresses.marginCurrency = IERC20(params.marginCurrency);
s.externalAddresses.oracle = OracleInterface(params.oracle);
s.externalAddresses.store = StoreInterface(params.store);
s.externalAddresses.priceFeed = PriceFeedInterface(params.priceFeed);
s.externalAddresses.returnCalculator = ReturnCalculatorInterface(params.returnCalculator);
// Verify that the price feed and s.externalAddresses.oracle support the given s.fixedParameters.product.
require(s.externalAddresses.oracle.isIdentifierSupported(params.product));
require(s.externalAddresses.priceFeed.isIdentifierSupported(params.product));
s.externalAddresses.sponsor = params.sponsor;
s.externalAddresses.admin = params.admin;
}
function _setFixedParameters(TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params, string memory symbol) internal {
// Ensure only valid enum values are provided.
require(params.returnType == TokenizedDerivativeParams.ReturnType.Compound
|| params.returnType == TokenizedDerivativeParams.ReturnType.Linear);
// Fee must be 0 if the returnType is linear.
require(params.returnType == TokenizedDerivativeParams.ReturnType.Compound || params.fixedYearlyFee == 0);
// The default penalty must be less than the required margin.
require(params.defaultPenalty <= UINT_FP_SCALING_FACTOR);
s.fixedParameters.returnType = params.returnType;
s.fixedParameters.defaultPenalty = params.defaultPenalty;
s.fixedParameters.product = params.product;
s.fixedParameters.fixedFeePerSecond = params.fixedYearlyFee.div(SECONDS_PER_YEAR);
s.fixedParameters.disputeDeposit = params.disputeDeposit;
s.fixedParameters.supportedMove = params.supportedMove;
s.fixedParameters.withdrawLimit = params.withdrawLimit;
s.fixedParameters.creationTime = params.creationTime;
s.fixedParameters.symbol = symbol;
}
// _remarginInternal() allows other functions to call remargin internally without satisfying permission checks for
// _remargin().
function _remarginInternal(TDS.Storage storage s) internal {
// If the state is not live, remargining does not make sense.
require(s.state == TDS.State.Live);
(uint latestTime, int latestPrice) = s._getLatestPrice();
// Checks whether contract has ended.
if (latestTime <= s.currentTokenState.time) {
// If the price feed hasn't advanced, remargining should be a no-op.
return;
}
// Save the penalty using the current state in case it needs to be used.
int potentialPenaltyAmount = s._computeDefaultPenalty();
if (latestTime >= s.endTime) {
s.state = TDS.State.Expired;
emit Expired(s.fixedParameters.symbol, s.endTime);
// Applies the same update a second time to effectively move the current state to the reference state.
int recomputedNav = s._computeNav(s.currentTokenState.underlyingPrice, s.currentTokenState.time);
assert(recomputedNav == s.nav);
uint feeAmount = s._deductOracleFees(s.currentTokenState.time, s.endTime);
// Save the precomputed default penalty in case the expiry price pushes the sponsor into default.
s.defaultPenaltyAmount = potentialPenaltyAmount;
// We have no idea what the price was, exactly at s.endTime, so we can't set
// s.currentTokenState, or update the nav, or do anything.
s._requestOraclePrice(s.endTime);
s._payOracleFees(feeAmount);
return;
}
uint feeAmount = s._deductOracleFees(s.currentTokenState.time, latestTime);
// Update nav of contract.
int navNew = s._computeNav(latestPrice, latestTime);
// Update the balances of the contract.
s._updateBalances(navNew);
// Make sure contract has not moved into default.
bool inDefault = !s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState);
if (inDefault) {
s.state = TDS.State.Defaulted;
s.defaultPenaltyAmount = potentialPenaltyAmount;
s.endTime = latestTime; // Change end time to moment when default occurred.
emit Default(s.fixedParameters.symbol, latestTime, s.nav);
s._requestOraclePrice(latestTime);
}
s._payOracleFees(feeAmount);
}
function _createTokensInternal(TDS.Storage storage s, uint tokensToPurchase, uint navSent) internal returns (uint refund) {
s._remarginInternal();
// Verify that remargining didn't push the contract into expiry or default.
require(s.state == TDS.State.Live);
int purchasedNav = _computeNavForTokens(s.currentTokenState.tokenPrice, tokensToPurchase);
if (purchasedNav < 0) {
purchasedNav = 0;
}
// Ensures that requiredNav >= navSent.
refund = navSent.sub(_safeUintCast(purchasedNav));
s.longBalance = s.longBalance.add(purchasedNav);
ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this));
thisErc20Token.mint(msg.sender, tokensToPurchase);
emit TokensCreated(s.fixedParameters.symbol, tokensToPurchase);
s.nav = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply());
// Make sure this still satisfies the margin requirement.
require(s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState));
}
function _depositInternal(TDS.Storage storage s, uint value) internal {
// Make sure that we are in a "depositable" state.
require(s.state == TDS.State.Live);
s.shortBalance = s.shortBalance.add(_safeIntCast(value));
emit Deposited(s.fixedParameters.symbol, value);
}
function _settleInternal(TDS.Storage storage s) internal {
TDS.State startingState = s.state;
require(startingState == TDS.State.Disputed || startingState == TDS.State.Expired
|| startingState == TDS.State.Defaulted || startingState == TDS.State.Emergency);
s._settleVerifiedPrice();
if (startingState == TDS.State.Disputed) {
int depositValue = _safeIntCast(s.disputeInfo.deposit);
if (s.nav != s.disputeInfo.disputedNav) {
s.shortBalance = s.shortBalance.add(depositValue);
} else {
s.longBalance = s.longBalance.add(depositValue);
}
}
}
// Deducts the fees from the margin account.
function _deductOracleFees(TDS.Storage storage s, uint lastTimeOracleFeesPaid, uint currentTime) internal returns (uint feeAmount) {
feeAmount = s._computeExpectedOracleFees(lastTimeOracleFeesPaid, currentTime);
s.shortBalance = s.shortBalance.sub(_safeIntCast(feeAmount));
// If paying the Oracle fee reduces the held margin below requirements, the rest of remargin() will default the
// contract.
}
// Pays out the fees to the Oracle.
function _payOracleFees(TDS.Storage storage s, uint feeAmount) internal {
if (feeAmount == 0) {
return;
}
if (address(s.externalAddresses.marginCurrency) == address(0x0)) {
s.externalAddresses.store.payOracleFees.value(feeAmount)();
} else {
require(s.externalAddresses.marginCurrency.approve(address(s.externalAddresses.store), feeAmount));
s.externalAddresses.store.payOracleFeesErc20(address(s.externalAddresses.marginCurrency));
}
}
function _computeExpectedOracleFees(TDS.Storage storage s, uint lastTimeOracleFeesPaid, uint currentTime)
internal
view
returns (uint feeAmount)
{
// The profit from corruption is set as the max(longBalance, shortBalance).
int pfc = s.shortBalance < s.longBalance ? s.longBalance : s.shortBalance;
uint expectedFeeAmount = s.externalAddresses.store.computeOracleFees(lastTimeOracleFeesPaid, currentTime, _safeUintCast(pfc));
// Ensure the fee returned can actually be paid by the short margin account.
uint shortBalance = _safeUintCast(s.shortBalance);
return (shortBalance < expectedFeeAmount) ? shortBalance : expectedFeeAmount;
}
function _computeNewTokenState(TDS.Storage storage s,
TDS.TokenState memory beginningTokenState, int latestUnderlyingPrice, uint recomputeTime)
internal
view
returns (TDS.TokenState memory newTokenState)
{
int underlyingReturn = s.externalAddresses.returnCalculator.computeReturn(
beginningTokenState.underlyingPrice, latestUnderlyingPrice);
int tokenReturn = underlyingReturn.sub(
_safeIntCast(s.fixedParameters.fixedFeePerSecond.mul(recomputeTime.sub(beginningTokenState.time))));
int tokenMultiplier = tokenReturn.add(INT_FP_SCALING_FACTOR);
// In the compound case, don't allow the token price to go below 0.
if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Compound && tokenMultiplier < 0) {
tokenMultiplier = 0;
}
int newTokenPrice = _takePercentage(beginningTokenState.tokenPrice, tokenMultiplier);
newTokenState = TDS.TokenState(latestUnderlyingPrice, newTokenPrice, recomputeTime);
}
function _satisfiesMarginRequirement(TDS.Storage storage s, int balance, TDS.TokenState memory tokenState)
internal
view
returns (bool doesSatisfyRequirement)
{
return s._getRequiredMargin(tokenState) <= balance;
}
function _requestOraclePrice(TDS.Storage storage s, uint requestedTime) internal {
uint expectedTime = s.externalAddresses.oracle.requestPrice(s.fixedParameters.product, requestedTime);
if (expectedTime == 0) {
// The Oracle price is already available, settle the contract right away.
s._settleInternal();
}
}
function _getLatestPrice(TDS.Storage storage s) internal view returns (uint latestTime, int latestUnderlyingPrice) {
(latestTime, latestUnderlyingPrice) = s.externalAddresses.priceFeed.latestPrice(s.fixedParameters.product);
require(latestTime != 0);
}
function _computeNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) {
if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Compound) {
navNew = s._computeCompoundNav(latestUnderlyingPrice, latestTime);
} else {
assert(s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear);
navNew = s._computeLinearNav(latestUnderlyingPrice, latestTime);
}
}
function _computeCompoundNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) {
s.referenceTokenState = s.currentTokenState;
s.currentTokenState = s._computeNewTokenState(s.currentTokenState, latestUnderlyingPrice, latestTime);
navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply());
emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice);
}
function _computeLinearNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) {
// Only update the time - don't update the prices becuase all price changes are relative to the initial price.
s.referenceTokenState.time = s.currentTokenState.time;
s.currentTokenState = s._computeNewTokenState(s.referenceTokenState, latestUnderlyingPrice, latestTime);
navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply());
emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice);
}
function _recomputeNav(TDS.Storage storage s, int oraclePrice, uint recomputeTime) internal returns (int navNew) {
// We're updating `last` based on what the Oracle has told us.
assert(s.endTime == recomputeTime);
s.currentTokenState = s._computeNewTokenState(s.referenceTokenState, oraclePrice, recomputeTime);
navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply());
emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice);
}
// Function is internally only called by `_settleAgreedPrice` or `_settleVerifiedPrice`. This function handles all
// of the settlement logic including assessing penalties and then moves the state to `Settled`.
function _settleWithPrice(TDS.Storage storage s, int price) internal {
// Remargin at whatever price we're using (verified or unverified).
s._updateBalances(s._recomputeNav(price, s.endTime));
bool inDefault = !s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState);
if (inDefault) {
int expectedDefaultPenalty = s._getDefaultPenalty();
int penalty = (s.shortBalance < expectedDefaultPenalty) ?
s.shortBalance :
expectedDefaultPenalty;
s.shortBalance = s.shortBalance.sub(penalty);
s.longBalance = s.longBalance.add(penalty);
}
s.state = TDS.State.Settled;
emit Settled(s.fixedParameters.symbol, s.endTime, s.nav);
}
function _updateBalances(TDS.Storage storage s, int navNew) internal {
// Compute difference -- Add the difference to owner and subtract
// from counterparty. Then update nav state variable.
int longDiff = _getLongDiff(navNew, s.longBalance, s.shortBalance);
s.nav = navNew;
s.longBalance = s.longBalance.add(longDiff);
s.shortBalance = s.shortBalance.sub(longDiff);
}
function _getDefaultPenalty(TDS.Storage storage s) internal view returns (int penalty) {
return s.defaultPenaltyAmount;
}
function _computeDefaultPenalty(TDS.Storage storage s) internal view returns (int penalty) {
return _takePercentage(s._getRequiredMargin(s.currentTokenState), s.fixedParameters.defaultPenalty);
}
function _getRequiredMargin(TDS.Storage storage s, TDS.TokenState memory tokenState)
internal
view
returns (int requiredMargin)
{
int leverageMagnitude = _absoluteValue(s.externalAddresses.returnCalculator.leverage());
int effectiveNotional;
if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear) {
int effectiveUnitsOfUnderlying = _safeIntCast(_totalSupply().mul(s.fixedParameters.initialTokenUnderlyingRatio).div(UINT_FP_SCALING_FACTOR)).mul(leverageMagnitude);
effectiveNotional = effectiveUnitsOfUnderlying.mul(tokenState.underlyingPrice).div(INT_FP_SCALING_FACTOR);
} else {
int currentNav = _computeNavForTokens(tokenState.tokenPrice, _totalSupply());
effectiveNotional = currentNav.mul(leverageMagnitude);
}
// Take the absolute value of the notional since a negative notional has similar risk properties to a positive
// notional of the same size, and, therefore, requires the same margin.
requiredMargin = _takePercentage(_absoluteValue(effectiveNotional), s.fixedParameters.supportedMove);
}
function _pullSentMargin(TDS.Storage storage s, uint expectedMargin) internal returns (uint refund) {
if (address(s.externalAddresses.marginCurrency) == address(0x0)) {
// Refund is any amount of ETH that was sent that was above the amount that was expected.
// Note: SafeMath will force a revert if msg.value < expectedMargin.
return msg.value.sub(expectedMargin);
} else {
// If we expect an ERC20 token, no ETH should be sent.
require(msg.value == 0);
_pullAuthorizedTokens(s.externalAddresses.marginCurrency, expectedMargin);
// There is never a refund in the ERC20 case since we use the argument to determine how much to "pull".
return 0;
}
}
function _sendMargin(TDS.Storage storage s, uint amount) internal {
// There's no point in attempting a send if there's nothing to send.
if (amount == 0) {
return;
}
if (address(s.externalAddresses.marginCurrency) == address(0x0)) {
msg.sender.transfer(amount);
} else {
require(s.externalAddresses.marginCurrency.transfer(msg.sender, amount));
}
}
function _settleAgreedPrice(TDS.Storage storage s) internal {
int agreedPrice = s.currentTokenState.underlyingPrice;
s._settleWithPrice(agreedPrice);
}
function _settleVerifiedPrice(TDS.Storage storage s) internal {
int oraclePrice = s.externalAddresses.oracle.getPrice(s.fixedParameters.product, s.endTime);
s._settleWithPrice(oraclePrice);
}
function _pullAuthorizedTokens(IERC20 erc20, uint amountToPull) private {
// If nothing is being pulled, there's no point in calling a transfer.
if (amountToPull > 0) {
require(erc20.transferFrom(msg.sender, address(this), amountToPull));
}
}
// Gets the change in balance for the long side.
// Note: there's a function for this because signage is tricky here, and it must be done the same everywhere.
function _getLongDiff(int navNew, int longBalance, int shortBalance) private pure returns (int longDiff) {
int newLongBalance = navNew;
// Long balance cannot go below zero.
if (newLongBalance < 0) {
newLongBalance = 0;
}
longDiff = newLongBalance.sub(longBalance);
// Cannot pull more margin from the short than is available.
if (longDiff > shortBalance) {
longDiff = shortBalance;
}
}
function _computeNavForTokens(int tokenPrice, uint numTokens) private pure returns (int navNew) {
int navPreDivision = _safeIntCast(numTokens).mul(tokenPrice);
navNew = navPreDivision.div(INT_FP_SCALING_FACTOR);
// The navNew division above truncates by default. Instead, we prefer to ceil this value to ensure tokens
// cannot be purchased or backed with less than their true value.
if ((navPreDivision % INT_FP_SCALING_FACTOR) != 0) {
navNew = navNew.add(1);
}
}
function _totalSupply() private view returns (uint totalSupply) {
ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this));
return thisErc20Token.totalSupply();
}
function _takePercentage(uint value, uint percentage) private pure returns (uint result) {
return value.mul(percentage).div(UINT_FP_SCALING_FACTOR);
}
function _takePercentage(int value, uint percentage) private pure returns (int result) {
return value.mul(_safeIntCast(percentage)).div(INT_FP_SCALING_FACTOR);
}
function _takePercentage(int value, int percentage) private pure returns (int result) {
return value.mul(percentage).div(INT_FP_SCALING_FACTOR);
}
function _absoluteValue(int value) private pure returns (int result) {
return value < 0 ? value.mul(-1) : value;
}
function _safeIntCast(uint value) private pure returns (int result) {
require(value <= INT_MAX);
return int(value);
}
function _safeUintCast(int value) private pure returns (uint result) {
require(value >= 0);
return uint(value);
}
// Note that we can't have the symbol parameter be `indexed` due to:
// TypeError: Indexed reference types cannot yet be used with ABIEncoderV2.
// An event emitted when the NAV of the contract changes.
event NavUpdated(string symbol, int newNav, int newTokenPrice);
// An event emitted when the contract enters the Default state on a remargin.
event Default(string symbol, uint defaultTime, int defaultNav);
// An event emitted when the contract settles.
event Settled(string symbol, uint settleTime, int finalNav);
// An event emitted when the contract expires.
event Expired(string symbol, uint expiryTime);
// An event emitted when the contract's NAV is disputed by the sponsor.
event Disputed(string symbol, uint timeDisputed, int navDisputed);
// An event emitted when the contract enters emergency shutdown.
event EmergencyShutdownTransition(string symbol, uint shutdownTime);
// An event emitted when tokens are created.
event TokensCreated(string symbol, uint numTokensCreated);
// An event emitted when tokens are redeemed.
event TokensRedeemed(string symbol, uint numTokensRedeemed);
// An event emitted when margin currency is deposited.
event Deposited(string symbol, uint amount);
// An event emitted when margin currency is withdrawn.
event Withdrawal(string symbol, uint amount);
}
// TODO(mrice32): make this and TotalReturnSwap derived classes of a single base to encap common functionality.
contract TokenizedDerivative is ERC20, AdminInterface, ExpandedIERC20 {
using TokenizedDerivativeUtils for TDS.Storage;
// Note: these variables are to give ERC20 consumers information about the token.
string public name;
string public symbol;
uint8 public constant decimals = 18; // solhint-disable-line const-name-snakecase
TDS.Storage public derivativeStorage;
constructor(
TokenizedDerivativeParams.ConstructorParams memory params,
string memory _name,
string memory _symbol
) public {
// Set token properties.
name = _name;
symbol = _symbol;
// Initialize the contract.
derivativeStorage._initialize(params, _symbol);
}
// Creates tokens with sent margin and returns additional margin.
function createTokens(uint marginForPurchase, uint tokensToPurchase) external payable {
derivativeStorage._createTokens(marginForPurchase, tokensToPurchase);
}
// Creates tokens with sent margin and deposits additional margin in short account.
function depositAndCreateTokens(uint marginForPurchase, uint tokensToPurchase) external payable {
derivativeStorage._depositAndCreateTokens(marginForPurchase, tokensToPurchase);
}
// Redeems tokens for margin currency.
function redeemTokens(uint tokensToRedeem) external {
derivativeStorage._redeemTokens(tokensToRedeem);
}
// Triggers a price dispute for the most recent remargin time.
function dispute(uint depositMargin) external payable {
derivativeStorage._dispute(depositMargin);
}
// Withdraws `amount` from short margin account.
function withdraw(uint amount) external {
derivativeStorage._withdraw(amount);
}
// Pays (Oracle and service) fees for the previous period, updates the contract NAV, moves margin between long and
// short accounts to reflect the new NAV, and checks if both accounts meet minimum requirements.
function remargin() external {
derivativeStorage._remargin();
}
// Forgo the Oracle verified price and settle the contract with last remargin price. This method is only callable on
// contracts in the `Defaulted` state, and the default penalty is always transferred from the short to the long
// account.
function acceptPriceAndSettle() external {
derivativeStorage._acceptPriceAndSettle();
}
// Assigns an address to be the contract's Delegate AP. Replaces previous value. Set to 0x0 to indicate there is no
// Delegate AP.
function setApDelegate(address apDelegate) external {
derivativeStorage._setApDelegate(apDelegate);
}
// Moves the contract into the Emergency state, where it waits on an Oracle price for the most recent remargin time.
function emergencyShutdown() external {
derivativeStorage._emergencyShutdown();
}
// Returns the expected net asset value (NAV) of the contract using the latest available Price Feed price.
function calcNAV() external view returns (int navNew) {
return derivativeStorage._calcNAV();
}
// Returns the expected value of each the outstanding tokens of the contract using the latest available Price Feed
// price.
function calcTokenValue() external view returns (int newTokenValue) {
return derivativeStorage._calcTokenValue();
}
// Returns the expected balance of the short margin account using the latest available Price Feed price.
function calcShortMarginBalance() external view returns (int newShortMarginBalance) {
return derivativeStorage._calcShortMarginBalance();
}
// Returns the expected short margin in excess of the margin requirement using the latest available Price Feed
// price. Value will be negative if the short margin is expected to be below the margin requirement.
function calcExcessMargin() external view returns (int excessMargin) {
return derivativeStorage._calcExcessMargin();
}
// Returns the required margin, as of the last remargin. Note that `calcExcessMargin` uses updated values using the
// latest available Price Feed price.
function getCurrentRequiredMargin() external view returns (int requiredMargin) {
return derivativeStorage._getCurrentRequiredMargin();
}
// Returns whether the contract can be settled, i.e., is it valid to call settle() now.
function canBeSettled() external view returns (bool canContractBeSettled) {
return derivativeStorage._canBeSettled();
}
// Returns the updated underlying price that was used in the calc* methods above. It will be a price feed price if
// the contract is Live and will remain Live, or an Oracle price if the contract is settled/about to be settled.
// Reverts if no Oracle price is available but an Oracle price is required.
function getUpdatedUnderlyingPrice() external view returns (int underlyingPrice, uint time) {
return derivativeStorage._getUpdatedUnderlyingPrice();
}
// When an Oracle price becomes available, performs a final remargin, assesses any penalties, and moves the contract
// into the `Settled` state.
function settle() external {
derivativeStorage._settle();
}
// Adds the margin sent along with the call (or in the case of an ERC20 margin currency, authorized before the call)
// to the short account.
function deposit(uint amountToDeposit) external payable {
derivativeStorage._deposit(amountToDeposit);
}
// Allows the sponsor to withdraw any ERC20 balance that is not the margin token.
function withdrawUnexpectedErc20(address erc20Address, uint amount) external {
derivativeStorage._withdrawUnexpectedErc20(erc20Address, amount);
}
// ExpandedIERC20 methods.
modifier onlyThis {
require(msg.sender == address(this));
_;
}
// Only allow calls from this contract or its libraries to burn tokens.
function burn(uint value) external onlyThis {
// Only allow calls from this contract or its libraries to burn tokens.
_burn(msg.sender, value);
}
// Only allow calls from this contract or its libraries to mint tokens.
function mint(address to, uint256 value) external onlyThis {
_mint(to, value);
}
// These events are actually emitted by TokenizedDerivativeUtils, but we unfortunately have to define the events
// here as well.
event NavUpdated(string symbol, int newNav, int newTokenPrice);
event Default(string symbol, uint defaultTime, int defaultNav);
event Settled(string symbol, uint settleTime, int finalNav);
event Expired(string symbol, uint expiryTime);
event Disputed(string symbol, uint timeDisputed, int navDisputed);
event EmergencyShutdownTransition(string symbol, uint shutdownTime);
event TokensCreated(string symbol, uint numTokensCreated);
event TokensRedeemed(string symbol, uint numTokensRedeemed);
event Deposited(string symbol, uint amount);
event Withdrawal(string symbol, uint amount);
}
contract TokenizedDerivativeCreator is ContractCreator, Testable {
struct Params {
uint defaultPenalty; // Percentage of mergin requirement * 10^18
uint supportedMove; // Expected percentage move in the underlying that the long is protected against.
bytes32 product;
uint fixedYearlyFee; // Percentage of nav * 10^18
uint disputeDeposit; // Percentage of mergin requirement * 10^18
address returnCalculator;
uint startingTokenPrice;
uint expiry;
address marginCurrency;
uint withdrawLimit; // Percentage of shortBalance * 10^18
TokenizedDerivativeParams.ReturnType returnType;
uint startingUnderlyingPrice;
string name;
string symbol;
}
AddressWhitelist public sponsorWhitelist;
AddressWhitelist public returnCalculatorWhitelist;
AddressWhitelist public marginCurrencyWhitelist;
constructor(
address registryAddress,
address _oracleAddress,
address _storeAddress,
address _priceFeedAddress,
address _sponsorWhitelist,
address _returnCalculatorWhitelist,
address _marginCurrencyWhitelist,
bool _isTest
)
public
ContractCreator(registryAddress, _oracleAddress, _storeAddress, _priceFeedAddress)
Testable(_isTest)
{
sponsorWhitelist = AddressWhitelist(_sponsorWhitelist);
returnCalculatorWhitelist = AddressWhitelist(_returnCalculatorWhitelist);
marginCurrencyWhitelist = AddressWhitelist(_marginCurrencyWhitelist);
}
function createTokenizedDerivative(Params memory params)
public
returns (address derivativeAddress)
{
TokenizedDerivative derivative = new TokenizedDerivative(_convertParams(params), params.name, params.symbol);
address[] memory parties = new address[](1);
parties[0] = msg.sender;
_registerContract(parties, address(derivative));
return address(derivative);
}
// Converts createTokenizedDerivative params to TokenizedDerivative constructor params.
function _convertParams(Params memory params)
private
view
returns (TokenizedDerivativeParams.ConstructorParams memory constructorParams)
{
// Copy and verify externally provided variables.
require(sponsorWhitelist.isOnWhitelist(msg.sender));
constructorParams.sponsor = msg.sender;
require(returnCalculatorWhitelist.isOnWhitelist(params.returnCalculator));
constructorParams.returnCalculator = params.returnCalculator;
require(marginCurrencyWhitelist.isOnWhitelist(params.marginCurrency));
constructorParams.marginCurrency = params.marginCurrency;
constructorParams.defaultPenalty = params.defaultPenalty;
constructorParams.supportedMove = params.supportedMove;
constructorParams.product = params.product;
constructorParams.fixedYearlyFee = params.fixedYearlyFee;
constructorParams.disputeDeposit = params.disputeDeposit;
constructorParams.startingTokenPrice = params.startingTokenPrice;
constructorParams.expiry = params.expiry;
constructorParams.withdrawLimit = params.withdrawLimit;
constructorParams.returnType = params.returnType;
constructorParams.startingUnderlyingPrice = params.startingUnderlyingPrice;
// Copy internal variables.
constructorParams.priceFeed = priceFeedAddress;
constructorParams.oracle = oracleAddress;
constructorParams.store = storeAddress;
constructorParams.admin = oracleAddress;
constructorParams.creationTime = getCurrentTime();
}
} | An event emitted when tokens are redeemed. | event TokensRedeemed(string symbol, uint numTokensRedeemed);
| 972,381 | [
1,
979,
871,
17826,
1347,
2430,
854,
283,
24903,
329,
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,
871,
13899,
426,
24903,
329,
12,
1080,
3273,
16,
2254,
818,
5157,
426,
24903,
329,
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
]
|
pragma solidity >=0.6.0 <0.9.0;
//SPDX-License-Identifier: MIT
import "./CustomMintRenameWithERC20.sol";
import "./CustomMintRenameWithEth.sol";
pragma experimental ABIEncoderV2;
contract CryptoJerseys is CustomMintRenameWithEth, CustomMintRenameWithERC20 {
constructor(string memory baseURI) public ERC721("CryptoJerseys", "CJA") {
// MINT the 0th eth J to the owner
_safeMint(owner(), uint256(0));
_rename(uint256(0), "Vitalik");
_setBaseURI(baseURI);
}
}
pragma solidity >=0.6.0 <0.9.0;
//SPDX-License-Identifier: MIT
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./CustomMintRename.sol";
import "./CostUtils.sol";
import "./TokenMetadata.sol";
pragma experimental ABIEncoderV2;
abstract contract CustomMintRenameWithERC20 is CustomMintRename {
using CostUtils for uint256;
struct SupportedTokenData {
address erc20ContractAddress;
uint32 decimals;
uint256 renameFee;
}
SupportedTokenData[] private supportedErc20Contracts;
function upsertNewErc20Token(
address erc20ContractAddress,
uint32 decimals,
uint256 renameFee,
string memory nameOf0thJ
) public {
require(owner() == _msgSender(), "Must be owner");
for (uint256 i = 0; i < supportedErc20Contracts.length; i++) {
if (
supportedErc20Contracts[i].erc20ContractAddress ==
erc20ContractAddress
) {
supportedErc20Contracts[i].decimals = decimals;
supportedErc20Contracts[i].renameFee = renameFee;
return;
}
}
SupportedTokenData memory std =
SupportedTokenData({
erc20ContractAddress: erc20ContractAddress,
decimals: decimals,
renameFee: renameFee
});
supportedErc20Contracts.push(std);
// MINT the 0th J to the owner when we push a new supported contract
uint256 tokenID = _getTokenId(erc20ContractAddress, 0);
_safeMint(owner(), tokenID);
_rename(tokenID, nameOf0thJ);
}
function mintFromERC20(address erc20ContractAddress, uint32 jNumber)
public
{
address minter = _msgSender();
// check erc20 address is in allow list
uint256 tokenID = _getTokenId(erc20ContractAddress, jNumber);
address thisContractAddress = address(this);
require(jNumber < 100 && jNumber > 0, "Invalid jnumber");
require(!_exists(tokenID), "Already minted");
uint256 decimals = _getDecimalsForContractAddress(erc20ContractAddress);
// Get Total Cost
uint256 cost = CostUtils.getMintCost(jNumber, decimals);
// Transfer total cost from minter to our contract
_safeTransferFrom(
erc20ContractAddress,
minter,
thisContractAddress,
cost
);
// Sweep fee from contract to owner
uint256 fee = CostUtils.getMintFee(jNumber, decimals);
_safeTransfer(erc20ContractAddress, owner(), fee);
_safeMint(minter, tokenID);
}
function renameWithERC20(
address erc20ContractAddress,
uint32 jNumber,
string memory newName
) public {
uint256 tokenID = _getTokenId(erc20ContractAddress, jNumber);
address ownerOfNft = ownerOf(tokenID);
require(_exists(tokenID), "Not minted");
require(ownerOfNft == _msgSender(), "Must be owner");
require(
validateName(newName),
"Invalid name. Must be 1-10 ASCII chars."
);
require(nameAvailable(newName), "Name already taken sorry");
_allocateAndSweepRenameFee(tokenID, erc20ContractAddress, ownerOfNft);
_rename(tokenID, newName);
}
function getTokensForERC20(address erc20ContractAddress)
external
view
returns (TokenMetadata[100] memory)
{
TokenMetadata[100] memory tokens;
for (uint32 jNumber = 0; jNumber < 100; jNumber++) {
uint256 tokenId = _getTokenId(erc20ContractAddress, jNumber);
if (_exists(tokenId)) {
TokenMetadata memory tmd =
TokenMetadata({
exists: true,
tokenId: tokenId,
jNumber: jNumber,
erc20ContractAddress: erc20ContractAddress,
claimableRenameFees: getRenameFeesAvailableToClaimERC20(
erc20ContractAddress,
jNumber
),
hasFreeRename: freeRenameAvailable(tokenId),
name: nameOf(tokenId),
ownerAddress: ownerOf(tokenId)
});
tokens[jNumber] = tmd;
} else {
TokenMetadata memory tmd =
TokenMetadata({
exists: false,
tokenId: tokenId,
jNumber: jNumber,
erc20ContractAddress: erc20ContractAddress,
claimableRenameFees: getRenameFeesAvailableToClaimERC20(
erc20ContractAddress,
jNumber
),
hasFreeRename: freeRenameAvailable(tokenId),
name: "",
ownerAddress: address(0)
});
tokens[jNumber] = tmd;
}
}
return tokens;
}
function _allocateAndSweepRenameFee(
uint256 tokenID,
address erc20ContractAddress,
address ownerOfNft
) private {
if (freeRenameAvailable(tokenID)) {
return;
}
// Transfer total cost from minter to our contract
uint256 costOfRename =
_getRenameFeeForContractAddress(erc20ContractAddress);
_safeTransferFrom(
erc20ContractAddress,
ownerOfNft,
address(this),
costOfRename
);
// We increase the J Type Epoch counter
// When fees are claimed in the future it is calculated
// from the difference of J_TYPE_EPOCH-lastClaimedEpoch.
// E.g 3-1=2 implies the nft is elligible for a percentage of 2*fees
J_TYPE_EPOCH[erc20ContractAddress] += 1;
// We pay out the flat 10% fee on the cost of renames
// E.g 0.1 * 10%
uint256 feeCollectorFeeAmount = (costOfRename * 10) / 100;
uint256 allocatableFee = costOfRename - feeCollectorFeeAmount;
uint256 remainderOfAllocation = allocatableFee % _totalShares;
uint256 feePlusRemainder =
feeCollectorFeeAmount + remainderOfAllocation;
_safeTransfer(erc20ContractAddress, owner(), feePlusRemainder);
}
function burnForERC20(address erc20ContractAddress, uint32 jNumber) public {
uint256 tokenID = _getTokenId(erc20ContractAddress, jNumber);
require(_exists(tokenID), "Not minted");
require(ownerOf(tokenID) == _msgSender(), "Must be owner.");
// Give the owner back their stake
_safeTransfer(
erc20ContractAddress,
ownerOf(tokenID),
CostUtils.getBurnValue(
jNumber,
_getDecimalsForContractAddress(erc20ContractAddress)
)
);
// Free up old name
_rename(tokenID, "");
_burn(tokenID);
}
function claimRenameFeesERC20(address erc20ContractAddress, uint32 jNumber)
public
{
uint256 tokenID = _getTokenId(erc20ContractAddress, jNumber);
require(_exists(tokenID), "Not minted");
address owner = ownerOf(tokenID);
require(owner == _msgSender(), "Must be owner.");
uint256 ownerFeeAmount =
_getRenameFeesAvailableToClaimERC20(erc20ContractAddress, jNumber);
if (ownerFeeAmount == 0) {
return;
}
// Move the last claimed epoch to the current nft type epoch
J_LAST_CLAIMED_EPOCH[tokenID] = J_TYPE_EPOCH[erc20ContractAddress];
// Transfer the funds to the owner
_safeTransfer(erc20ContractAddress, owner, ownerFeeAmount);
}
function hasUsedFreeRenameERC20(
address erc20ContractAddress,
uint32 jNumber
) public view returns (bool) {
uint256 tokenID = _getTokenId(erc20ContractAddress, jNumber);
return !freeRenameAvailable(tokenID);
}
function getRenameFeesAvailableToClaimERC20(
address erc20ContractAddress,
uint32 jNumber
) public view returns (uint256) {
return
_getRenameFeesAvailableToClaimERC20(erc20ContractAddress, jNumber);
}
function _getRenameFeesAvailableToClaimERC20(
address erc20ContractAddress,
uint32 jNumber
) private view returns (uint256) {
uint256 tokenID = _getTokenId(erc20ContractAddress, jNumber);
uint256 jEpoch = J_TYPE_EPOCH[erc20ContractAddress];
uint256 lastClaimed = J_LAST_CLAIMED_EPOCH[tokenID];
if (jEpoch <= lastClaimed) {
return 0;
}
uint256 feeMultiplier = jEpoch - lastClaimed;
// E.g 99/4950 * 1 * 0.1 * 90% (flat 10% was paid to contract owner)
uint256 costOfRename =
_getRenameFeeForContractAddress(erc20ContractAddress);
// 10% is paid to contract owner, so 90% remains for the nft holders
uint256 adjustedCostOfRename = (costOfRename * 90) / 100;
uint256 remainderAfterAllocation = adjustedCostOfRename % _totalShares;
uint256 evenlyDivisibleAllocation =
adjustedCostOfRename - remainderAfterAllocation;
uint256 ownerFeeAmount =
((((uint256(jNumber) * PRECISION_MULTIPLIER)) *
feeMultiplier *
evenlyDivisibleAllocation) / PRECISION_MULTIPLIER) /
_totalShares;
return ownerFeeAmount;
}
function getSupportedErc20Contracts()
external
view
returns (SupportedTokenData[] memory)
{
return supportedErc20Contracts;
}
function _getRenameFeeForContractAddress(address erc20TokenAddress)
private
view
returns (uint256)
{
for (uint256 i = 0; i < supportedErc20Contracts.length; i++) {
if (
supportedErc20Contracts[i].erc20ContractAddress ==
erc20TokenAddress
) {
return supportedErc20Contracts[i].renameFee;
}
}
revert("Token not supported");
}
function _getDecimalsForContractAddress(address erc20TokenAddress)
private
view
returns (uint256)
{
for (uint256 i = 0; i < supportedErc20Contracts.length; i++) {
if (
supportedErc20Contracts[i].erc20ContractAddress ==
erc20TokenAddress
) {
return supportedErc20Contracts[i].decimals;
}
}
revert("Token not supported");
}
function _getTokenId(address erc20ContractAddress, uint32 jNumber)
internal
pure
returns (uint256)
{
return
uint256(keccak256(abi.encodePacked(erc20ContractAddress, jNumber)));
}
// Some tokens on Mainnet are problematic in that some may not throw if the transfer fails
// but return `false` and some might not return `true` as a value in the case of success
function _safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
(bool success, bytes memory data) =
token.call(
abi.encodeWithSelector(
IERC20.transferFrom.selector,
from,
to,
value
)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"Failed to transferFrom"
);
}
function _safeTransfer(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) =
token.call(
abi.encodeWithSelector(IERC20.transfer.selector, to, value)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"Failed to transfer"
);
}
}
pragma solidity >=0.6.0 <0.9.0;
//SPDX-License-Identifier: MIT
import "./CustomMintRename.sol";
import "./CostUtils.sol";
import "./TokenMetadata.sol";
pragma experimental ABIEncoderV2;
abstract contract CustomMintRenameWithEth is CustomMintRename {
uint256 private ETH_RENAME_FEE = 10**17; // 0.1
using CostUtils for uint256;
address internal constant ETH_ADDRESS =
0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
function updateRenameFeeEth(uint256 renameFeeInWei) public {
require(owner() == _msgSender(), "Must be owner");
ETH_RENAME_FEE = renameFeeInWei;
}
function mintFromEth(uint256 jNumber) public payable {
address minter = _msgSender();
require(jNumber < 100 && jNumber > 0, "Invalid jnumber");
require(!_exists(jNumber), "Already minted");
uint256 cost = CostUtils.getMintCost(jNumber, 18);
uint256 weiSent = msg.value;
// Check the contract exact amount to mint
require(weiSent == cost, "Incorrect eth sent for jNumber");
// Sweep fee to owner
uint256 fee = CostUtils.getMintFee(jNumber, 18);
payable(owner()).transfer(fee);
_safeMint(minter, jNumber);
}
function renameWithEth(uint32 jNumber, string memory newName)
public
payable
{
uint256 tokenID = jNumber;
address ownerOfNft = ownerOf(tokenID);
require(_exists(tokenID), "Not minted");
require(ownerOfNft == _msgSender(), "Must be owner");
require(
validateName(newName),
"Invalid name. Must be 1-10 ASCII chars."
);
require(nameAvailable(newName), "Name already taken sorry");
uint256 weiSent = msg.value;
_allocateAndSweepRenameFee(tokenID, weiSent);
_rename(tokenID, newName);
}
function _allocateAndSweepRenameFee(uint256 tokenID, uint256 weiSent)
private
{
if (freeRenameAvailable(tokenID)) {
if (weiSent != 0) {
// Send them back their ETH
_msgSender().transfer(weiSent);
}
return;
}
J_TYPE_EPOCH[ETH_ADDRESS] += 1;
// Flat 10% rename fee paid to the contract owner
uint256 feeCollectorFeeAmount = (ETH_RENAME_FEE * 10) / 100;
uint256 allocatableFee = ETH_RENAME_FEE - feeCollectorFeeAmount;
uint256 remainderOfAllocation = allocatableFee % _totalShares;
uint256 feePlusRemainder =
feeCollectorFeeAmount + remainderOfAllocation;
payable(owner()).transfer(feePlusRemainder);
}
function burnForEth(uint32 jNumber) public {
uint256 tokenID = jNumber;
require(_exists(tokenID), "Not minted");
require(ownerOf(tokenID) == _msgSender(), "Must be owner.");
address payable tokenOwner = payable(ownerOf(tokenID));
// Give the owner back their stake
tokenOwner.transfer(CostUtils.getBurnValue(jNumber, 18));
// Free up old name
_rename(tokenID, "");
_burn(tokenID);
}
function claimRenameFeesEth(uint32 jNumber) public {
require(ownerOf(uint256(jNumber)) == _msgSender(), "Must be owner.");
address payable tokenOwner = payable(_msgSender());
uint256 ownerFeeAmount = _getRenameFeesAvailableToClaimEth(jNumber);
if (ownerFeeAmount == 0) {
return;
}
// Move the last claimed epoch to the current j type epoch
J_LAST_CLAIMED_EPOCH[uint256(jNumber)] = J_TYPE_EPOCH[ETH_ADDRESS];
tokenOwner.transfer(ownerFeeAmount);
}
function hasUsedFreeRenameEth(uint32 jNumber) public view returns (bool) {
return !freeRenameAvailable(jNumber);
}
function getRenameFeesAvailableToClaimEth(uint32 jNumber)
public
view
returns (uint256)
{
return _getRenameFeesAvailableToClaimEth(jNumber);
}
function getTokensForEth()
external
view
returns (TokenMetadata[100] memory)
{
TokenMetadata[100] memory tokens;
for (uint32 jNumber = 0; jNumber < 100; jNumber++) {
uint256 tokenId = jNumber;
if (_exists(tokenId)) {
TokenMetadata memory tmd =
TokenMetadata({
exists: true,
tokenId: tokenId,
jNumber: jNumber,
erc20ContractAddress: address(0),
claimableRenameFees: getRenameFeesAvailableToClaimEth(
jNumber
),
hasFreeRename: freeRenameAvailable(tokenId),
name: nameOf(tokenId),
ownerAddress: ownerOf(tokenId)
});
tokens[jNumber] = tmd;
} else {
TokenMetadata memory tmd =
TokenMetadata({
exists: false,
tokenId: tokenId,
jNumber: jNumber,
erc20ContractAddress: address(0),
claimableRenameFees: getRenameFeesAvailableToClaimEth(
jNumber
),
hasFreeRename: freeRenameAvailable(tokenId),
name: "",
ownerAddress: address(0)
});
tokens[jNumber] = tmd;
}
}
return tokens;
}
function _getRenameFeesAvailableToClaimEth(uint32 jNumber)
internal
view
returns (uint256)
{
uint256 tokenID = jNumber;
uint256 jEpoch = J_TYPE_EPOCH[ETH_ADDRESS];
uint256 lastClaimed = J_LAST_CLAIMED_EPOCH[tokenID];
if (jEpoch <= lastClaimed) {
return 0;
}
uint256 feeMultiplier = jEpoch - lastClaimed;
// E.g 99/4950 * 1 * 0.1 * 90% (flat 10% was paid to contract owner)
// 10% is paid to contract owner, so 90% remains for the nft holders
uint256 adjustedCostOfRename = (ETH_RENAME_FEE * 90) / 100;
uint256 remainderAfterAllocation = adjustedCostOfRename % _totalShares;
uint256 evenlyDivisibleAllocation =
adjustedCostOfRename - remainderAfterAllocation;
uint256 ownerFeeAmount =
((((uint256(jNumber) * PRECISION_MULTIPLIER)) *
feeMultiplier *
evenlyDivisibleAllocation) / PRECISION_MULTIPLIER) /
_totalShares;
return ownerFeeAmount;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity >=0.6.0 <0.9.0;
//SPDX-License-Identifier: MIT
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
pragma experimental ABIEncoderV2;
abstract contract CustomMintRename is Ownable, ERC721 {
event Rename(uint256 indexed tokenID);
mapping(uint256 => string) private tokenNames;
mapping(uint256 => bool) private usedFreeRename;
mapping(string => bool) private nameDictionary;
// For each J type we have an epoch, incrememnted with every paid rename
// Token Address => totalEpoch
mapping(address => uint256) internal J_TYPE_EPOCH;
// For J ID we have a last claimed epoch, incrememnted with fee claim
// A j can claim a fee when J_TYPE_EPOCH-J_LAST_CLAIMED_EPOCH > 0
// TokenID => lastClaimedEpoch
mapping(uint256 => uint256) internal J_LAST_CLAIMED_EPOCH;
uint256 internal constant PRECISION_MULTIPLIER = 1e18;
// sum of ‘n’ natural numbers to 99.
// 99*(100)/2 = 4950
//
uint256 _totalShares = 4950;
function exists(uint256 tokenId) public view returns (bool) {
return _exists(tokenId);
}
function nameOf(uint256 tokenId) public view returns (string memory) {
return tokenNames[tokenId];
}
function freeRenameAvailable(uint256 tokenId) public view returns (bool) {
return !usedFreeRename[tokenId];
}
function nameAvailable(string memory newName) public view returns (bool) {
return !nameDictionary[toLower(newName)];
}
function _rename(uint256 tokenID, string memory newName) internal {
// Free up old name
string storage oldName = tokenNames[tokenID];
nameDictionary[toLower(oldName)] = false;
// Add the name to the unique dictionary
nameDictionary[toLower(newName)] = true;
// Set the new name
tokenNames[tokenID] = newName;
// Used the free rename - can set everytime no state change
usedFreeRename[tokenID] = true;
emit Rename(tokenID);
}
/**
* @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space)
*/
function validateName(string memory str) public pure returns (bool) {
uint256 MAX_LENTH = 10;
bytes memory b = bytes(str);
if (b.length < 1) return false;
if (b.length > MAX_LENTH) return false; // Cannot be longer than 25 characters
if (b[0] == 0x20) return false; // Leading space
if (b[b.length - 1] == 0x20) return false; // Trailing space
bytes1 lastChar = b[0];
for (uint256 i; i < b.length; i++) {
bytes1 char = b[i];
if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces
if (
!(char >= 0x30 && char <= 0x39) && //9-0
!(char >= 0x41 && char <= 0x5A) && //A-Z
!(char >= 0x61 && char <= 0x7A) && //a-z
!(char == 0x20) //space
) return false;
lastChar = char;
}
return true;
}
/**
* @dev Converts the string to lowercase
*/
function toLower(string memory str) public pure returns (string memory) {
bytes memory bStr = bytes(str);
bytes memory bLower = new bytes(bStr.length);
for (uint256 i = 0; i < bStr.length; i++) {
// Uppercase character
if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) {
bLower[i] = bytes1(uint8(bStr[i]) + 32);
} else {
bLower[i] = bStr[i];
}
}
return string(bLower);
}
}
pragma solidity >=0.6.0 <0.9.0;
//SPDX-License-Identifier: MIT
library CostUtils {
function getMintCost(uint256 jNumber, uint256 decimals)
internal
pure
returns (uint256)
{
require(jNumber >= 0);
require(jNumber < 100);
return (((jNumber * 110)) * (uint256(10)**decimals)) / 100;
}
function getMintFee(uint256 jNumber, uint256 decimals)
internal
pure
returns (uint256)
{
uint256 cost = getMintCost(jNumber, decimals);
return cost / 11;
}
function getBurnValue(uint256 jNumber, uint256 decimals)
internal
pure
returns (uint256)
{
require(jNumber >= 0);
require(jNumber < 100);
return jNumber * (uint256(10)**decimals);
}
}
pragma solidity >=0.6.0 <0.9.0;
//SPDX-License-Identifier: MIT
struct TokenMetadata {
bool exists;
uint256 tokenId;
address erc20ContractAddress;
uint256 jNumber;
uint256 claimableRenameFees;
bool hasFreeRename;
string name;
address ownerAddress;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC721.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./IERC721Receiver.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../utils/EnumerableSet.sol";
import "../../utils/EnumerableMap.sol";
import "../../utils/Strings.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// If there is no base URI, return the token URI.
if (bytes(_baseURI).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(_baseURI, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = 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 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 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 returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view 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 Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @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.6.0;
import "../GSN/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.
*/
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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
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.6.2;
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
pragma solidity ^0.6.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.6.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) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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 Check if the name string is valid (Alphanumeric and spaces without leading or trailing space)/ | function validateName(string memory str) public pure returns (bool) {
uint256 MAX_LENTH = 10;
bytes memory b = bytes(str);
if (b.length < 1) return false;
bytes1 lastChar = b[0];
for (uint256 i; i < b.length; i++) {
bytes1 char = b[i];
if (
) return false;
lastChar = char;
}
return true;
}
| 1,331,086 | [
1,
1564,
309,
326,
508,
533,
353,
923,
261,
1067,
21183,
471,
7292,
2887,
7676,
578,
7341,
3476,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1954,
461,
12,
1080,
3778,
609,
13,
1071,
16618,
1135,
261,
6430,
13,
288,
203,
3639,
2254,
5034,
4552,
67,
900,
1784,
44,
273,
1728,
31,
203,
3639,
1731,
3778,
324,
273,
1731,
12,
701,
1769,
203,
3639,
309,
261,
70,
18,
2469,
411,
404,
13,
327,
629,
31,
203,
203,
3639,
1731,
21,
23914,
273,
324,
63,
20,
15533,
203,
203,
3639,
364,
261,
11890,
5034,
277,
31,
277,
411,
324,
18,
2469,
31,
277,
27245,
288,
203,
5411,
1731,
21,
1149,
273,
324,
63,
77,
15533,
203,
203,
203,
5411,
309,
261,
203,
5411,
262,
327,
629,
31,
203,
203,
5411,
23914,
273,
1149,
31,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x9460b380c57F65e8AFc4bA3518F643A526640F26/sources/contracts/protocol/libraries/logic/ReserveLogic.sol | * @notice Updates the liquidity cumulative index and the variable borrow index. @param reserve The reserve object @param reserveCache The caching layer for the reserve data/ | function updateState(
DataTypes.ReserveData storage reserve,
DataTypes.ReserveCache memory reserveCache
) internal {
_updateIndexes(reserve, reserveCache);
_accrueToTreasury(reserve, reserveCache);
}
| 4,203,432 | [
1,
5121,
326,
4501,
372,
24237,
15582,
770,
471,
326,
2190,
29759,
770,
18,
225,
20501,
1021,
20501,
733,
225,
20501,
1649,
1021,
11393,
3018,
364,
326,
20501,
501,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
1089,
1119,
12,
203,
3639,
1910,
2016,
18,
607,
6527,
751,
2502,
20501,
16,
203,
3639,
1910,
2016,
18,
607,
6527,
1649,
3778,
20501,
1649,
203,
565,
262,
2713,
288,
203,
3639,
389,
2725,
8639,
12,
455,
6527,
16,
20501,
1649,
1769,
203,
3639,
389,
8981,
86,
344,
774,
56,
266,
345,
22498,
12,
455,
6527,
16,
20501,
1649,
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
]
|
pragma solidity ^0.4.25;
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x80ac58cd.
interface ERC721 /* is ERC165 */ {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
///
/// MOVED THIS TO CSportsBase because of how class structure is derived.
///
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) external view returns (uint256);
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId) external view returns (address);
/// @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,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable;
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external payable;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x5b5e139f.
interface ERC721Metadata /* is ERC721 */ {
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string _name);
/// @notice An abbreviated name for NFTs in this contract
function symbol() external view 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);
}
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x780e9d63.
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() external 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);
}
/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02.
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. Return of other than the magic value MUST result in the
/// transaction being reverted.
/// Note: the 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(keccak256("onERC721Received(address,address,uint256,bytes)"))`
/// unless throwing
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4);
}
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);
}
/// @title Auction Core
/// @dev Contains models, variables, and internal methods for the auction.
contract TimeAuctionBase {
// Represents an auction on an NFT
struct Auction {
// Current owner of NFT
address seller;
// Price (in wei) at beginning of auction
uint128 startingPrice;
// Price (in wei) at end of auction
uint128 endingPrice;
// Duration (in seconds) of auction
uint64 duration;
// Time when auction started
// NOTE: 0 if this auction has been concluded
uint64 startedAt;
}
// Reference to contract tracking NFT ownership
ERC721 public nonFungibleContract;
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
// Map from token ID to their corresponding auction.
mapping (uint256 => Auction) tokenIdToAuction;
event AuctionCreated(uint256 tokenId, address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
event AuctionCancelled(uint256 tokenId);
event AuctionSettled(uint256 tokenId, uint256 price, uint256 sellerProceeds, address seller, address buyer);
event AuctionRepriced(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint64 duration, uint64 startedAt);
/// @dev DON'T give me your money.
function() external {}
// Modifiers to check that inputs can be safely stored with a certain
// number of bits. We use constants and multiple modifiers to save gas.
modifier canBeStoredWith32Bits(uint256 _value) {
require(_value <= 4294967295);
_;
}
// Modifiers to check that inputs can be safely stored with a certain
// number of bits. We use constants and multiple modifiers to save gas.
modifier canBeStoredWith64Bits(uint256 _value) {
require(_value <= 18446744073709551615);
_;
}
modifier canBeStoredWith128Bits(uint256 _value) {
require(_value < 340282366920938463463374607431768211455);
_;
}
/// @dev Returns true if the claimant owns the token.
/// @param _claimant - Address claiming to own the token.
/// @param _tokenId - ID of token whose ownership to verify.
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
/// @dev Escrows the NFT, assigning ownership to this contract.
/// Throws if the escrow fails.
/// @param _owner - Current owner address of token to escrow.
/// @param _tokenId - ID of token whose approval to verify.
function _escrow(address _owner, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
/// @dev Transfers an NFT owned by this contract to another address.
/// Returns true if the transfer succeeds.
/// @param _receiver - Address to transfer NFT to.
/// @param _tokenId - ID of token to transfer.
function _transfer(address _receiver, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.approve(_receiver, _tokenId);
nonFungibleContract.transferFrom(address(this), _receiver, _tokenId);
}
/// @dev Adds an auction to the list of open auctions. Also fires the
/// AuctionCreated event.
/// @param _tokenId The ID of the token to be put on auction.
/// @param _auction Auction to add.
function _addAuction(uint256 _tokenId, Auction _auction) internal {
// Require that all auctions have a duration of
// at least one minute. (Keeps our math from getting hairy!)
require(_auction.duration >= 1 minutes);
tokenIdToAuction[_tokenId] = _auction;
emit AuctionCreated(
uint256(_tokenId),
address(_auction.seller),
uint256(_auction.startingPrice),
uint256(_auction.endingPrice),
uint256(_auction.duration)
);
}
/// @dev Cancels an auction unconditionally.
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
emit AuctionCancelled(_tokenId);
}
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _bid(uint256 _tokenId, uint256 _bidAmount)
internal
returns (uint256)
{
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// Explicitly check that this auction is currently live.
// (Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return an auction object that is all zeros.)
require(_isOnAuction(auction));
// Check that the incoming bid is higher than the current
// price
uint256 price = _currentPrice(auction);
require(_bidAmount >= price);
// Grab a reference to the seller before the auction struct
// gets deleted.
address seller = auction.seller;
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeAuction(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the auctioneer's cut.
// (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
// NOTE: Doing a transfer() in the middle of a complex
// method like this is generally discouraged because of
// reentrancy attacks and DoS attacks if the seller is
// a contract with an invalid fallback function. We explicitly
// guard against reentrancy attacks by removing the auction
// before calling transfer(), and the only thing the seller
// can DoS is the sale of their own asset! (And if it's an
// accident, they can call cancelAuction(). )
seller.transfer(sellerProceeds);
emit AuctionSettled(_tokenId, price, sellerProceeds, seller, msg.sender);
}
// Tell the world!
emit AuctionSuccessful(_tokenId, price, msg.sender);
return price;
}
/// @dev Removes an auction from the list of open auctions.
/// @param _tokenId - ID of NFT on auction.
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/// @dev Returns true if the NFT is on auction.
/// @param _auction - Auction to check.
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
/// @dev Returns current price of an NFT on auction. Broken into two
/// functions (this one, that computes the duration from the auction
/// structure, and the other that does the price computation) so we
/// can easily test that the price computation works correctly.
function _currentPrice(Auction storage _auction)
internal
view
returns (uint256)
{
uint256 secondsPassed = 0;
// A bit of insurance against negative values (or wraparound).
// Probably not necessary (since Ethereum guarnatees that the
// now variable doesn't ever go backwards).
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
return _computeCurrentPrice(
_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed
);
}
/// @dev Computes the current price of an auction. Factored out
/// from _currentPrice so we can run extensive unit tests.
/// When testing, make this function public and turn on
/// `Current price computation` test suite.
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
)
internal
pure
returns (uint256)
{
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our public functions carefully cap the maximum values for
// time (at 64-bits) and currency (at 128-bits). _duration is
// also known to be non-zero (see the require() statement in
// _addAuction())
if (_secondsPassed >= _duration) {
// We've reached the end of the dynamic pricing portion
// of the auction, just return the end price.
return _endingPrice;
} else {
// Starting price can be higher than ending price (and often is!), so
// this delta can be negative.
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
// This multiplication can't overflow, _secondsPassed will easily fit within
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
// will always fit within 256-bits.
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
// currentPriceChange can be negative, but if so, will have a magnitude
// less that _startingPrice. Thus, this result will always end up positive.
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
/// @dev Computes owner's cut of a sale.
/// @param _price - Sale price of NFT.
function _computeCut(uint256 _price) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
// statement in the TimeAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * ownerCut / 10000;
}
}
/**
* @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 Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/// @title Clock auction for non-fungible tokens.
contract TimeAuction is Pausable, TimeAuctionBase {
/// @dev Constructor creates a reference to the NFT ownership contract
/// and verifies the owner cut is in the valid range.
/// @param _nftAddress - address of a deployed contract implementing
/// the Nonfungible Interface.
/// @param _cut - 100*(percent cut) the owner takes on each auction, must be
/// between 0-10,000.
constructor(address _nftAddress, uint256 _cut) public {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
nonFungibleContract = candidateContract;
}
/// @dev Remove all Ether from the contract, which is the owner's cuts
/// as well as any Ether sent directly to the contract address.
/// Always transfers to the NFT contract, and can only be called from
/// the NFT contract.
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(msg.sender == nftAddress);
nftAddress.transfer(address(this).balance);
}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of time to move between starting
/// price and ending price (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
public
whenNotPaused
canBeStoredWith128Bits(_startingPrice)
canBeStoredWith128Bits(_endingPrice)
canBeStoredWith64Bits(_duration)
{
require(_owns(msg.sender, _tokenId));
_escrow(msg.sender, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Bids on an open auction, completing the auction and transferring
/// ownership of the NFT if enough Ether is supplied.
/// @param _tokenId - ID of token to bid on.
function bid(uint256 _tokenId)
public
payable
whenNotPaused
{
// _bid will throw if the bid or funds transfer fails
_bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
}
/// @dev Cancels an auction that hasn't been won yet.
/// Returns the NFT to original owner.
/// @notice This is a state-modifying function that can
/// be called while the contract is paused. An auction can
/// only be cancelled by the seller.
/// @param _tokenId - ID of token on auction
function cancelAuction(uint256 _tokenId)
public
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
/// @dev Cancels an auction when the contract is paused.
/// Only the owner (account that created the contract)
/// may do this, and NFTs are returned to
/// the seller. This should only be used in emergencies.
/// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuctionWhenPaused(uint256 _tokenId)
whenPaused
onlyOwner
public
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId, auction.seller);
}
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId)
public
view
returns
(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 currentPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
uint256 price = _currentPrice(auction);
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
price,
auction.duration,
auction.startedAt
);
}
/// @dev Returns current auction prices for up to 50 auctions
/// @param _tokenIds - up to 50 IDs of NFT on auction that we want the prices of
function getCurrentAuctionPrices(uint128[] _tokenIds) public view returns (uint128[50]) {
require (_tokenIds.length <= 50);
/// @dev A fixed array we can return current auction price information in.
uint128[50] memory currentPricesArray;
for (uint8 i = 0; i < _tokenIds.length; i++) {
Auction storage auction = tokenIdToAuction[_tokenIds[i]];
if (_isOnAuction(auction)) {
uint256 price = _currentPrice(auction);
currentPricesArray[i] = uint128(price);
}
}
return currentPricesArray;
}
/// @dev Returns the current price of an auction.
/// @param _tokenId - ID of the token price we are checking.
function getCurrentPrice(uint256 _tokenId)
public
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
}
/// @title Interface to allow a contract to listen to auction events.
contract SaleClockAuctionListener {
function implementsSaleClockAuctionListener() public pure returns (bool);
function auctionCreated(uint256 tokenId, address seller, uint128 startingPrice, uint128 endingPrice, uint64 duration) public;
function auctionSuccessful(uint256 tokenId, uint128 totalPrice, address seller, address buyer) public;
function auctionCancelled(uint256 tokenId, address seller) public;
}
/// @title Clock auction modified for sale of kitties
contract SaleClockAuction is TimeAuction {
// @dev A listening contract that wants notifications of auction creation,
// completion, and cancellation
SaleClockAuctionListener public listener;
// Delegate constructor
constructor(address _nftAddr, uint256 _cut) public TimeAuction(_nftAddr, _cut) {
}
/// @dev Sanity check that allows us to ensure that we are pointing to the
/// right auction in our setSaleAuctionAddress() call.
function isSaleClockAuction() public pure returns (bool) {
return true;
}
// @dev Method used to add a listener for auction events. This can only be called
// if the listener has not already been set (i.e. once). This limitation is in place to prevent
// malicious attempt to hijack the listening contract and perhaps try to do
// something bad (like throw). Since the listener methods are called inline with our
// createAuction(...), bid(...), and cancelAuction(...) methods, we need to make
// sure none of the listener methods causes a revert/throw/out of gas/etc.
// @param _listener - Address of a SaleClockAuctionListener compatible contract
function setListener(address _listener) public {
require(listener == address(0));
SaleClockAuctionListener candidateContract = SaleClockAuctionListener(_listener);
require(candidateContract.implementsSaleClockAuctionListener());
listener = candidateContract;
}
/// @dev Creates and begins a new auction. We override the base class
/// so we can add the listener capability.
///
/// CALLABLE ONLY BY NFT CONTRACT
///
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of auction (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
public
canBeStoredWith128Bits(_startingPrice)
canBeStoredWith128Bits(_endingPrice)
canBeStoredWith64Bits(_duration)
{
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
if (listener != address(0)) {
listener.auctionCreated(_tokenId, _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration));
}
}
/// @dev Reprices (and updates duration) of an array of tokens that are currently
/// being auctioned by this contract.
///
/// CALLABLE ONLY BY NFT CONTRACT
///
/// @param _tokenIds Array of tokenIds corresponding to auctions being updated
/// @param _startingPrices New starting prices
/// @param _endingPrices New ending prices
/// @param _duration New duration
/// @param _seller Address of the seller in all specified auctions to be updated
function repriceAuctions(
uint256[] _tokenIds,
uint256[] _startingPrices,
uint256[] _endingPrices,
uint256 _duration,
address _seller
)
public
canBeStoredWith64Bits(_duration)
{
require(msg.sender == address(nonFungibleContract));
uint64 timeNow = uint64(now);
for (uint32 i = 0; i < _tokenIds.length; i++) {
uint256 _tokenId = _tokenIds[i];
uint256 _startingPrice = _startingPrices[i];
uint256 _endingPrice = _endingPrices[i];
// Must be able to be stored in 128 bits
require(_startingPrice < 340282366920938463463374607431768211455);
require(_endingPrice < 340282366920938463463374607431768211455);
Auction storage auction = tokenIdToAuction[_tokenId];
// Here is where we make sure the seller in the auction is correct.
// Since this method can only be called by the NFT, the NFT controls
// what happens here by passing in the _seller we are to require.
if (auction.seller == _seller) {
// Update the auction parameters
auction.startingPrice = uint128(_startingPrice);
auction.endingPrice = uint128(_endingPrice);
auction.duration = uint64(_duration);
auction.startedAt = timeNow;
emit AuctionRepriced(_tokenId, _startingPrice, _endingPrice, uint64(_duration), timeNow);
}
}
}
/// @dev Place a bid to purchase multiple tokens in a single call.
/// @param _tokenIds Array of IDs of tokens to bid on.
function batchBid(uint256[] _tokenIds) public payable whenNotPaused
{
// Check to make sure the bid amount is sufficient to purchase
// all of the auctions specified.
uint256 totalPrice = 0;
for (uint32 i = 0; i < _tokenIds.length; i++) {
uint256 _tokenId = _tokenIds[i];
Auction storage auction = tokenIdToAuction[_tokenId];
totalPrice += _currentPrice(auction);
}
require(msg.value >= totalPrice);
// Loop through auctions, placing bids to buy
//
for (i = 0; i < _tokenIds.length; i++) {
_tokenId = _tokenIds[i];
auction = tokenIdToAuction[_tokenId];
// Need to store this before the _bid & _transfer calls
// so we can fire our auctionSuccessful events
address seller = auction.seller;
uint256 bid = _currentPrice(auction);
uint256 price = _bid(_tokenId, bid);
_transfer(msg.sender, _tokenId);
if (listener != address(0)) {
listener.auctionSuccessful(_tokenId, uint128(price), seller, msg.sender);
}
}
}
/// @dev Does exactly what the parent does, but also notifies any
/// listener of the successful bid.
/// @param _tokenId - ID of token to bid on.
function bid(uint256 _tokenId) public payable whenNotPaused
{
Auction storage auction = tokenIdToAuction[_tokenId];
// Need to store this before the _bid & _transfer calls
// so we can fire our auctionSuccessful events
address seller = auction.seller;
// _bid will throw if the bid or funds transfer fails
uint256 price = _bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
if (listener != address(0)) {
listener.auctionSuccessful(_tokenId, uint128(price), seller, msg.sender);
}
}
/// @dev Cancels an auction that hasn't been won yet by calling
/// the super(...) and then notifying any listener.
/// @param _tokenId - ID of token on auction
function cancelAuction(uint256 _tokenId) public
{
super.cancelAuction(_tokenId);
if (listener != address(0)) {
listener.auctionCancelled(_tokenId, msg.sender);
}
}
} | @dev Place a bid to purchase multiple tokens in a single call. @param _tokenIds Array of IDs of tokens to bid on. Check to make sure the bid amount is sufficient to purchase all of the auctions specified. Loop through auctions, placing bids to buy Need to store this before the _bid & _transfer calls so we can fire our auctionSuccessful events | function batchBid(uint256[] _tokenIds) public payable whenNotPaused
{
uint256 totalPrice = 0;
for (uint32 i = 0; i < _tokenIds.length; i++) {
uint256 _tokenId = _tokenIds[i];
Auction storage auction = tokenIdToAuction[_tokenId];
totalPrice += _currentPrice(auction);
}
require(msg.value >= totalPrice);
for (i = 0; i < _tokenIds.length; i++) {
_tokenId = _tokenIds[i];
auction = tokenIdToAuction[_tokenId];
address seller = auction.seller;
uint256 bid = _currentPrice(auction);
uint256 price = _bid(_tokenId, bid);
_transfer(msg.sender, _tokenId);
if (listener != address(0)) {
listener.auctionSuccessful(_tokenId, uint128(price), seller, msg.sender);
}
}
}
| 6,386,690 | [
1,
6029,
279,
9949,
358,
23701,
3229,
2430,
316,
279,
2202,
745,
18,
225,
389,
2316,
2673,
1510,
434,
7115,
434,
2430,
358,
9949,
603,
18,
2073,
358,
1221,
3071,
326,
9949,
3844,
353,
18662,
358,
23701,
777,
434,
326,
279,
4062,
87,
1269,
18,
9720,
3059,
279,
4062,
87,
16,
886,
5330,
30534,
358,
30143,
12324,
358,
1707,
333,
1865,
326,
389,
19773,
473,
389,
13866,
4097,
1427,
732,
848,
4452,
3134,
279,
4062,
14277,
2641,
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,
2581,
17763,
12,
11890,
5034,
8526,
389,
2316,
2673,
13,
1071,
8843,
429,
1347,
1248,
28590,
203,
565,
288,
203,
3639,
2254,
5034,
2078,
5147,
273,
374,
31,
203,
3639,
364,
261,
11890,
1578,
277,
273,
374,
31,
277,
411,
389,
2316,
2673,
18,
2469,
31,
277,
27245,
288,
203,
1850,
2254,
5034,
389,
2316,
548,
273,
389,
2316,
2673,
63,
77,
15533,
203,
1850,
432,
4062,
2502,
279,
4062,
273,
1147,
28803,
37,
4062,
63,
67,
2316,
548,
15533,
203,
1850,
2078,
5147,
1011,
389,
2972,
5147,
12,
69,
4062,
1769,
203,
3639,
289,
203,
3639,
2583,
12,
3576,
18,
1132,
1545,
2078,
5147,
1769,
203,
203,
3639,
364,
261,
77,
273,
374,
31,
277,
411,
389,
2316,
2673,
18,
2469,
31,
277,
27245,
288,
203,
203,
1850,
389,
2316,
548,
273,
389,
2316,
2673,
63,
77,
15533,
203,
1850,
279,
4062,
273,
1147,
28803,
37,
4062,
63,
67,
2316,
548,
15533,
203,
203,
1850,
1758,
29804,
273,
279,
4062,
18,
1786,
749,
31,
203,
203,
1850,
2254,
5034,
9949,
273,
389,
2972,
5147,
12,
69,
4062,
1769,
203,
1850,
2254,
5034,
6205,
273,
389,
19773,
24899,
2316,
548,
16,
9949,
1769,
203,
1850,
389,
13866,
12,
3576,
18,
15330,
16,
389,
2316,
548,
1769,
203,
203,
1850,
309,
261,
12757,
480,
1758,
12,
20,
3719,
288,
203,
5411,
2991,
18,
69,
4062,
14277,
24899,
2316,
548,
16,
2254,
10392,
12,
8694,
3631,
29804,
16,
1234,
18,
15330,
1769,
203,
1850,
289,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100
]
|
./full_match/80001/0xd04FDb47Ba15B85dfdC8657BEFBc5738EB4d880B/sources/contracts/interface/IDiamondCut.sol | Add=0, Replace=1, Remove=2 | interface IDiamondCut {
pragma solidity ^0.8.0;
enum FacetCutAction {Add, Replace, Remove}
struct FacetCut {
address facetAddress;
FacetCutAction action;
bytes4[] functionSelectors;
}
}
| 9,451,333 | [
1,
986,
33,
20,
16,
6910,
33,
21,
16,
3581,
33,
22,
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,
5831,
1599,
29401,
1434,
15812,
288,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
565,
2792,
31872,
15812,
1803,
288,
986,
16,
6910,
16,
3581,
97,
203,
565,
1958,
31872,
15812,
288,
203,
3639,
1758,
11082,
1887,
31,
203,
3639,
31872,
15812,
1803,
1301,
31,
203,
3639,
1731,
24,
8526,
445,
19277,
31,
203,
565,
289,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
contract Foo {
/// #if_succeeds abi.encode(v).length > 0;
function foo(uint v) public {
}
/// #if_succeeds abi.encodePacked(v).length > 0;
function foo1(uint v) public {
}
/// #if_succeeds abi.encodeWithSelector(bytes4(hex"01020304"), v).length > 0;
function foo2(uint v) public {
}
/// #if_succeeds abi.encodeWithSignature("dummy", v).length > 0;
function foo3(uint v) public {
}
}
| #if_succeeds abi.encodeWithSelector(bytes4(hex"01020304"), v).length > 0; | function foo2(uint v) public {
}
| 1,842,513 | [
1,
430,
67,
87,
5286,
5288,
87,
24126,
18,
3015,
1190,
4320,
12,
3890,
24,
12,
7118,
6,
1611,
3103,
4630,
3028,
6,
3631,
331,
2934,
2469,
405,
374,
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,
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,
445,
8431,
22,
12,
11890,
331,
13,
1071,
288,
203,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/56/0x1047FaC208FaBB3902CACD27f04304ACC4c348e7/sources/project_/contracts/characters.sol | technically next level
| uint requiredToLevel = experienceTable[char.level]; | 3,226,632 | [
1,
28012,
82,
6478,
1024,
1801,
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,
5411,
2254,
1931,
774,
2355,
273,
31207,
1388,
63,
3001,
18,
2815,
15533,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/56/0x8f63A11b8eCa1287E932F048140C0B68a92Bc155/sources/contracts/ForkBabyBUSD.sol | generate the uniswap pair path of weth -> busd make the swap | function swapTokensForBusd(uint256 tokenAmount, address recipient) private {
address[] memory path = new address[](3);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
path[2] = BUSDToken;
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
tokenAmount,
path,
recipient,
block.timestamp
);
}
| 3,244,389 | [
1,
7163,
326,
640,
291,
91,
438,
3082,
589,
434,
341,
546,
317,
5766,
72,
1221,
326,
7720,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
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,
7720,
5157,
1290,
7086,
72,
12,
11890,
5034,
1147,
6275,
16,
1758,
8027,
13,
3238,
288,
203,
3639,
203,
3639,
1758,
8526,
3778,
589,
273,
394,
1758,
8526,
12,
23,
1769,
203,
3639,
589,
63,
20,
65,
273,
1758,
12,
2211,
1769,
203,
3639,
589,
63,
21,
65,
273,
640,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
5621,
203,
3639,
589,
63,
22,
65,
273,
605,
3378,
40,
1345,
31,
203,
203,
3639,
389,
12908,
537,
12,
2867,
12,
2211,
3631,
1758,
12,
318,
291,
91,
438,
58,
22,
8259,
3631,
1147,
6275,
1769,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
18,
22270,
14332,
5157,
1290,
5157,
6289,
310,
14667,
1398,
5912,
5157,
12,
203,
5411,
1147,
6275,
16,
203,
5411,
589,
16,
203,
5411,
8027,
16,
203,
5411,
1203,
18,
5508,
203,
3639,
11272,
203,
540,
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
]
|
pragma solidity ^0.4.18;
interface ConflictResolutionInterface {
function minHouseStake(uint activeGames) public pure returns(uint);
function maxBalance() public pure returns(int);
function isValidBet(uint8 _gameType, uint _betNum, uint _betValue) public pure returns(bool);
function endGameConflict(
uint8 _gameType,
uint _betNum,
uint _betValue,
int _balance,
uint _stake,
bytes32 _serverSeed,
bytes32 _playerSeed
)
public
view
returns(int);
function serverForceGameEnd(
uint8 gameType,
uint _betNum,
uint _betValue,
int _balance,
uint _stake,
uint _endInitiatedTime
)
public
view
returns(int);
function playerForceGameEnd(
uint8 _gameType,
uint _betNum,
uint _betValue,
int _balance,
uint _stake,
uint _endInitiatedTime
)
public
view
returns(int);
}
library MathUtil {
/**
* @dev Returns the absolute value of _val.
* @param _val value
* @return The absolute value of _val.
*/
function abs(int _val) internal pure returns(uint) {
if (_val < 0) {
return uint(-_val);
} else {
return uint(_val);
}
}
/**
* @dev Calculate maximum.
*/
function max(uint _val1, uint _val2) internal pure returns(uint) {
return _val1 >= _val2 ? _val1 : _val2;
}
/**
* @dev Calculate minimum.
*/
function min(uint _val1, uint _val2) internal pure returns(uint) {
return _val1 <= _val2 ? _val1 : _val2;
}
}
contract Ownable {
address public owner;
event LogOwnerShipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Modifier, which throws if called by other account than owner.
*/
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/**
* @dev Set contract creator as initial owner
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Allows the current owner to transfer control of the
* contract to a newOwner _newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function setOwner(address _newOwner) public onlyOwner {
require(_newOwner != address(0));
LogOwnerShipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract ConflictResolutionManager is Ownable {
/// @dev Conflict resolution contract.
ConflictResolutionInterface public conflictRes;
/// @dev New Conflict resolution contract.
address public newConflictRes = 0;
/// @dev Time update of new conflict resolution contract was initiated.
uint public updateTime = 0;
/// @dev Min time before new conflict res contract can be activated after initiating update.
uint public constant MIN_TIMEOUT = 3 days;
/// @dev Min time before new conflict res contract can be activated after initiating update.
uint public constant MAX_TIMEOUT = 6 days;
/// @dev Update of conflict resolution contract was initiated.
event LogUpdatingConflictResolution(address newConflictResolutionAddress);
/// @dev New conflict resolution contract is active.
event LogUpdatedConflictResolution(address newConflictResolutionAddress);
/**
* @dev Constructor
* @param _conflictResAddress conflict resolution contract address.
*/
function ConflictResolutionManager(address _conflictResAddress) public {
conflictRes = ConflictResolutionInterface(_conflictResAddress);
}
/**
* @dev Initiate conflict resolution contract update.
* @param _newConflictResAddress New conflict resolution contract address.
*/
function updateConflictResolution(address _newConflictResAddress) public onlyOwner {
newConflictRes = _newConflictResAddress;
updateTime = block.timestamp;
LogUpdatingConflictResolution(_newConflictResAddress);
}
/**
* @dev Active new conflict resolution contract.
*/
function activateConflictResolution() public onlyOwner {
require(newConflictRes != 0);
require(updateTime != 0);
require(updateTime + MIN_TIMEOUT <= block.timestamp && block.timestamp <= updateTime + MAX_TIMEOUT);
conflictRes = ConflictResolutionInterface(newConflictRes);
newConflictRes = 0;
updateTime = 0;
LogUpdatedConflictResolution(newConflictRes);
}
}
contract Pausable is Ownable {
/// @dev Is contract paused.
bool public paused = false;
/// @dev Time pause was called
uint public timePaused = 0;
/// @dev Modifier, which only allows function execution if not paused.
modifier onlyNotPaused() {
require(!paused);
_;
}
/// @dev Modifier, which only allows function execution if paused.
modifier onlyPaused() {
require(paused);
_;
}
/// @dev Modifier, which only allows function execution if paused longer than timeSpan.
modifier onlyPausedSince(uint timeSpan) {
require(paused && timePaused + timeSpan <= block.timestamp);
_;
}
/// @dev Event is fired if paused.
event LogPause();
/// @dev Event is fired if pause is ended.
event LogUnpause();
/**
* @dev Pause contract. No new game sessions can be created.
*/
function pause() public onlyOwner onlyNotPaused {
paused = true;
timePaused = block.timestamp;
LogPause();
}
/**
* @dev Unpause contract.
*/
function unpause() public onlyOwner onlyPaused {
paused = false;
timePaused = 0;
LogUnpause();
}
}
contract Destroyable is Pausable {
/// @dev After pausing the contract for 20 days owner can selfdestruct it.
uint public constant TIMEOUT_DESTROY = 20 days;
/**
* @dev Destroy contract and transfer ether to address _targetAddress.
*/
function destroy() public onlyOwner onlyPausedSince(TIMEOUT_DESTROY) {
selfdestruct(owner);
}
}
contract GameChannelBase is Destroyable, ConflictResolutionManager {
/// @dev Different game session states.
enum GameStatus {
ENDED, ///< @dev Game session is ended.
ACTIVE, ///< @dev Game session is active.
WAITING_FOR_SERVER, ///< @dev Waiting for server to accept game session.
PLAYER_INITIATED_END, ///< @dev Player initiated non regular end.
SERVER_INITIATED_END ///< @dev Server initiated non regular end.
}
/// @dev Reason game session ended.
enum ReasonEnded {
REGULAR_ENDED, ///< @dev Game session is regularly ended.
END_FORCED_BY_SERVER, ///< @dev Player did not respond. Server forced end.
END_FORCED_BY_PLAYER, ///< @dev Server did not respond. Player forced end.
REJECTED_BY_SERVER, ///< @dev Server rejected game session.
CANCELLED_BY_PLAYER ///< @dev Player canceled game session before server accepted it.
}
struct Game {
/// @dev Game session status.
GameStatus status;
/// @dev Reason game session ended.
ReasonEnded reasonEnded;
/// @dev Player's stake.
uint stake;
/// @dev Last game round info if not regularly ended.
/// If game session is ended normally this data is not used.
uint8 gameType;
uint32 roundId;
uint16 betNum;
uint betValue;
int balance;
bytes32 playerSeed;
bytes32 serverSeed;
uint endInitiatedTime;
}
/// @dev Minimal time span between profit transfer.
uint public constant MIN_TRANSFER_TIMESPAN = 1 days;
/// @dev Maximal time span between profit transfer.
uint public constant MAX_TRANSFER_TIMSPAN = 6 * 30 days;
/// @dev Current active game sessions.
uint public activeGames = 0;
/// @dev Game session id counter. Points to next free game session slot. So gameIdCntr -1 is the
// number of game sessions created.
uint public gameIdCntr;
/// @dev Only this address can accept and end games.
address public serverAddress;
/// @dev Address to transfer profit to.
address public houseAddress;
/// @dev Current house stake.
uint public houseStake = 0;
/// @dev House profit since last profit transfer.
int public houseProfit = 0;
/// @dev Min value player needs to deposit for creating game session.
uint public minStake;
/// @dev Max value player can deposit for creating game session.
uint public maxStake;
/// @dev Timeout until next profit transfer is allowed.
uint public profitTransferTimeSpan = 14 days;
/// @dev Last time profit transferred to house.
uint public lastProfitTransferTimestamp;
bytes32 public typeHash;
/// @dev Maps gameId to game struct.
mapping (uint => Game) public gameIdGame;
/// @dev Maps player address to current player game id.
mapping (address => uint) public playerGameId;
/// @dev Maps player address to pending returns.
mapping (address => uint) public pendingReturns;
/// @dev Modifier, which only allows to execute if house stake is high enough.
modifier onlyValidHouseStake(uint _activeGames) {
uint minHouseStake = conflictRes.minHouseStake(_activeGames);
require(houseStake >= minHouseStake);
_;
}
/// @dev Modifier to check if value send fulfills player stake requirements.
modifier onlyValidValue() {
require(minStake <= msg.value && msg.value <= maxStake);
_;
}
/// @dev Modifier, which only allows server to call function.
modifier onlyServer() {
require(msg.sender == serverAddress);
_;
}
/// @dev Modifier, which only allows to set valid transfer timeouts.
modifier onlyValidTransferTimeSpan(uint transferTimeout) {
require(transferTimeout >= MIN_TRANSFER_TIMESPAN
&& transferTimeout <= MAX_TRANSFER_TIMSPAN);
_;
}
/// @dev This event is fired when player creates game session.
event LogGameCreated(address indexed player, uint indexed gameId, uint stake, bytes32 endHash);
/// @dev This event is fired when server rejects player's game.
event LogGameRejected(address indexed player, uint indexed gameId);
/// @dev This event is fired when server accepts player's game.
event LogGameAccepted(address indexed player, uint indexed gameId, bytes32 endHash);
/// @dev This event is fired when player requests conflict end.
event LogPlayerRequestedEnd(address indexed player, uint indexed gameId);
/// @dev This event is fired when server requests conflict end.
event LogServerRequestedEnd(address indexed player, uint indexed gameId);
/// @dev This event is fired when game session is ended.
event LogGameEnded(address indexed player, uint indexed gameId, ReasonEnded reason);
/// @dev this event is fired when owner modifies player's stake limits.
event LogStakeLimitsModified(uint minStake, uint maxStake);
/**
* @dev Contract constructor.
* @param _serverAddress Server address.
* @param _minStake Min value player needs to deposit to create game session.
* @param _maxStake Max value player can deposit to create game session.
* @param _conflictResAddress Conflict resolution contract address.
* @param _houseAddress House address to move profit to.
*/
function GameChannelBase(
address _serverAddress,
uint _minStake,
uint _maxStake,
address _conflictResAddress,
address _houseAddress,
uint _gameIdCntr
)
public
ConflictResolutionManager(_conflictResAddress)
{
require(_minStake > 0 && _minStake <= _maxStake);
require(_gameIdCntr > 0);
gameIdCntr = _gameIdCntr;
serverAddress = _serverAddress;
houseAddress = _houseAddress;
lastProfitTransferTimestamp = block.timestamp;
minStake = _minStake;
maxStake = _maxStake;
typeHash = keccak256(
"uint32 Round Id",
"uint8 Game Type",
"uint16 Number",
"uint Value (Wei)",
"int Current Balance (Wei)",
"bytes32 Server Hash",
"bytes32 Player Hash",
"uint Game Id",
"address Contract Address"
);
}
/**
* @notice Withdraw pending returns.
*/
function withdraw() public {
uint toTransfer = pendingReturns[msg.sender];
require(toTransfer > 0);
pendingReturns[msg.sender] = 0;
msg.sender.transfer(toTransfer);
}
/**
* @notice Transfer house profit to houseAddress.
*/
function transferProfitToHouse() public {
require(lastProfitTransferTimestamp + profitTransferTimeSpan <= block.timestamp);
if (houseProfit <= 0) {
// update last transfer timestamp
lastProfitTransferTimestamp = block.timestamp;
return;
}
// houseProfit is gt 0 => safe to cast
uint toTransfer = uint(houseProfit);
assert(houseStake >= toTransfer);
houseProfit = 0;
lastProfitTransferTimestamp = block.timestamp;
houseStake = houseStake - toTransfer;
houseAddress.transfer(toTransfer);
}
/**
* @dev Set profit transfer time span.
*/
function setProfitTransferTimeSpan(uint _profitTransferTimeSpan)
public
onlyOwner
onlyValidTransferTimeSpan(_profitTransferTimeSpan)
{
profitTransferTimeSpan = _profitTransferTimeSpan;
}
/**
* @dev Increase house stake by msg.value
*/
function addHouseStake() public payable onlyOwner {
houseStake += msg.value;
}
/**
* @dev Withdraw house stake.
*/
function withdrawHouseStake(uint value) public onlyOwner {
uint minHouseStake = conflictRes.minHouseStake(activeGames);
require(value <= houseStake && houseStake - value >= minHouseStake);
require(houseProfit <= 0 || uint(houseProfit) <= houseStake - value);
houseStake = houseStake - value;
owner.transfer(value);
}
/**
* @dev Withdraw house stake and profit.
*/
function withdrawAll() public onlyOwner onlyPausedSince(3 days) {
houseProfit = 0;
uint toTransfer = houseStake;
houseStake = 0;
owner.transfer(toTransfer);
}
/**
* @dev Set new house address.
* @param _houseAddress New house address.
*/
function setHouseAddress(address _houseAddress) public onlyOwner {
houseAddress = _houseAddress;
}
/**
* @dev Set stake min and max value.
* @param _minStake Min stake.
* @param _maxStake Max stake.
*/
function setStakeRequirements(uint _minStake, uint _maxStake) public onlyOwner {
require(_minStake > 0 && _minStake <= _maxStake);
minStake = _minStake;
maxStake = _maxStake;
LogStakeLimitsModified(minStake, maxStake);
}
/**
* @dev Close game session.
* @param _game Game session data.
* @param _gameId Id of game session.
* @param _playerAddress Player's address of game session.
* @param _reason Reason for closing game session.
* @param _balance Game session balance.
*/
function closeGame(
Game storage _game,
uint _gameId,
address _playerAddress,
ReasonEnded _reason,
int _balance
)
internal
{
_game.status = GameStatus.ENDED;
_game.reasonEnded = _reason;
_game.balance = _balance;
assert(activeGames > 0);
activeGames = activeGames - 1;
LogGameEnded(_playerAddress, _gameId, _reason);
}
/**
* @dev End game by paying out player and server.
* @param _game Game session to payout.
* @param _playerAddress Player's address.
*/
function payOut(Game storage _game, address _playerAddress) internal {
assert(_game.balance <= conflictRes.maxBalance());
assert(_game.status == GameStatus.ENDED);
assert(_game.stake <= maxStake);
assert((int(_game.stake) + _game.balance) >= 0);
uint valuePlayer = uint(int(_game.stake) + _game.balance);
if (_game.balance > 0 && int(houseStake) < _game.balance) {
// Should never happen!
// House is bankrupt.
// Payout left money.
valuePlayer = houseStake;
}
houseProfit = houseProfit - _game.balance;
int newHouseStake = int(houseStake) - _game.balance;
assert(newHouseStake >= 0);
houseStake = uint(newHouseStake);
pendingReturns[_playerAddress] += valuePlayer;
if (pendingReturns[_playerAddress] > 0) {
safeSend(_playerAddress);
}
}
/**
* @dev Send value of pendingReturns[_address] to _address.
* @param _address Address to send value to.
*/
function safeSend(address _address) internal {
uint valueToSend = pendingReturns[_address];
assert(valueToSend > 0);
pendingReturns[_address] = 0;
if (_address.send(valueToSend) == false) {
pendingReturns[_address] = valueToSend;
}
}
/**
* @dev Verify signature of given data. Throws on verification failure.
* @param _sig Signature of given data in the form of rsv.
* @param _address Address of signature signer.
*/
function verifySig(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress,
bytes _sig,
address _address
)
internal
view
{
// check if this is the correct contract
address contractAddress = this;
require(_contractAddress == contractAddress);
bytes32 roundHash = calcHash(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress
);
verify(
roundHash,
_sig,
_address
);
}
/**
* @dev Calculate typed hash of given data (compare eth_signTypedData).
* @return Hash of given data.
*/
function calcHash(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress
)
private
view
returns(bytes32)
{
bytes32 dataHash = keccak256(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress
);
return keccak256(typeHash, dataHash);
}
/**
* @dev Check if _sig is valid signature of _hash. Throws if invalid signature.
* @param _hash Hash to check signature of.
* @param _sig Signature of _hash.
* @param _address Address of signer.
*/
function verify(
bytes32 _hash,
bytes _sig,
address _address
)
private
pure
{
var (r, s, v) = signatureSplit(_sig);
address addressRecover = ecrecover(_hash, v, r, s);
require(addressRecover == _address);
}
/**
* @dev Split the given signature of the form rsv in r s v. v is incremented with 27 if
* it is below 2.
* @param _signature Signature to split.
* @return r s v
*/
function signatureSplit(bytes _signature)
private
pure
returns (bytes32 r, bytes32 s, uint8 v)
{
require(_signature.length == 65);
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := and(mload(add(_signature, 65)), 0xff)
}
if (v < 2) {
v = v + 27;
}
}
}
contract GameChannelConflict is GameChannelBase {
/**
* @dev Contract constructor.
* @param _serverAddress Server address.
* @param _minStake Min value player needs to deposit to create game session.
* @param _maxStake Max value player can deposit to create game session.
* @param _conflictResAddress Conflict resolution contract address
* @param _houseAddress House address to move profit to
*/
function GameChannelConflict(
address _serverAddress,
uint _minStake,
uint _maxStake,
address _conflictResAddress,
address _houseAddress,
uint _gameIdCtr
)
public
GameChannelBase(_serverAddress, _minStake, _maxStake, _conflictResAddress, _houseAddress, _gameIdCtr)
{
// nothing to do
}
/**
* @dev Used by server if player does not end game session.
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Balance before this bet.
* @param _serverHash Hash of server seed for this bet.
* @param _playerHash Hash of player seed for this bet.
* @param _gameId Game session id.
* @param _contractAddress Address of this contract.
* @param _playerSig Player signature of this bet.
* @param _playerAddress Address of player.
* @param _serverSeed Server seed for this bet.
* @param _playerSeed Player seed for this bet.
*/
function serverEndGameConflict(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress,
bytes _playerSig,
address _playerAddress,
bytes32 _serverSeed,
bytes32 _playerSeed
)
public
onlyServer
{
verifySig(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress,
_playerSig,
_playerAddress
);
serverEndGameConflictImpl(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_serverSeed,
_playerSeed,
_gameId,
_playerAddress
);
}
/**
* @notice Can be used by player if server does not answer to the end game session request.
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Balance before this bet.
* @param _serverHash Hash of server seed for this bet.
* @param _playerHash Hash of player seed for this bet.
* @param _gameId Game session id.
* @param _contractAddress Address of this contract.
* @param _serverSig Server signature of this bet.
* @param _playerSeed Player seed for this bet.
*/
function playerEndGameConflict(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress,
bytes _serverSig,
bytes32 _playerSeed
)
public
{
verifySig(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress,
_serverSig,
serverAddress
);
playerEndGameConflictImpl(
_roundId,
_gameType,
_num,
_value,
_balance,
_playerHash,
_playerSeed,
_gameId,
msg.sender
);
}
/**
* @notice Cancel active game without playing. Useful if server stops responding before
* one game is played.
* @param _gameId Game session id.
*/
function playerCancelActiveGame(uint _gameId) public {
address playerAddress = msg.sender;
uint gameId = playerGameId[playerAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId);
if (game.status == GameStatus.ACTIVE) {
game.endInitiatedTime = block.timestamp;
game.status = GameStatus.PLAYER_INITIATED_END;
LogPlayerRequestedEnd(msg.sender, gameId);
} else if (game.status == GameStatus.SERVER_INITIATED_END && game.roundId == 0) {
closeGame(game, gameId, playerAddress, ReasonEnded.REGULAR_ENDED, 0);
payOut(game, playerAddress);
} else {
revert();
}
}
/**
* @dev Cancel active game without playing. Useful if player starts game session and
* does not play.
* @param _playerAddress Players' address.
* @param _gameId Game session id.
*/
function serverCancelActiveGame(address _playerAddress, uint _gameId) public onlyServer {
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId);
if (game.status == GameStatus.ACTIVE) {
game.endInitiatedTime = block.timestamp;
game.status = GameStatus.SERVER_INITIATED_END;
LogServerRequestedEnd(msg.sender, gameId);
} else if (game.status == GameStatus.PLAYER_INITIATED_END && game.roundId == 0) {
closeGame(game, gameId, _playerAddress, ReasonEnded.REGULAR_ENDED, 0);
payOut(game, _playerAddress);
} else {
revert();
}
}
/**
* @dev Force end of game if player does not respond. Only possible after a certain period of time
* to give the player a chance to respond.
* @param _playerAddress Player's address.
*/
function serverForceGameEnd(address _playerAddress, uint _gameId) public onlyServer {
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId);
require(game.status == GameStatus.SERVER_INITIATED_END);
// theoretically we have enough data to calculate winner
// but as player did not respond assume he has lost.
int newBalance = conflictRes.serverForceGameEnd(
game.gameType,
game.betNum,
game.betValue,
game.balance,
game.stake,
game.endInitiatedTime
);
closeGame(game, gameId, _playerAddress, ReasonEnded.END_FORCED_BY_SERVER, newBalance);
payOut(game, _playerAddress);
}
/**
* @notice Force end of game if server does not respond. Only possible after a certain period of time
* to give the server a chance to respond.
*/
function playerForceGameEnd(uint _gameId) public {
address playerAddress = msg.sender;
uint gameId = playerGameId[playerAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId);
require(game.status == GameStatus.PLAYER_INITIATED_END);
int newBalance = conflictRes.playerForceGameEnd(
game.gameType,
game.betNum,
game.betValue,
game.balance,
game.stake,
game.endInitiatedTime
);
closeGame(game, gameId, playerAddress, ReasonEnded.END_FORCED_BY_PLAYER, newBalance);
payOut(game, playerAddress);
}
/**
* @dev Conflict handling implementation. Stores game data and timestamp if game
* is active. If server has already marked conflict for game session the conflict
* resolution contract is used (compare conflictRes).
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Balance before this bet.
* @param _playerHash Hash of player's seed for this bet.
* @param _playerSeed Player's seed for this bet.
* @param _gameId game Game session id.
* @param _playerAddress Player's address.
*/
function playerEndGameConflictImpl(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _playerHash,
bytes32 _playerSeed,
uint _gameId,
address _playerAddress
)
private
{
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
int maxBalance = conflictRes.maxBalance();
require(gameId == _gameId);
require(_roundId > 0);
require(keccak256(_playerSeed) == _playerHash);
require(_value <= game.stake);
require(-int(game.stake) <= _balance && _balance <= maxBalance); // save to cast as ranges are fixed
require(int(game.stake) + _balance - int(_value) >= 0); // save to cast as ranges are fixed
require(conflictRes.isValidBet(_gameType, _num, _value));
if (game.status == GameStatus.SERVER_INITIATED_END && game.roundId == _roundId) {
game.playerSeed = _playerSeed;
endGameConflict(game, gameId, _playerAddress);
} else if (game.status == GameStatus.ACTIVE
|| (game.status == GameStatus.SERVER_INITIATED_END && game.roundId < _roundId)) {
game.status = GameStatus.PLAYER_INITIATED_END;
game.endInitiatedTime = block.timestamp;
game.roundId = _roundId;
game.gameType = _gameType;
game.betNum = _num;
game.betValue = _value;
game.balance = _balance;
game.playerSeed = _playerSeed;
game.serverSeed = bytes32(0);
LogPlayerRequestedEnd(msg.sender, gameId);
} else {
revert();
}
}
/**
* @dev Conflict handling implementation. Stores game data and timestamp if game
* is active. If player has already marked conflict for game session the conflict
* resolution contract is used (compare conflictRes).
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Balance before this bet.
* @param _serverHash Hash of server's seed for this bet.
* @param _playerHash Hash of player's seed for this bet.
* @param _serverSeed Server's seed for this bet.
* @param _playerSeed Player's seed for this bet.
* @param _playerAddress Player's address.
*/
function serverEndGameConflictImpl(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
bytes32 _serverSeed,
bytes32 _playerSeed,
uint _gameId,
address _playerAddress
)
private
{
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
int maxBalance = conflictRes.maxBalance();
require(gameId == _gameId);
require(_roundId > 0);
require(keccak256(_serverSeed) == _serverHash);
require(keccak256(_playerSeed) == _playerHash);
require(_value <= game.stake);
require(-int(game.stake) <= _balance && _balance <= maxBalance); // save to cast as ranges are fixed
require(int(game.stake) + _balance - int(_value) >= 0); // save to cast as ranges are fixed
require(conflictRes.isValidBet(_gameType, _num, _value));
if (game.status == GameStatus.PLAYER_INITIATED_END && game.roundId == _roundId) {
game.serverSeed = _serverSeed;
endGameConflict(game, gameId, _playerAddress);
} else if (game.status == GameStatus.ACTIVE
|| (game.status == GameStatus.PLAYER_INITIATED_END && game.roundId < _roundId)) {
game.status = GameStatus.SERVER_INITIATED_END;
game.endInitiatedTime = block.timestamp;
game.roundId = _roundId;
game.gameType = _gameType;
game.betNum = _num;
game.betValue = _value;
game.balance = _balance;
game.serverSeed = _serverSeed;
game.playerSeed = _playerSeed;
LogServerRequestedEnd(_playerAddress, gameId);
} else {
revert();
}
}
/**
* @dev End conflicting game.
* @param _game Game session data.
* @param _gameId Game session id.
* @param _playerAddress Player's address.
*/
function endGameConflict(Game storage _game, uint _gameId, address _playerAddress) private {
int newBalance = conflictRes.endGameConflict(
_game.gameType,
_game.betNum,
_game.betValue,
_game.balance,
_game.stake,
_game.serverSeed,
_game.playerSeed
);
closeGame(_game, _gameId, _playerAddress, ReasonEnded.REGULAR_ENDED, newBalance);
payOut(_game, _playerAddress);
}
}
contract GameChannel is GameChannelConflict {
/**
* @dev contract constructor
* @param _serverAddress Server address.
* @param _minStake Min value player needs to deposit to create game session.
* @param _maxStake Max value player can deposit to create game session.
* @param _conflictResAddress Conflict resolution contract address.
* @param _houseAddress House address to move profit to.
*/
function GameChannel(
address _serverAddress,
uint _minStake,
uint _maxStake,
address _conflictResAddress,
address _houseAddress,
uint _gameIdCntr
)
public
GameChannelConflict(_serverAddress, _minStake, _maxStake, _conflictResAddress, _houseAddress, _gameIdCntr)
{
// nothing to do
}
/**
* @notice Create games session request. msg.value needs to be valid stake value.
* @param _endHash Last hash of the hash chain generated by the player.
*/
function createGame(bytes32 _endHash)
public
payable
onlyValidValue
onlyValidHouseStake(activeGames + 1)
onlyNotPaused
{
address playerAddress = msg.sender;
uint previousGameId = playerGameId[playerAddress];
Game storage game = gameIdGame[previousGameId];
require(game.status == GameStatus.ENDED);
uint gameId = gameIdCntr++;
playerGameId[playerAddress] = gameId;
Game storage newGame = gameIdGame[gameId];
newGame.stake = msg.value;
newGame.status = GameStatus.WAITING_FOR_SERVER;
activeGames = activeGames + 1;
LogGameCreated(playerAddress, gameId, msg.value, _endHash);
}
/**
* @notice Cancel game session waiting for server acceptance.
* @param _gameId Game session id.
*/
function cancelGame(uint _gameId) public {
address playerAddress = msg.sender;
uint gameId = playerGameId[playerAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId);
require(game.status == GameStatus.WAITING_FOR_SERVER);
closeGame(game, gameId, playerAddress, ReasonEnded.CANCELLED_BY_PLAYER, 0);
payOut(game, playerAddress);
}
/**
* @dev Called by the server to reject game session created by player with address
* _playerAddress.
* @param _playerAddress Players's address who created the game session.
* @param _gameId Game session id.
*/
function rejectGame(address _playerAddress, uint _gameId) public onlyServer {
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
require(_gameId == gameId);
require(game.status == GameStatus.WAITING_FOR_SERVER);
closeGame(game, gameId, _playerAddress, ReasonEnded.REJECTED_BY_SERVER, 0);
payOut(game, _playerAddress);
LogGameRejected(_playerAddress, gameId);
}
/**
* @dev Called by server to accept game session created by player with
* address _playerAddress.
* @param _playerAddress Player's address who created the game.
* @param _gameId Game id of game session.
* @param _endHash Last hash of the hash chain generated by the server.
*/
function acceptGame(address _playerAddress, uint _gameId, bytes32 _endHash)
public
onlyServer
{
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
require(_gameId == gameId);
require(game.status == GameStatus.WAITING_FOR_SERVER);
game.status = GameStatus.ACTIVE;
LogGameAccepted(_playerAddress, gameId, _endHash);
}
/**
* @dev Regular end game session. Used if player and house have both
* accepted current game session state.
* The game session with gameId _gameId is closed
* and the player paid out. This functions is called by the server after
* the player requested the termination of the current game session.
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Current balance.
* @param _serverHash Hash of server's seed for this bet.
* @param _playerHash Hash of player's seed for this bet.
* @param _gameId Game session id.
* @param _contractAddress Address of this contract.
* @param _playerAddress Address of player.
* @param _playerSig Player's signature of this bet.
*/
function serverEndGame(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress,
address _playerAddress,
bytes _playerSig
)
public
onlyServer
{
verifySig(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress,
_playerSig,
_playerAddress
);
regularEndGame(_playerAddress, _roundId, _gameType, _num, _value, _balance, _gameId, _contractAddress);
}
/**
* @notice Regular end game session. Normally not needed as server ends game (@see serverEndGame).
* Can be used by player if server does not end game session.
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Current balance.
* @param _serverHash Hash of server's seed for this bet.
* @param _playerHash Hash of player's seed for this bet.
* @param _gameId Game session id.
* @param _contractAddress Address of this contract.
* @param _serverSig Server's signature of this bet.
*/
function playerEndGame(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress,
bytes _serverSig
)
public
{
verifySig(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress,
_serverSig,
serverAddress
);
regularEndGame(msg.sender, _roundId, _gameType, _num, _value, _balance, _gameId, _contractAddress);
}
/**
* @dev Regular end game session implementation. Used if player and house have both
* accepted current game session state. The game session with gameId _gameId is closed
* and the player paid out.
* @param _playerAddress Address of player.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Current balance.
* @param _gameId Game session id.
* @param _contractAddress Address of this contract.
*/
function regularEndGame(
address _playerAddress,
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
uint _gameId,
address _contractAddress
)
private
{
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
address contractAddress = this;
int maxBalance = conflictRes.maxBalance();
require(_gameId == gameId);
require(_roundId > 0);
// save to cast as game.stake hash fixed range
require(-int(game.stake) <= _balance && _balance <= maxBalance);
require((_gameType == 0) && (_num == 0) && (_value == 0));
require(_contractAddress == contractAddress);
require(game.status == GameStatus.ACTIVE);
closeGame(game, gameId, _playerAddress, ReasonEnded.REGULAR_ENDED, _balance);
payOut(game, _playerAddress);
}
} | @dev Timeout until next profit transfer is allowed. | uint public profitTransferTimeSpan = 14 days;
| 1,034,097 | [
1,
2694,
3180,
1024,
450,
7216,
7412,
353,
2935,
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,
565,
2254,
1071,
450,
7216,
5912,
950,
6952,
273,
5045,
4681,
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
]
|
//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;
}
}
| 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];
}
| 918,544 | [
1,
2463,
326,
3796,
10067,
364,
279,
1147,
3082,
1377,
326,
3796,
10067,
353,
326,
11981,
1245,
309,
518,
1807,
392,
6827,
16,
1377,
471,
9742,
1245,
309,
518,
1807,
279,
9949,
10067,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
28782,
10513,
12,
654,
39,
3462,
357,
80,
67,
23465,
16,
4232,
39,
3462,
30143,
67,
23465,
13,
5381,
1135,
12,
11890,
13,
288,
203,
3639,
327,
389,
12729,
63,
87,
1165,
67,
23465,
6362,
70,
9835,
67,
23465,
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
]
|
pragma solidity ^0.4.4;
//contract to store donor details
//by Aditya Sahu
//TESTED, NO LOGICAL, SYNTAX OR RUNTIME ERRORS
// IGNORE 10 WARNINGS SHOWN MY REMIX IDE
contract Donorsol {
struct DonorRecord {
uint64 uid; //unique id for donor
string datetime; //store date and time
string organ; //organ name stored as a string
uint timestamp; //timestamp for blockchain
}
mapping(uint256 => DonorRecord) public records; //change1, map(keyvalue=>value)
struct Donor {
uint64 uid;
string name;
string birthdate;
string sex;
uint16 height;
uint16 weight;
string btype;
uint128[] recindex;
}
mapping(uint64 => Donor) public donors;
function createDonor(uint64 uniqueid )public returns (bool) {
var d = donors[uniqueid];
d.uid = uniqueid;
return true;
}
function updateDonorDetails(uint64 uniqueid,string name,string birthdate,string sex,uint16 height,uint16 weight,string btype)public returns(bool) {
var d = donors[uniqueid];
d.name = name;
d.birthdate = birthdate;
d.sex = sex;
d.height = height;
d.weight = weight;
d.btype = btype;
return true;
}
function createDonorRecord(uint64 uid,uint64 rid,string datetime,string organ)public returns (bool) {
uint128 realrid = uid+rid;
records[realrid].datetime = datetime;
records[realrid].organ = organ;
records[realrid].timestamp = now;
donors[uid].recindex.push(realrid); //very important statement
return true;
}
/*function getdonoruid(uint64 rid )public constant returns (uint64){
return donors[rid].uid;
}*/
function getridfromuid(uint64 uid )public constant returns (uint128[]) {
return donors[uid].recindex;
}
function getorgan(uint64 uid, uint128 rid )public constant returns (string) {
// var=donors[uid].
return records[uid+rid].organ;
}
function Donorsol(string _greeting) public {
return;
}
}
| function getdonoruid(uint64 rid )public constant returns (uint64){ | return donors[rid].uid;
| 12,914,371 | [
1,
915,
336,
19752,
280,
1911,
12,
11890,
1105,
10911,
262,
482,
5381,
1135,
261,
11890,
1105,
15329,
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,
4202,
327,
2727,
1383,
63,
1691,
8009,
1911,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma ton-solidity ^0.37.0;
import "../../contracts/utils/Stash.sol";
/**
* Error codes
* 100 - Method for the manager only
*/
contract IdleV2 is Stash {
/*************
* VARIABLES *
*************/
TvmCell private _certificateCode;
uint32 private _certificateDuration;
uint32 private _certificateProlongationPeriod;
uint32 private _certificateAuctionPeriod;
bool private _certificateCheckLeapYear;
TvmCell private _auctionCode;
uint32 private _auctionBidsDuration;
uint32 private _auctionSubmittingDuration;
uint32 private _auctionFinishDuration;
address private _manager;
uint32[] private _versionHistory;
/*************
* MODIFIERS *
*************/
modifier accept {
tvm.accept();
_;
}
modifier onlyManager {
require(msg.sender == _manager, 100, "Method for the manager only");
_;
}
/***************************
* EXTERNAL * ONLY MANAGER *
***************************/
function upgrade(TvmCell code) external onlyManager accept {
tvm.setcode(code);
tvm.setCurrentCode(code);
onCodeUpgrade();
}
/***********
* GETTERS *
***********/
function getVersionHistory() public view returns (uint32[] versionHistory) {
return _versionHistory;
}
function isIdle() public pure returns (bool idle) {
return true;
}
/*****************************
* PRIVATE * ON CODE UPGRADE *
*****************************/
function onCodeUpgrade() private {
_versionHistory.push(now);
}
} | ************************** EXTERNAL ONLY MANAGER / | function upgrade(TvmCell code) external onlyManager accept {
tvm.setcode(code);
tvm.setCurrentCode(code);
onCodeUpgrade();
}
| 2,549,094 | [
1,
2294,
11702,
225,
20747,
20972,
16302,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
8400,
12,
56,
3489,
4020,
981,
13,
3903,
1338,
1318,
2791,
288,
203,
3639,
268,
3489,
18,
542,
710,
12,
710,
1769,
203,
3639,
268,
3489,
18,
542,
3935,
1085,
12,
710,
1769,
203,
3639,
603,
1085,
10784,
5621,
203,
565,
289,
203,
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
]
|
/**
*Submitted for verification at Etherscan.io on 2021-05-16
*/
/*
https://powerpool.finance/
wrrrw r wrr
ppwr rrr wppr0 prwwwrp prwwwrp wr0
rr 0rrrwrrprpwp0 pp pr prrrr0 pp 0r prrrr0 0rwrrr pp pr prrrr0 prrrr0 r0
rrp pr wr00rrp prwww0 pp wr pp w00r prwwwpr 0rw prwww0 pp wr pp wr r0
r0rprprwrrrp pr0 pp wr pr pp rwwr wr 0r pp wr pr wr pr r0
prwr wrr0wpwr 00 www0 0w0ww www0 0w 00 www0 www0 0www0
wrr ww0rrrr
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/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.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-ethereum-package/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 OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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: @powerpool/poweroracle/contracts/interfaces/IPowerPoke.sol
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
interface IPowerPoke {
/*** CLIENT'S CONTRACT INTERFACE ***/
function authorizeReporter(uint256 userId_, address pokerKey_) external view;
function authorizeNonReporter(uint256 userId_, address pokerKey_) external view;
function authorizeNonReporterWithDeposit(
uint256 userId_,
address pokerKey_,
uint256 overrideMinDeposit_
) external view;
function authorizePoker(uint256 userId_, address pokerKey_) external view;
function authorizePokerWithDeposit(
uint256 userId_,
address pokerKey_,
uint256 overrideMinStake_
) external view;
function slashReporter(uint256 slasherId_, uint256 times_) external;
function reward(
uint256 userId_,
uint256 gasUsed_,
uint256 compensationPlan_,
bytes calldata pokeOptions_
) external;
/*** CLIENT OWNER INTERFACE ***/
function transferClientOwnership(address client_, address to_) external;
function addCredit(address client_, uint256 amount_) external;
function withdrawCredit(
address client_,
address to_,
uint256 amount_
) external;
function setReportIntervals(
address client_,
uint256 minReportInterval_,
uint256 maxReportInterval_
) external;
function setSlasherHeartbeat(address client_, uint256 slasherHeartbeat_) external;
function setGasPriceLimit(address client_, uint256 gasPriceLimit_) external;
function setFixedCompensations(
address client_,
uint256 eth_,
uint256 cvp_
) external;
function setBonusPlan(
address client_,
uint256 planId_,
bool active_,
uint64 bonusNominator_,
uint64 bonusDenominator_,
uint64 perGas_
) external;
function setMinimalDeposit(address client_, uint256 defaultMinDeposit_) external;
/*** POKER INTERFACE ***/
function withdrawRewards(uint256 userId_, address to_) external;
function setPokerKeyRewardWithdrawAllowance(uint256 userId_, bool allow_) external;
/*** OWNER INTERFACE ***/
function addClient(
address client_,
address owner_,
bool canSlash_,
uint256 gasPriceLimit_,
uint256 minReportInterval_,
uint256 maxReportInterval_
) external;
function setClientActiveFlag(address client_, bool active_) external;
function setCanSlashFlag(address client_, bool canSlash) external;
function setOracle(address oracle_) external;
function pause() external;
function unpause() external;
/*** GETTERS ***/
function creditOf(address client_) external view returns (uint256);
function ownerOf(address client_) external view returns (address);
function getMinMaxReportIntervals(address client_) external view returns (uint256 min, uint256 max);
function getSlasherHeartbeat(address client_) external view returns (uint256);
function getGasPriceLimit(address client_) external view returns (uint256);
function getPokerBonus(
address client_,
uint256 bonusPlanId_,
uint256 gasUsed_,
uint256 userDeposit_
) external view returns (uint256);
function getGasPriceFor(address client_) external view returns (uint256);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/interfaces/BMathInterface.sol
pragma solidity 0.6.12;
interface BMathInterface {
function calcInGivenOut(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 tokenAmountOut,
uint256 swapFee
) external pure returns (uint256 tokenAmountIn);
function calcSingleInGivenPoolOut(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 poolSupply,
uint256 totalWeight,
uint256 poolAmountOut,
uint256 swapFee
) external pure returns (uint256 tokenAmountIn);
}
// File: contracts/interfaces/BPoolInterface.sol
pragma solidity 0.6.12;
interface BPoolInterface is IERC20, BMathInterface {
function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external;
function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external;
function swapExactAmountIn(
address,
uint256,
address,
uint256,
uint256
) external returns (uint256, uint256);
function swapExactAmountOut(
address,
uint256,
address,
uint256,
uint256
) external returns (uint256, uint256);
function joinswapExternAmountIn(
address,
uint256,
uint256
) external returns (uint256);
function joinswapPoolAmountOut(
address,
uint256,
uint256
) external returns (uint256);
function exitswapPoolAmountIn(
address,
uint256,
uint256
) external returns (uint256);
function exitswapExternAmountOut(
address,
uint256,
uint256
) external returns (uint256);
function getDenormalizedWeight(address) external view returns (uint256);
function getBalance(address) external view returns (uint256);
function getSwapFee() external view returns (uint256);
function getTotalDenormalizedWeight() external view returns (uint256);
function getCommunityFee()
external
view
returns (
uint256,
uint256,
uint256,
address
);
function calcAmountWithCommunityFee(
uint256,
uint256,
address
) external view returns (uint256, uint256);
function getRestrictions() external view returns (address);
function isPublicSwap() external view returns (bool);
function isFinalized() external view returns (bool);
function isBound(address t) external view returns (bool);
function getCurrentTokens() external view returns (address[] memory tokens);
function getFinalTokens() external view returns (address[] memory tokens);
function setSwapFee(uint256) external;
function setCommunityFeeAndReceiver(
uint256,
uint256,
uint256,
address
) external;
function setController(address) external;
function setPublicSwap(bool) external;
function finalize() external;
function bind(
address,
uint256,
uint256
) external;
function rebind(
address,
uint256,
uint256
) external;
function unbind(address) external;
function gulp(address) external;
function callVoting(
address voting,
bytes4 signature,
bytes calldata args,
uint256 value
) external;
function getMinWeight() external view returns (uint256);
function getMaxBoundTokens() external view returns (uint256);
}
// File: contracts/interfaces/PowerIndexPoolInterface.sol
pragma solidity 0.6.12;
interface PowerIndexPoolInterface is BPoolInterface {
function initialize(
string calldata name,
string calldata symbol,
uint256 minWeightPerSecond,
uint256 maxWeightPerSecond
) external;
function bind(
address,
uint256,
uint256,
uint256,
uint256
) external;
function setDynamicWeight(
address token,
uint256 targetDenorm,
uint256 fromTimestamp,
uint256 targetTimestamp
) external;
function getDynamicWeightSettings(address token)
external
view
returns (
uint256 fromTimestamp,
uint256 targetTimestamp,
uint256 fromDenorm,
uint256 targetDenorm
);
function getMinWeight() external view override returns (uint256);
function getWeightPerSecondBounds() external view returns (uint256, uint256);
function setWeightPerSecondBounds(uint256, uint256) external;
function setWrapper(address, bool) external;
function getWrapperMode() external view returns (bool);
}
// File: contracts/interfaces/TokenInterface.sol
pragma solidity 0.6.12;
interface TokenInterface is IERC20 {
function deposit() external payable;
function withdraw(uint256) external;
}
// File: contracts/interfaces/ICurveDepositor2.sol
pragma solidity 0.6.12;
interface ICurveDepositor2 {
function add_liquidity(uint256[2] memory _amounts, uint256 _min_mint_amount) external;
function calc_token_amount(uint256[2] memory _amounts, bool _deposit) external view returns (uint256);
}
// File: contracts/interfaces/ICurveDepositor3.sol
pragma solidity 0.6.12;
interface ICurveDepositor3 {
function add_liquidity(uint256[3] memory _amounts, uint256 _min_mint_amount) external;
function calc_token_amount(uint256[3] memory _amounts, bool _deposit) external view returns (uint256);
}
// File: contracts/interfaces/ICurveDepositor4.sol
pragma solidity 0.6.12;
interface ICurveDepositor4 {
function add_liquidity(uint256[4] memory _amounts, uint256 _min_mint_amount) external;
function calc_token_amount(uint256[4] memory _amounts, bool _deposit) external view returns (uint256);
}
// File: contracts/interfaces/IVault.sol
pragma solidity ^0.6.0;
interface IVault {
function token() external view returns (address);
function totalAssets() external view returns (uint256);
function balanceOf(address _acc) external view returns (uint256);
function pricePerShare() external view returns (uint256);
function deposit(uint256 _amount) external;
function withdraw(uint256 _amount) external;
}
// File: contracts/interfaces/ICurvePoolRegistry.sol
pragma solidity 0.6.12;
interface ICurvePoolRegistry {
function get_virtual_price_from_lp_token(address _token) external view returns (uint256);
}
// File: contracts/interfaces/IErc20PiptSwap.sol
pragma solidity 0.6.12;
interface IErc20PiptSwap {
function swapEthToPipt(uint256 _slippage) external payable returns (uint256 poolAmountOutAfterFee, uint256 oddEth);
function swapErc20ToPipt(
address _swapToken,
uint256 _swapAmount,
uint256 _slippage
) external payable returns (uint256 poolAmountOut);
function defaultSlippage() external view returns (uint256);
function swapPiptToEth(uint256 _poolAmountIn) external payable returns (uint256 ethOutAmount);
function swapPiptToErc20(address _swapToken, uint256 _poolAmountIn) external payable returns (uint256 erc20Out);
}
// File: contracts/interfaces/IErc20VaultPoolSwap.sol
pragma solidity 0.6.12;
interface IErc20VaultPoolSwap {
function swapErc20ToVaultPool(
address _pool,
address _swapToken,
uint256 _swapAmount
) external returns (uint256 poolAmountOut);
function swapVaultPoolToErc20(
address _pool,
uint256 _poolAmountIn,
address _swapToken
) external returns (uint256 erc20Out);
}
// File: contracts/IndicesSupplyRedeemZap.sol
pragma solidity 0.6.12;
contract IndicesSupplyRedeemZap is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event InitRound(
bytes32 indexed key,
address indexed pool,
uint256 endTime,
address indexed inputToken,
address outputToken
);
event FinishRound(
bytes32 indexed key,
address indexed pool,
address indexed inputToken,
uint256 totalInputAmount,
uint256 inputCap,
uint256 initEndTime,
uint256 finishEndTime
);
event SetFee(address indexed token, uint256 fee);
event TakeFee(address indexed pool, address indexed token, uint256 amount);
event ClaimFee(address indexed token, uint256 amount);
event SetRoundPeriod(uint256 roundPeriod);
event SetPool(address indexed pool, PoolType pType);
event SetPiptSwap(address indexed pool, address piptSwap);
event SetTokenCap(address indexed token, uint256 cap);
event Deposit(
bytes32 indexed roundKey,
address indexed pool,
address indexed user,
address inputToken,
uint256 inputAmount
);
event Withdraw(
bytes32 indexed roundKey,
address indexed pool,
address indexed user,
address inputToken,
uint256 inputAmount
);
event SupplyAndRedeemPoke(
bytes32 indexed roundKey,
address indexed pool,
address indexed inputToken,
address outputToken,
uint256 totalInputAmount,
uint256 totalOutputAmount
);
event ClaimPoke(
bytes32 indexed roundKey,
address indexed pool,
address indexed claimFor,
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount
);
uint256 internal constant COMPENSATION_PLAN_1_ID = 1;
address public constant ETH = 0x0000000000000000000000000000000000000001;
IERC20 public immutable usdc;
IPowerPoke public immutable powerPoke;
enum PoolType { NULL, PIPT, VAULT }
mapping(address => PoolType) public poolType;
mapping(address => address) public poolSwapContract;
mapping(address => uint256) public tokenCap;
// TODO: delete on proxy replace
mapping(address => address[]) public poolTokens;
// TODO: delete on proxy replace
struct VaultConfig {
uint256 depositorLength;
uint256 depositorIndex;
address depositor;
address lpToken;
address vaultRegistry;
}
mapping(address => VaultConfig) public vaultConfig;
uint256 public roundPeriod;
// TODO: delete on proxy replace
address public feeReceiver;
mapping(address => uint256) public feeByToken;
mapping(address => uint256) public pendingFeeByToken;
mapping(address => uint256) public pendingOddTokens;
struct Round {
uint256 startBlock;
address inputToken;
address outputToken;
address pool;
mapping(address => uint256) inputAmount;
uint256 totalInputAmount;
mapping(address => uint256) outputAmount;
uint256 totalOutputAmount;
uint256 totalOutputAmountClaimed;
uint256 endTime;
}
mapping(bytes32 => Round) public rounds;
mapping(bytes32 => bytes32) public lastRoundByPartialKey;
modifier onlyReporter(uint256 _reporterId, bytes calldata _rewardOpts) {
uint256 gasStart = gasleft();
powerPoke.authorizeReporter(_reporterId, msg.sender);
_;
_reward(_reporterId, gasStart, COMPENSATION_PLAN_1_ID, _rewardOpts);
}
modifier onlyNonReporter(uint256 _reporterId, bytes calldata _rewardOpts) {
uint256 gasStart = gasleft();
powerPoke.authorizeNonReporter(_reporterId, msg.sender);
_;
_reward(_reporterId, gasStart, COMPENSATION_PLAN_1_ID, _rewardOpts);
}
modifier onlyEOA() {
require(tx.origin == msg.sender, "ONLY_EOA");
_;
}
constructor(address _usdc, address _powerPoke) public {
usdc = IERC20(_usdc);
powerPoke = IPowerPoke(_powerPoke);
}
function initialize(uint256 _roundPeriod) external initializer {
__Ownable_init();
roundPeriod = _roundPeriod;
}
receive() external payable {
pendingOddTokens[ETH] = pendingOddTokens[ETH].add(msg.value);
}
/* ========== Client Functions ========== */
function depositEth(address _pool) external payable onlyEOA {
require(poolType[_pool] == PoolType.PIPT, "NS_POOL");
_deposit(_pool, ETH, _pool, msg.value);
}
function depositErc20(
address _pool,
address _inputToken,
uint256 _amount
) external onlyEOA {
require(poolType[_pool] != PoolType.NULL, "UP");
require(_inputToken == address(usdc), "NS_TOKEN");
_deposit(_pool, _inputToken, _pool, _amount);
}
function depositPoolToken(
address _pool,
address _outputToken,
uint256 _poolAmount
) external onlyEOA {
PoolType pType = poolType[_pool];
require(pType != PoolType.NULL, "UP");
if (pType == PoolType.PIPT) {
require(_outputToken == address(usdc) || _outputToken == ETH, "NS_TOKEN");
} else {
require(_outputToken == address(usdc), "NS_TOKEN");
}
_deposit(_pool, _pool, _outputToken, _poolAmount);
}
function withdrawEth(address _pool, uint256 _amount) external onlyEOA {
require(poolType[_pool] == PoolType.PIPT, "NS_POOL");
_withdraw(_pool, ETH, _pool, _amount);
}
function withdrawErc20(
address _pool,
address _outputToken,
uint256 _amount
) external onlyEOA {
require(poolType[_pool] != PoolType.NULL, "UP");
require(_outputToken != ETH, "ETH_CANT_BE_OT");
_withdraw(_pool, _outputToken, _pool, _amount);
}
function withdrawPoolToken(
address _pool,
address _outputToken,
uint256 _amount
) external onlyEOA {
PoolType pType = poolType[_pool];
require(pType != PoolType.NULL, "UP");
if (pType == PoolType.PIPT) {
require(_outputToken == address(usdc) || _outputToken == ETH, "NS_TOKEN");
} else {
require(_outputToken == address(usdc), "NS_TOKEN");
}
_withdraw(_pool, _pool, _outputToken, _amount);
}
/* ========== Poker Functions ========== */
function supplyAndRedeemPokeFromReporter(
uint256 _reporterId,
bytes32[] memory _roundKeys,
bytes calldata _rewardOpts
) external onlyReporter(_reporterId, _rewardOpts) onlyEOA {
_supplyAndRedeemPoke(_roundKeys, false);
}
function supplyAndRedeemPokeFromSlasher(
uint256 _reporterId,
bytes32[] memory _roundKeys,
bytes calldata _rewardOpts
) external onlyNonReporter(_reporterId, _rewardOpts) onlyEOA {
_supplyAndRedeemPoke(_roundKeys, true);
}
function claimPokeFromReporter(
uint256 _reporterId,
bytes32 _roundKey,
address[] memory _claimForList,
bytes calldata _rewardOpts
) external onlyReporter(_reporterId, _rewardOpts) onlyEOA {
_claimPoke(_roundKey, _claimForList, false);
}
function claimPokeFromSlasher(
uint256 _reporterId,
bytes32 _roundKey,
address[] memory _claimForList,
bytes calldata _rewardOpts
) external onlyNonReporter(_reporterId, _rewardOpts) onlyEOA {
_claimPoke(_roundKey, _claimForList, true);
}
/* ========== Owner Functions ========== */
function setRoundPeriod(uint256 _roundPeriod) external onlyOwner {
roundPeriod = _roundPeriod;
emit SetRoundPeriod(roundPeriod);
}
function setPools(address[] memory _pools, PoolType[] memory _types) external onlyOwner {
uint256 len = _pools.length;
require(len == _types.length, "L");
for (uint256 i = 0; i < len; i++) {
poolType[_pools[i]] = _types[i];
_updatePool(_pools[i]);
emit SetPool(_pools[i], _types[i]);
}
}
function setPoolsSwapContracts(address[] memory _pools, address[] memory _swapContracts) external onlyOwner {
uint256 len = _pools.length;
require(len == _swapContracts.length, "L");
for (uint256 i = 0; i < len; i++) {
poolSwapContract[_pools[i]] = _swapContracts[i];
usdc.approve(_swapContracts[i], uint256(-1));
IERC20(_pools[i]).approve(_swapContracts[i], uint256(-1));
emit SetPiptSwap(_pools[i], _swapContracts[i]);
}
}
function setTokensCap(address[] memory _tokens, uint256[] memory _caps) external onlyOwner {
uint256 len = _tokens.length;
require(len == _caps.length, "L");
for (uint256 i = 0; i < len; i++) {
tokenCap[_tokens[i]] = _caps[i];
emit SetTokenCap(_tokens[i], _caps[i]);
}
}
function updatePools(address[] memory _pools) external onlyOwner {
uint256 len = _pools.length;
for (uint256 i = 0; i < len; i++) {
_updatePool(_pools[i]);
}
}
/* ========== View Functions ========== */
function getCurrentBlockRoundKey(
address pool,
address inputToken,
address outputToken
) public view returns (bytes32) {
return getRoundKey(block.number, pool, inputToken, outputToken);
}
function getRoundKey(
uint256 blockNumber,
address pool,
address inputToken,
address outputToken
) public view returns (bytes32) {
return keccak256(abi.encodePacked(blockNumber, pool, inputToken, outputToken));
}
function getRoundPartialKey(
address pool,
address inputToken,
address outputToken
) public view returns (bytes32) {
return keccak256(abi.encodePacked(pool, inputToken, outputToken));
}
function getLastRoundKey(
address pool,
address inputToken,
address outputToken
) external view returns (bytes32) {
return lastRoundByPartialKey[getRoundPartialKey(pool, inputToken, outputToken)];
}
function isRoundReadyToExecute(bytes32 roundKey) public view returns (bool) {
Round storage round = rounds[roundKey];
if (tokenCap[round.inputToken] == 0) {
return round.endTime <= block.timestamp;
}
if (round.totalInputAmount == 0) {
return false;
}
return round.totalInputAmount >= tokenCap[round.inputToken] || round.endTime <= block.timestamp;
}
function getRoundUserInput(bytes32 roundKey, address user) external view returns (uint256) {
return rounds[roundKey].inputAmount[user];
}
function getRoundUserOutput(bytes32 roundKey, address user) external view returns (uint256) {
return rounds[roundKey].outputAmount[user];
}
/* ========== Internal Functions ========== */
function _deposit(
address _pool,
address _inputToken,
address _outputToken,
uint256 _amount
) internal {
require(_amount > 0, "NA");
bytes32 roundKey = _updateRound(_pool, _inputToken, _outputToken);
if (_inputToken != ETH) {
IERC20(_inputToken).safeTransferFrom(msg.sender, address(this), _amount);
}
Round storage round = rounds[roundKey];
round.inputAmount[msg.sender] = round.inputAmount[msg.sender].add(_amount);
round.totalInputAmount = round.totalInputAmount.add(_amount);
require(round.inputAmount[msg.sender] == 0 || round.inputAmount[msg.sender] > 1e5, "MIN_INPUT");
emit Deposit(roundKey, _pool, msg.sender, _inputToken, _amount);
}
function _withdraw(
address _pool,
address _inputToken,
address _outputToken,
uint256 _amount
) internal {
require(_amount > 0, "NA");
bytes32 roundKey = _updateRound(_pool, _inputToken, _outputToken);
Round storage round = rounds[roundKey];
round.inputAmount[msg.sender] = round.inputAmount[msg.sender].sub(_amount);
round.totalInputAmount = round.totalInputAmount.sub(_amount);
require(round.inputAmount[msg.sender] == 0 || round.inputAmount[msg.sender] > 1e5, "MIN_INPUT");
if (_inputToken == ETH) {
msg.sender.transfer(_amount);
} else {
IERC20(_inputToken).safeTransfer(msg.sender, _amount);
}
emit Withdraw(roundKey, _pool, msg.sender, _inputToken, _amount);
}
function _supplyAndRedeemPoke(bytes32[] memory _roundKeys, bool _bySlasher) internal {
(uint256 minInterval, uint256 maxInterval) = _getMinMaxReportInterval();
uint256 len = _roundKeys.length;
require(len > 0, "L");
for (uint256 i = 0; i < len; i++) {
Round storage round = rounds[_roundKeys[i]];
_updateRound(round.pool, round.inputToken, round.outputToken);
_checkRoundBeforeExecute(_roundKeys[i], round);
require(round.endTime + minInterval <= block.timestamp, "MIN_I");
if (_bySlasher) {
require(round.endTime + maxInterval <= block.timestamp, "MAX_I");
}
require(round.inputToken == round.pool || round.outputToken == round.pool, "UA");
if (round.inputToken == round.pool) {
_redeemPool(round, round.totalInputAmount);
} else {
_supplyPool(round, round.totalInputAmount);
}
require(round.totalOutputAmount != 0, "NULL_TO");
emit SupplyAndRedeemPoke(
_roundKeys[i],
round.pool,
round.inputToken,
round.outputToken,
round.totalInputAmount,
round.totalOutputAmount
);
}
}
function _supplyPool(Round storage round, uint256 totalInputAmount) internal {
PoolType pType = poolType[round.pool];
if (pType == PoolType.PIPT) {
IErc20PiptSwap piptSwap = IErc20PiptSwap(payable(poolSwapContract[round.pool]));
if (round.inputToken == ETH) {
(round.totalOutputAmount, ) = piptSwap.swapEthToPipt{ value: totalInputAmount }(piptSwap.defaultSlippage());
} else {
round.totalOutputAmount = piptSwap.swapErc20ToPipt(
round.inputToken,
totalInputAmount,
piptSwap.defaultSlippage()
);
}
} else if (pType == PoolType.VAULT) {
IErc20VaultPoolSwap vaultPoolSwap = IErc20VaultPoolSwap(poolSwapContract[round.pool]);
round.totalOutputAmount = vaultPoolSwap.swapErc20ToVaultPool(round.pool, address(usdc), totalInputAmount);
}
}
function _redeemPool(Round storage round, uint256 totalInputAmount) internal {
PoolType pType = poolType[round.pool];
if (pType == PoolType.PIPT) {
IErc20PiptSwap piptSwap = IErc20PiptSwap(payable(poolSwapContract[round.pool]));
if (round.inputToken == ETH) {
round.totalOutputAmount = piptSwap.swapPiptToEth(totalInputAmount);
} else {
round.totalOutputAmount = piptSwap.swapPiptToErc20(round.outputToken, totalInputAmount);
}
} else if (pType == PoolType.VAULT) {
IErc20VaultPoolSwap vaultPoolSwap = IErc20VaultPoolSwap(poolSwapContract[round.pool]);
round.totalOutputAmount = vaultPoolSwap.swapVaultPoolToErc20(round.pool, totalInputAmount, address(usdc));
}
}
function _claimPoke(
bytes32 _roundKey,
address[] memory _claimForList,
bool _bySlasher
) internal {
(uint256 minInterval, uint256 maxInterval) = _getMinMaxReportInterval();
uint256 len = _claimForList.length;
require(len > 0, "L");
Round storage round = rounds[_roundKey];
require(round.endTime + minInterval <= block.timestamp, "MIN_I");
if (_bySlasher) {
require(round.endTime + maxInterval <= block.timestamp, "MAX_I");
}
require(round.totalOutputAmount != 0, "NULL_TO");
for (uint256 i = 0; i < len; i++) {
address _claimFor = _claimForList[i];
require(round.inputAmount[_claimFor] != 0, "INPUT_NULL");
require(round.outputAmount[_claimFor] == 0, "OUTPUT_NOT_NULL");
uint256 inputShare = round.inputAmount[_claimFor].mul(1 ether).div(round.totalInputAmount);
uint256 outputAmount = round.totalOutputAmount.mul(inputShare).div(1 ether);
round.outputAmount[_claimFor] = outputAmount;
round.totalOutputAmountClaimed = round.totalOutputAmountClaimed.add(outputAmount).add(10);
IERC20(round.outputToken).safeTransfer(_claimFor, outputAmount - 1);
emit ClaimPoke(
_roundKey,
round.pool,
_claimFor,
round.inputToken,
round.outputToken,
round.inputAmount[_claimFor],
outputAmount
);
}
}
function _checkRoundBeforeExecute(bytes32 _roundKey, Round storage round) internal {
bytes32 partialKey = getRoundPartialKey(round.pool, round.inputToken, round.outputToken);
require(lastRoundByPartialKey[partialKey] != _roundKey, "CUR_ROUND");
require(round.totalInputAmount != 0, "TI_NULL");
require(round.totalOutputAmount == 0, "TO_NOT_NULL");
}
function _updateRound(
address _pool,
address _inputToken,
address _outputToken
) internal returns (bytes32 roundKey) {
bytes32 partialKey = getRoundPartialKey(_pool, _inputToken, _outputToken);
roundKey = lastRoundByPartialKey[partialKey];
if (roundKey == bytes32(0) || isRoundReadyToExecute(roundKey)) {
if (roundKey != bytes32(0)) {
emit FinishRound(
roundKey,
_pool,
_inputToken,
rounds[roundKey].totalInputAmount,
tokenCap[_inputToken],
rounds[roundKey].endTime,
block.timestamp
);
rounds[roundKey].endTime = block.timestamp;
}
roundKey = getCurrentBlockRoundKey(_pool, _inputToken, _outputToken);
rounds[roundKey].startBlock = block.number;
rounds[roundKey].pool = _pool;
rounds[roundKey].inputToken = _inputToken;
rounds[roundKey].outputToken = _outputToken;
rounds[roundKey].endTime = block.timestamp.add(roundPeriod);
lastRoundByPartialKey[partialKey] = roundKey;
emit InitRound(roundKey, _pool, rounds[roundKey].endTime, _inputToken, _outputToken);
}
return roundKey;
}
function _updatePool(address _pool) internal {
poolTokens[_pool] = PowerIndexPoolInterface(_pool).getCurrentTokens();
if (poolType[_pool] == PoolType.VAULT) {
uint256 len = poolTokens[_pool].length;
for (uint256 i = 0; i < len; i++) {
IERC20(poolTokens[_pool][i]).approve(_pool, uint256(-1));
}
}
}
function _reward(
uint256 _reporterId,
uint256 _gasStart,
uint256 _compensationPlan,
bytes calldata _rewardOpts
) internal {
powerPoke.reward(_reporterId, _gasStart.sub(gasleft()), _compensationPlan, _rewardOpts);
}
function _getMinMaxReportInterval() internal view returns (uint256 min, uint256 max) {
(min, max) = powerPoke.getMinMaxReportIntervals(address(this));
min = min == 1 ? 0 : min;
}
} | TODO: delete on proxy replace | address public feeReceiver;
| 10,719,212 | [
1,
6241,
30,
1430,
603,
2889,
1453,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
1758,
1071,
14036,
12952,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/42/0x76263Fb6257A5eEBBA2d23a00073760C7Fa49417/sources/ShadowsState.sol | * @notice The remaining synths an issuer can issue against their total shadows balance. @param _issuer The account that intends to issue/ Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. | function remainingIssuableSynths(address _issuer)
public
view
returns (
uint,
uint
)
{
uint alreadyIssued = debtBalanceOf(_issuer, xUSD);
uint maxIssuable = maxIssuableSynths(_issuer);
if (alreadyIssued >= maxIssuable) {
maxIssuable = 0;
maxIssuable = maxIssuable.sub(alreadyIssued);
}
return (maxIssuable, alreadyIssued);
}
| 3,408,203 | [
1,
1986,
4463,
6194,
451,
87,
392,
9715,
848,
5672,
5314,
3675,
2078,
10510,
87,
11013,
18,
225,
389,
17567,
1021,
2236,
716,
509,
5839,
358,
5672,
19,
7615,
1404,
1608,
358,
866,
364,
6194,
451,
2062,
578,
14067,
17544,
2724,
943,
7568,
89,
429,
10503,
451,
87,
903,
741,
518,
364,
584,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4463,
7568,
89,
429,
10503,
451,
87,
12,
2867,
389,
17567,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
203,
5411,
2254,
16,
203,
5411,
2254,
203,
3639,
262,
203,
565,
288,
203,
3639,
2254,
1818,
7568,
5957,
273,
18202,
88,
13937,
951,
24899,
17567,
16,
619,
3378,
40,
1769,
203,
3639,
2254,
943,
7568,
89,
429,
273,
943,
7568,
89,
429,
10503,
451,
87,
24899,
17567,
1769,
203,
203,
3639,
309,
261,
17583,
7568,
5957,
1545,
943,
7568,
89,
429,
13,
288,
203,
5411,
943,
7568,
89,
429,
273,
374,
31,
203,
5411,
943,
7568,
89,
429,
273,
943,
7568,
89,
429,
18,
1717,
12,
17583,
7568,
5957,
1769,
203,
3639,
289,
203,
3639,
327,
261,
1896,
7568,
89,
429,
16,
1818,
7568,
5957,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/AccessControl.sol";
contract AccessController is AccessControl {
bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
constructor() public {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MANAGER_ROLE, msg.sender);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/IMerkleDistributor.sol";
contract MerkleDistributor is IMerkleDistributor, Ownable {
address public immutable override token;
bytes32 public immutable override merkleRoot;
uint256 public immutable override endTime;
// This is a packed array of booleans.
mapping(uint256 => uint256) private _claimedBitMap;
constructor(
address _token,
bytes32 _merkleRoot,
uint256 _endTime
) public {
token = _token;
merkleRoot = _merkleRoot;
require(block.timestamp < _endTime, "Invalid endTime");
endTime = _endTime;
}
/** @dev Modifier to check that claim period is active.*/
modifier whenActive() {
require(isActive(), "Claim period has ended");
_;
}
function claim(
uint256 _index,
address _account,
uint256 _amount,
bytes32[] calldata merkleProof
) external override whenActive {
require(!isClaimed(_index), "Drop already claimed");
// Verify the merkle proof.
bytes32 node = keccak256(abi.encodePacked(_index, _account, _amount));
require(MerkleProof.verify(merkleProof, merkleRoot, node), "Invalid proof");
// Mark it claimed and send the token.
_setClaimed(_index);
require(IERC20(token).transfer(_account, _amount), "Transfer failed");
emit Claimed(_index, _account, _amount);
}
function isClaimed(uint256 _index) public view override returns (bool) {
uint256 claimedWordIndex = _index / 256;
uint256 claimedBitIndex = _index % 256;
uint256 claimedWord = _claimedBitMap[claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
}
function isActive() public view override returns (bool) {
return block.timestamp < endTime;
}
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) public onlyOwner {
IERC20(_tokenAddress).transfer(owner(), _tokenAmount);
}
function _setClaimed(uint256 _index) private {
uint256 claimedWordIndex = _index / 256;
uint256 claimedBitIndex = _index % 256;
_claimedBitMap[claimedWordIndex] = _claimedBitMap[claimedWordIndex] | (1 << claimedBitIndex);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
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) {
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 = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
// Allows anyone to claim a token if they exist in a merkle root.
interface IMerkleDistributor {
// This event is triggered whenever a call to #claim succeeds.
event Claimed(uint256 index, address account, uint256 amount);
// Claim the given amount of the token to the given address. Reverts if the inputs are invalid.
function claim(
uint256 index,
address account,
uint256 amount,
bytes32[] calldata merkleProof
) external;
// Returns the address of the token distributed by this contract.
function token() external view returns (address);
// Returns the merkle root of the merkle tree containing account balances available to claim.
function merkleRoot() external view returns (bytes32);
// Returns true if the index has been marked claimed.
function isClaimed(uint256 index) external view returns (bool);
// Returns the block timestamp when claims will end
function endTime() external view returns (uint256);
// Returns true if the claim period has not ended.
function isActive() external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../libraries/WadRayMath.sol";
import "./interfaces/IVaultsCoreV1.sol";
import "./interfaces/ILiquidationManagerV1.sol";
import "./interfaces/IAddressProviderV1.sol";
contract VaultsCoreV1 is IVaultsCoreV1, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using WadRayMath for uint256;
uint256 public constant MAX_INT = 2**256 - 1;
mapping(address => uint256) public override cumulativeRates;
mapping(address => uint256) public override lastRefresh;
IAddressProviderV1 public override a;
modifier onlyManager() {
require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender));
_;
}
modifier onlyVaultOwner(uint256 _vaultId) {
require(a.vaultsData().vaultOwner(_vaultId) == msg.sender);
_;
}
modifier onlyConfig() {
require(msg.sender == address(a.config()));
_;
}
constructor(IAddressProviderV1 _addresses) public {
require(address(_addresses) != address(0));
a = _addresses;
}
/*
Allow smooth upgrading of the vaultscore.
@dev this function approves token transfers to the new vaultscore of
both stablex and all configured collateral types
@param _newVaultsCore address of the new vaultscore
*/
function upgrade(address _newVaultsCore) public override onlyManager {
require(address(_newVaultsCore) != address(0));
require(a.stablex().approve(_newVaultsCore, MAX_INT));
for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) {
address collateralType = a.config().collateralConfigs(i).collateralType;
IERC20 asset = IERC20(collateralType);
asset.safeApprove(_newVaultsCore, MAX_INT);
}
}
/**
Calculate the available income
@return available income that has not been minted yet.
**/
function availableIncome() public view override returns (uint256) {
return a.vaultsData().debt().sub(a.stablex().totalSupply());
}
/**
Refresh the cumulative rates and debts of all vaults and all collateral types.
**/
function refresh() public override {
for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) {
address collateralType = a.config().collateralConfigs(i).collateralType;
refreshCollateral(collateralType);
}
}
/**
Initialize the cumulative rates to 1 for a new collateral type.
@param _collateralType the address of the new collateral type to be initialized
**/
function initializeRates(address _collateralType) public override onlyConfig {
require(_collateralType != address(0));
lastRefresh[_collateralType] = now;
cumulativeRates[_collateralType] = WadRayMath.ray();
}
/**
Refresh the cumulative rate of a collateraltype.
@dev this updates the debt for all vaults with the specified collateral type.
@param _collateralType the address of the collateral type to be refreshed.
**/
function refreshCollateral(address _collateralType) public override {
require(_collateralType != address(0));
require(a.config().collateralIds(_collateralType) != 0);
uint256 timestamp = now;
uint256 timeElapsed = timestamp.sub(lastRefresh[_collateralType]);
_refreshCumulativeRate(_collateralType, timeElapsed);
lastRefresh[_collateralType] = timestamp;
}
/**
Internal function to increase the cumulative rate over a specified time period
@dev this updates the debt for all vaults with the specified collateral type.
@param _collateralType the address of the collateral type to be updated
@param _timeElapsed the amount of time in seconds to add to the cumulative rate
**/
function _refreshCumulativeRate(address _collateralType, uint256 _timeElapsed) internal {
uint256 borrowRate = a.config().collateralBorrowRate(_collateralType);
uint256 oldCumulativeRate = cumulativeRates[_collateralType];
cumulativeRates[_collateralType] = a.ratesManager().calculateCumulativeRate(
borrowRate,
oldCumulativeRate,
_timeElapsed
);
emit CumulativeRateUpdated(_collateralType, _timeElapsed, cumulativeRates[_collateralType]);
}
/**
Deposit an ERC20 token into the vault of the msg.sender as collateral
@dev A new vault is created if no vault exists for the `msg.sender` with the specified collateral type.
this function used `transferFrom()` and requires pre-approval via `approve()` on the ERC20.
@param _collateralType the address of the collateral type to be deposited
@param _amount the amount of tokens to be deposited in WEI.
**/
function deposit(address _collateralType, uint256 _amount) public override {
require(a.config().collateralIds(_collateralType) != 0);
uint256 vaultId = a.vaultsData().vaultId(_collateralType, msg.sender);
if (vaultId == 0) {
vaultId = a.vaultsData().createVault(_collateralType, msg.sender);
}
IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(vaultId);
a.vaultsData().setCollateralBalance(vaultId, v.collateralBalance.add(_amount));
IERC20 asset = IERC20(v.collateralType);
asset.safeTransferFrom(msg.sender, address(this), _amount);
emit Deposited(vaultId, _amount, msg.sender);
}
/**
Withdraws ERC20 tokens from a vault.
@dev Only te owner of a vault can withdraw collateral from it.
`withdraw()` will fail if it would bring the vault below the liquidation treshold.
@param _vaultId the ID of the vault from which to withdraw the collateral.
@param _amount the amount of ERC20 tokens to be withdrawn in WEI.
**/
function withdraw(uint256 _vaultId, uint256 _amount) public override onlyVaultOwner(_vaultId) nonReentrant {
IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId);
require(_amount <= v.collateralBalance);
uint256 newCollateralBalance = v.collateralBalance.sub(_amount);
a.vaultsData().setCollateralBalance(_vaultId, newCollateralBalance);
if (v.baseDebt > 0) {
//save gas cost when withdrawing from 0 debt vault
refreshCollateral(v.collateralType);
uint256 newCollateralValue = a.priceFeed().convertFrom(v.collateralType, newCollateralBalance);
bool _isHealthy = ILiquidationManagerV1(address(a.liquidationManager())).isHealthy(
v.collateralType,
newCollateralValue,
a.vaultsData().vaultDebt(_vaultId)
);
require(_isHealthy);
}
IERC20 asset = IERC20(v.collateralType);
asset.safeTransfer(msg.sender, _amount);
emit Withdrawn(_vaultId, _amount, msg.sender);
}
/**
Convenience function to withdraw all collateral of a vault
@dev Only te owner of a vault can withdraw collateral from it.
`withdrawAll()` will fail if the vault has any outstanding debt attached to it.
@param _vaultId the ID of the vault from which to withdraw the collateral.
**/
function withdrawAll(uint256 _vaultId) public override onlyVaultOwner(_vaultId) {
uint256 collateralBalance = a.vaultsData().vaultCollateralBalance(_vaultId);
withdraw(_vaultId, collateralBalance);
}
/**
Borrow new StableX (Eg: PAR) tokens from a vault.
@dev Only te owner of a vault can borrow from it.
`borrow()` will update the outstanding vault debt to the current time before attempting the withdrawal.
and will fail if it would bring the vault below the liquidation treshold.
@param _vaultId the ID of the vault from which to borrow.
@param _amount the amount of borrowed StableX tokens in WEI.
**/
function borrow(uint256 _vaultId, uint256 _amount) public override onlyVaultOwner(_vaultId) nonReentrant {
IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId);
//make sure current rate is up to date
refreshCollateral(v.collateralType);
uint256 originationFeePercentage = a.config().collateralOriginationFee(v.collateralType);
uint256 newDebt = _amount;
if (originationFeePercentage > 0) {
newDebt = newDebt.add(_amount.wadMul(originationFeePercentage));
}
// Increment vault borrow balance
uint256 newBaseDebt = a.ratesManager().calculateBaseDebt(newDebt, cumulativeRates[v.collateralType]);
a.vaultsData().setBaseDebt(_vaultId, v.baseDebt.add(newBaseDebt));
uint256 collateralValue = a.priceFeed().convertFrom(v.collateralType, v.collateralBalance);
uint256 newVaultDebt = a.vaultsData().vaultDebt(_vaultId);
require(a.vaultsData().collateralDebt(v.collateralType) <= a.config().collateralDebtLimit(v.collateralType));
bool isHealthy = ILiquidationManagerV1(address(a.liquidationManager())).isHealthy(
v.collateralType,
collateralValue,
newVaultDebt
);
require(isHealthy);
a.stablex().mint(msg.sender, _amount);
emit Borrowed(_vaultId, _amount, msg.sender);
}
/**
Convenience function to repay all debt of a vault
@dev `repayAll()` will update the outstanding vault debt to the current time.
@param _vaultId the ID of the vault for which to repay the debt.
**/
function repayAll(uint256 _vaultId) public override {
repay(_vaultId, 2**256 - 1);
}
/**
Repay an outstanding StableX balance to a vault.
@dev `repay()` will update the outstanding vault debt to the current time.
@param _vaultId the ID of the vault for which to repay the outstanding debt balance.
@param _amount the amount of StableX tokens in WEI to be repaid.
**/
function repay(uint256 _vaultId, uint256 _amount) public override nonReentrant {
address collateralType = a.vaultsData().vaultCollateralType(_vaultId);
// Make sure current rate is up to date
refreshCollateral(collateralType);
uint256 currentVaultDebt = a.vaultsData().vaultDebt(_vaultId);
// Decrement vault borrow balance
if (_amount >= currentVaultDebt) {
//full repayment
_amount = currentVaultDebt; //only pay back what's outstanding
}
_reduceVaultDebt(_vaultId, _amount);
a.stablex().burn(msg.sender, _amount);
emit Repaid(_vaultId, _amount, msg.sender);
}
/**
Internal helper function to reduce the debt of a vault.
@dev assumes cumulative rates for the vault's collateral type are up to date.
please call `refreshCollateral()` before calling this function.
@param _vaultId the ID of the vault for which to reduce the debt.
@param _amount the amount of debt to be reduced.
**/
function _reduceVaultDebt(uint256 _vaultId, uint256 _amount) internal {
address collateralType = a.vaultsData().vaultCollateralType(_vaultId);
uint256 currentVaultDebt = a.vaultsData().vaultDebt(_vaultId);
uint256 remainder = currentVaultDebt.sub(_amount);
uint256 cumulativeRate = cumulativeRates[collateralType];
if (remainder == 0) {
a.vaultsData().setBaseDebt(_vaultId, 0);
} else {
uint256 newBaseDebt = a.ratesManager().calculateBaseDebt(remainder, cumulativeRate);
a.vaultsData().setBaseDebt(_vaultId, newBaseDebt);
}
}
/**
Liquidate a vault that is below the liquidation treshold by repaying it's outstanding debt.
@dev `liquidate()` will update the outstanding vault debt to the current time and pay a `liquidationBonus`
to the liquidator. `liquidate()` can be called by anyone.
@param _vaultId the ID of the vault to be liquidated.
**/
function liquidate(uint256 _vaultId) public override nonReentrant {
IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId);
refreshCollateral(v.collateralType);
uint256 collateralValue = a.priceFeed().convertFrom(v.collateralType, v.collateralBalance);
uint256 currentVaultDebt = a.vaultsData().vaultDebt(_vaultId);
require(
!ILiquidationManagerV1(address(a.liquidationManager())).isHealthy(
v.collateralType,
collateralValue,
currentVaultDebt
)
);
uint256 discountedValue = ILiquidationManagerV1(address(a.liquidationManager())).applyLiquidationDiscount(
collateralValue
);
uint256 collateralToReceive;
uint256 stableXToPay = currentVaultDebt;
if (discountedValue < currentVaultDebt) {
//Insurance Case
uint256 insuranceAmount = currentVaultDebt.sub(discountedValue);
require(a.stablex().balanceOf(address(this)) >= insuranceAmount);
a.stablex().burn(address(this), insuranceAmount);
emit InsurancePaid(_vaultId, insuranceAmount, msg.sender);
collateralToReceive = v.collateralBalance;
stableXToPay = currentVaultDebt.sub(insuranceAmount);
} else {
collateralToReceive = a.priceFeed().convertTo(v.collateralType, currentVaultDebt);
collateralToReceive = collateralToReceive.add(
ILiquidationManagerV1(address(a.liquidationManager())).liquidationBonus(collateralToReceive)
);
}
// reduce the vault debt to 0
_reduceVaultDebt(_vaultId, currentVaultDebt);
a.stablex().burn(msg.sender, stableXToPay);
// send the collateral to the liquidator
a.vaultsData().setCollateralBalance(_vaultId, v.collateralBalance.sub(collateralToReceive));
IERC20 asset = IERC20(v.collateralType);
asset.safeTransfer(msg.sender, collateralToReceive);
emit Liquidated(_vaultId, stableXToPay, collateralToReceive, v.owner, msg.sender);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
/******************
@title WadRayMath library
@author Aave
@dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)
*/
library WadRayMath {
using SafeMath for uint256;
uint256 internal constant _WAD = 1e18;
uint256 internal constant _HALF_WAD = _WAD / 2;
uint256 internal constant _RAY = 1e27;
uint256 internal constant _HALF_RAY = _RAY / 2;
uint256 internal constant _WAD_RAY_RATIO = 1e9;
function ray() internal pure returns (uint256) {
return _RAY;
}
function wad() internal pure returns (uint256) {
return _WAD;
}
function halfRay() internal pure returns (uint256) {
return _HALF_RAY;
}
function halfWad() internal pure returns (uint256) {
return _HALF_WAD;
}
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
return _HALF_WAD.add(a.mul(b)).div(_WAD);
}
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 halfB = b / 2;
return halfB.add(a.mul(_WAD)).div(b);
}
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
return _HALF_RAY.add(a.mul(b)).div(_RAY);
}
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 halfB = b / 2;
return halfB.add(a.mul(_RAY)).div(b);
}
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = _WAD_RAY_RATIO / 2;
return halfRatio.add(a).div(_WAD_RAY_RATIO);
}
function wadToRay(uint256 a) internal pure returns (uint256) {
return a.mul(_WAD_RAY_RATIO);
}
/**
* @dev calculates x^n, in ray. The code uses the ModExp precompile
* @param x base
* @param n exponent
* @return z = x^n, in ray
*/
function rayPow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : _RAY;
for (n /= 2; n != 0; n /= 2) {
x = rayMul(x, x);
if (n % 2 != 0) {
z = rayMul(z, x);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import './IAddressProviderV1.sol';
interface IVaultsCoreV1 {
event Opened(uint256 indexed vaultId, address indexed collateralType, address indexed owner);
event Deposited(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Withdrawn(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Borrowed(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Repaid(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Liquidated(
uint256 indexed vaultId,
uint256 debtRepaid,
uint256 collateralLiquidated,
address indexed owner,
address indexed sender
);
event CumulativeRateUpdated(address indexed collateralType, uint256 elapsedTime, uint256 newCumulativeRate); //cumulative interest rate from deployment time T0
event InsurancePaid(uint256 indexed vaultId, uint256 insuranceAmount, address indexed sender);
function deposit(address _collateralType, uint256 _amount) external;
function withdraw(uint256 _vaultId, uint256 _amount) external;
function withdrawAll(uint256 _vaultId) external;
function borrow(uint256 _vaultId, uint256 _amount) external;
function repayAll(uint256 _vaultId) external;
function repay(uint256 _vaultId, uint256 _amount) external;
function liquidate(uint256 _vaultId) external;
//Refresh
function initializeRates(address _collateralType) external;
function refresh() external;
function refreshCollateral(address collateralType) external;
//upgrade
function upgrade(address _newVaultsCore) external;
//Read only
function a() external view returns (IAddressProviderV1);
function availableIncome() external view returns (uint256);
function cumulativeRates(address _collateralType) external view returns (uint256);
function lastRefresh(address _collateralType) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import './IAddressProviderV1.sol';
interface ILiquidationManagerV1 {
function a() external view returns (IAddressProviderV1);
function calculateHealthFactor(
address _collateralType,
uint256 _collateralValue,
uint256 _vaultDebt
) external view returns (uint256 healthFactor);
function liquidationBonus(uint256 _amount) external view returns (uint256 bonus);
function applyLiquidationDiscount(uint256 _amount) external view returns (uint256 discountedAmount);
function isHealthy(
address _collateralType,
uint256 _collateralValue,
uint256 _vaultDebt
) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import './IConfigProviderV1.sol';
import './ILiquidationManagerV1.sol';
import './IVaultsCoreV1.sol';
import '../../interfaces/IVaultsCore.sol';
import '../../interfaces/IAccessController.sol';
import '../../interfaces/ISTABLEX.sol';
import '../../interfaces/IPriceFeed.sol';
import '../../interfaces/IRatesManager.sol';
import '../../interfaces/IVaultsDataProvider.sol';
import '../../interfaces/IFeeDistributor.sol';
interface IAddressProviderV1 {
function setAccessController(IAccessController _controller) external;
function setConfigProvider(IConfigProviderV1 _config) external;
function setVaultsCore(IVaultsCoreV1 _core) external;
function setStableX(ISTABLEX _stablex) external;
function setRatesManager(IRatesManager _ratesManager) external;
function setPriceFeed(IPriceFeed _priceFeed) external;
function setLiquidationManager(ILiquidationManagerV1 _liquidationManager) external;
function setVaultsDataProvider(IVaultsDataProvider _vaultsData) external;
function setFeeDistributor(IFeeDistributor _feeDistributor) external;
function controller() external view returns (IAccessController);
function config() external view returns (IConfigProviderV1);
function core() external view returns (IVaultsCoreV1);
function stablex() external view returns (ISTABLEX);
function ratesManager() external view returns (IRatesManager);
function priceFeed() external view returns (IPriceFeed);
function liquidationManager() external view returns (ILiquidationManagerV1);
function vaultsData() external view returns (IVaultsDataProvider);
function feeDistributor() external view returns (IFeeDistributor);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import './IAddressProviderV1.sol';
interface IConfigProviderV1 {
struct CollateralConfig {
address collateralType;
uint256 debtLimit;
uint256 minCollateralRatio;
uint256 borrowRate;
uint256 originationFee;
}
event CollateralUpdated(
address indexed collateralType,
uint256 debtLimit,
uint256 minCollateralRatio,
uint256 borrowRate,
uint256 originationFee
);
event CollateralRemoved(address indexed collateralType);
function setCollateralConfig(
address _collateralType,
uint256 _debtLimit,
uint256 _minCollateralRatio,
uint256 _borrowRate,
uint256 _originationFee
) external;
function removeCollateral(address _collateralType) external;
function setCollateralDebtLimit(address _collateralType, uint256 _debtLimit) external;
function setCollateralMinCollateralRatio(address _collateralType, uint256 _minCollateralRatio) external;
function setCollateralBorrowRate(address _collateralType, uint256 _borrowRate) external;
function setCollateralOriginationFee(address _collateralType, uint256 _originationFee) external;
function setLiquidationBonus(uint256 _bonus) external;
function a() external view returns (IAddressProviderV1);
function collateralConfigs(uint256 _id) external view returns (CollateralConfig memory);
function collateralIds(address _collateralType) external view returns (uint256);
function numCollateralConfigs() external view returns (uint256);
function liquidationBonus() external view returns (uint256);
function collateralDebtLimit(address _collateralType) external view returns (uint256);
function collateralMinCollateralRatio(address _collateralType) external view returns (uint256);
function collateralBorrowRate(address _collateralType) external view returns (uint256);
function collateralOriginationFee(address _collateralType) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "../interfaces/IAddressProvider.sol";
import "../interfaces/IVaultsCoreState.sol";
import "../interfaces/IWETH.sol";
import "../liquidityMining/interfaces/IDebtNotifier.sol";
interface IVaultsCore {
event Opened(uint256 indexed vaultId, address indexed collateralType, address indexed owner);
event Deposited(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Withdrawn(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Borrowed(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Repaid(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Liquidated(
uint256 indexed vaultId,
uint256 debtRepaid,
uint256 collateralLiquidated,
address indexed owner,
address indexed sender
);
event InsurancePaid(uint256 indexed vaultId, uint256 insuranceAmount, address indexed sender);
function deposit(address _collateralType, uint256 _amount) external;
function depositETH() external payable;
function depositByVaultId(uint256 _vaultId, uint256 _amount) external;
function depositETHByVaultId(uint256 _vaultId) external payable;
function depositAndBorrow(
address _collateralType,
uint256 _depositAmount,
uint256 _borrowAmount
) external;
function depositETHAndBorrow(uint256 _borrowAmount) external payable;
function withdraw(uint256 _vaultId, uint256 _amount) external;
function withdrawETH(uint256 _vaultId, uint256 _amount) external;
function borrow(uint256 _vaultId, uint256 _amount) external;
function repayAll(uint256 _vaultId) external;
function repay(uint256 _vaultId, uint256 _amount) external;
function liquidate(uint256 _vaultId) external;
function liquidatePartial(uint256 _vaultId, uint256 _amount) external;
function upgrade(address payable _newVaultsCore) external;
function acceptUpgrade(address payable _oldVaultsCore) external;
function setDebtNotifier(IDebtNotifier _debtNotifier) external;
//Read only
function a() external view returns (IAddressProvider);
function WETH() external view returns (IWETH);
function debtNotifier() external view returns (IDebtNotifier);
function state() external view returns (IVaultsCoreState);
function cumulativeRates(address _collateralType) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IAccessController {
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
function MANAGER_ROLE() external view returns (bytes32);
function MINTER_ROLE() external view returns (bytes32);
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleMemberCount(bytes32 role) external view returns (uint256);
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/IAddressProvider.sol";
interface ISTABLEX is IERC20 {
function mint(address account, uint256 amount) external;
function burn(address account, uint256 amount) external;
function a() external view returns (IAddressProvider);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../chainlink/AggregatorV3Interface.sol";
import "../interfaces/IAddressProvider.sol";
interface IPriceFeed {
event OracleUpdated(address indexed asset, address oracle, address sender);
event EurOracleUpdated(address oracle, address sender);
function setAssetOracle(address _asset, address _oracle) external;
function setEurOracle(address _oracle) external;
function a() external view returns (IAddressProvider);
function assetOracles(address _asset) external view returns (AggregatorV3Interface);
function eurOracle() external view returns (AggregatorV3Interface);
function getAssetPrice(address _asset) external view returns (uint256);
function convertFrom(address _asset, uint256 _amount) external view returns (uint256);
function convertTo(address _asset, uint256 _amount) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "../interfaces/IAddressProvider.sol";
interface IRatesManager {
function a() external view returns (IAddressProvider);
//current annualized borrow rate
function annualizedBorrowRate(uint256 _currentBorrowRate) external pure returns (uint256);
//uses current cumulative rate to calculate totalDebt based on baseDebt at time T0
function calculateDebt(uint256 _baseDebt, uint256 _cumulativeRate) external pure returns (uint256);
//uses current cumulative rate to calculate baseDebt at time T0
function calculateBaseDebt(uint256 _debt, uint256 _cumulativeRate) external pure returns (uint256);
//calculate a new cumulative rate
function calculateCumulativeRate(
uint256 _borrowRate,
uint256 _cumulativeRate,
uint256 _timeElapsed
) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "../interfaces/IAddressProvider.sol";
interface IVaultsDataProvider {
struct Vault {
// borrowedType support USDX / PAR
address collateralType;
address owner;
uint256 collateralBalance;
uint256 baseDebt;
uint256 createdAt;
}
//Write
function createVault(address _collateralType, address _owner) external returns (uint256);
function setCollateralBalance(uint256 _id, uint256 _balance) external;
function setBaseDebt(uint256 _id, uint256 _newBaseDebt) external;
// Read
function a() external view returns (IAddressProvider);
function baseDebt(address _collateralType) external view returns (uint256);
function vaultCount() external view returns (uint256);
function vaults(uint256 _id) external view returns (Vault memory);
function vaultOwner(uint256 _id) external view returns (address);
function vaultCollateralType(uint256 _id) external view returns (address);
function vaultCollateralBalance(uint256 _id) external view returns (uint256);
function vaultBaseDebt(uint256 _id) external view returns (uint256);
function vaultId(address _collateralType, address _owner) external view returns (uint256);
function vaultExists(uint256 _id) external view returns (bool);
function vaultDebt(uint256 _vaultId) external view returns (uint256);
function debt() external view returns (uint256);
function collateralDebt(address _collateralType) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../interfaces/IAddressProvider.sol";
interface IFeeDistributor {
event PayeeAdded(address indexed account, uint256 shares);
event FeeReleased(uint256 income, uint256 releasedAt);
function release() external;
function changePayees(address[] memory _payees, uint256[] memory _shares) external;
function a() external view returns (IAddressProvider);
function lastReleasedAt() external view returns (uint256);
function getPayees() external view returns (address[] memory);
function totalShares() external view returns (uint256);
function shares(address payee) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "./IAccessController.sol";
import "./IConfigProvider.sol";
import "./ISTABLEX.sol";
import "./IPriceFeed.sol";
import "./IRatesManager.sol";
import "./ILiquidationManager.sol";
import "./IVaultsCore.sol";
import "./IVaultsDataProvider.sol";
import "./IFeeDistributor.sol";
interface IAddressProvider {
function setAccessController(IAccessController _controller) external;
function setConfigProvider(IConfigProvider _config) external;
function setVaultsCore(IVaultsCore _core) external;
function setStableX(ISTABLEX _stablex) external;
function setRatesManager(IRatesManager _ratesManager) external;
function setPriceFeed(IPriceFeed _priceFeed) external;
function setLiquidationManager(ILiquidationManager _liquidationManager) external;
function setVaultsDataProvider(IVaultsDataProvider _vaultsData) external;
function setFeeDistributor(IFeeDistributor _feeDistributor) external;
function controller() external view returns (IAccessController);
function config() external view returns (IConfigProvider);
function core() external view returns (IVaultsCore);
function stablex() external view returns (ISTABLEX);
function ratesManager() external view returns (IRatesManager);
function priceFeed() external view returns (IPriceFeed);
function liquidationManager() external view returns (ILiquidationManager);
function vaultsData() external view returns (IVaultsDataProvider);
function feeDistributor() external view returns (IFeeDistributor);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "./IAddressProvider.sol";
import "../v1/interfaces/IVaultsCoreV1.sol";
interface IVaultsCoreState {
event CumulativeRateUpdated(address indexed collateralType, uint256 elapsedTime, uint256 newCumulativeRate); //cumulative interest rate from deployment time T0
function initializeRates(address _collateralType) external;
function refresh() external;
function refreshCollateral(address collateralType) external;
function syncState(IVaultsCoreState _stateAddress) external;
function syncStateFromV1(IVaultsCoreV1 _core) external;
//Read only
function a() external view returns (IAddressProvider);
function availableIncome() external view returns (uint256);
function cumulativeRates(address _collateralType) external view returns (uint256);
function lastRefresh(address _collateralType) external view returns (uint256);
function synced() external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256 wad) external;
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import '../../governance/interfaces/IGovernanceAddressProvider.sol';
import './ISupplyMiner.sol';
interface IDebtNotifier {
function debtChanged(uint256 _vaultId) external;
function setCollateralSupplyMiner(address collateral, ISupplyMiner supplyMiner) external;
function a() external view returns (IGovernanceAddressProvider);
function collateralSupplyMinerMapping(address collateral) external view returns (ISupplyMiner);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "../interfaces/IAddressProvider.sol";
interface IConfigProvider {
struct CollateralConfig {
address collateralType;
uint256 debtLimit;
uint256 liquidationRatio;
uint256 minCollateralRatio;
uint256 borrowRate;
uint256 originationFee;
uint256 liquidationBonus;
uint256 liquidationFee;
}
event CollateralUpdated(
address indexed collateralType,
uint256 debtLimit,
uint256 liquidationRatio,
uint256 minCollateralRatio,
uint256 borrowRate,
uint256 originationFee,
uint256 liquidationBonus,
uint256 liquidationFee
);
event CollateralRemoved(address indexed collateralType);
function setCollateralConfig(
address _collateralType,
uint256 _debtLimit,
uint256 _liquidationRatio,
uint256 _minCollateralRatio,
uint256 _borrowRate,
uint256 _originationFee,
uint256 _liquidationBonus,
uint256 _liquidationFee
) external;
function removeCollateral(address _collateralType) external;
function setCollateralDebtLimit(address _collateralType, uint256 _debtLimit) external;
function setCollateralLiquidationRatio(address _collateralType, uint256 _liquidationRatio) external;
function setCollateralMinCollateralRatio(address _collateralType, uint256 _minCollateralRatio) external;
function setCollateralBorrowRate(address _collateralType, uint256 _borrowRate) external;
function setCollateralOriginationFee(address _collateralType, uint256 _originationFee) external;
function setCollateralLiquidationBonus(address _collateralType, uint256 _liquidationBonus) external;
function setCollateralLiquidationFee(address _collateralType, uint256 _liquidationFee) external;
function setMinVotingPeriod(uint256 _minVotingPeriod) external;
function setMaxVotingPeriod(uint256 _maxVotingPeriod) external;
function setVotingQuorum(uint256 _votingQuorum) external;
function setProposalThreshold(uint256 _proposalThreshold) external;
function a() external view returns (IAddressProvider);
function collateralConfigs(uint256 _id) external view returns (CollateralConfig memory);
function collateralIds(address _collateralType) external view returns (uint256);
function numCollateralConfigs() external view returns (uint256);
function minVotingPeriod() external view returns (uint256);
function maxVotingPeriod() external view returns (uint256);
function votingQuorum() external view returns (uint256);
function proposalThreshold() external view returns (uint256);
function collateralDebtLimit(address _collateralType) external view returns (uint256);
function collateralLiquidationRatio(address _collateralType) external view returns (uint256);
function collateralMinCollateralRatio(address _collateralType) external view returns (uint256);
function collateralBorrowRate(address _collateralType) external view returns (uint256);
function collateralOriginationFee(address _collateralType) external view returns (uint256);
function collateralLiquidationBonus(address _collateralType) external view returns (uint256);
function collateralLiquidationFee(address _collateralType) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "../interfaces/IAddressProvider.sol";
interface ILiquidationManager {
function a() external view returns (IAddressProvider);
function calculateHealthFactor(
uint256 _collateralValue,
uint256 _vaultDebt,
uint256 _minRatio
) external view returns (uint256 healthFactor);
function liquidationBonus(address _collateralType, uint256 _amount) external view returns (uint256 bonus);
function applyLiquidationDiscount(address _collateralType, uint256 _amount)
external
view
returns (uint256 discountedAmount);
function isHealthy(
uint256 _collateralValue,
uint256 _vaultDebt,
uint256 _minRatio
) external view returns (bool);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.12;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import './IGovernorAlpha.sol';
import './ITimelock.sol';
import './IVotingEscrow.sol';
import '../../interfaces/IAccessController.sol';
import '../../interfaces/IAddressProvider.sol';
import '../../liquidityMining/interfaces/IMIMO.sol';
import '../../liquidityMining/interfaces/IDebtNotifier.sol';
interface IGovernanceAddressProvider {
function setParallelAddressProvider(IAddressProvider _parallel) external;
function setMIMO(IMIMO _mimo) external;
function setDebtNotifier(IDebtNotifier _debtNotifier) external;
function setGovernorAlpha(IGovernorAlpha _governorAlpha) external;
function setTimelock(ITimelock _timelock) external;
function setVotingEscrow(IVotingEscrow _votingEscrow) external;
function controller() external view returns (IAccessController);
function parallel() external view returns (IAddressProvider);
function mimo() external view returns (IMIMO);
function debtNotifier() external view returns (IDebtNotifier);
function governorAlpha() external view returns (IGovernorAlpha);
function timelock() external view returns (ITimelock);
function votingEscrow() external view returns (IVotingEscrow);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
interface ISupplyMiner {
function baseDebtChanged(address user, uint256 newBaseDebt) external;
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
interface IGovernorAlpha {
/// @notice Possible states that a proposal may be in
enum ProposalState { Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed }
struct Proposal {
// Unique id for looking up a proposal
uint256 id;
// Creator of the proposal
address proposer;
// The timestamp that the proposal will be available for execution, set once the vote succeeds
uint256 eta;
// the ordered list of target addresses for calls to be made
address[] targets;
// The ordered list of values (i.e. msg.value) to be passed to the calls to be made
uint256[] values;
// The ordered list of function signatures to be called
string[] signatures;
// The ordered list of calldata to be passed to each call
bytes[] calldatas;
// The timestamp at which voting begins: holders must delegate their votes prior to this timestamp
uint256 startTime;
// The timestamp at which voting ends: votes must be cast prior to this timestamp
uint256 endTime;
// Current number of votes in favor of this proposal
uint256 forVotes;
// Current number of votes in opposition to this proposal
uint256 againstVotes;
// Flag marking whether the proposal has been canceled
bool canceled;
// Flag marking whether the proposal has been executed
bool executed;
// Receipts of ballots for the entire set of voters
mapping(address => Receipt) receipts;
}
/// @notice Ballot receipt record for a voter
struct Receipt {
// Whether or not a vote has been cast
bool hasVoted;
// Whether or not the voter supports the proposal
bool support;
// The number of votes the voter had, which were cast
uint256 votes;
}
/// @notice An event emitted when a new proposal is created
event ProposalCreated(
uint256 id,
address proposer,
address[] targets,
uint256[] values,
string[] signatures,
bytes[] calldatas,
uint256 startTime,
uint256 endTime,
string description
);
/// @notice An event emitted when a vote has been cast on a proposal
event VoteCast(address voter, uint256 proposalId, bool support, uint256 votes);
/// @notice An event emitted when a proposal has been canceled
event ProposalCanceled(uint256 id);
/// @notice An event emitted when a proposal has been queued in the Timelock
event ProposalQueued(uint256 id, uint256 eta);
/// @notice An event emitted when a proposal has been executed in the Timelock
event ProposalExecuted(uint256 id);
function propose(
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
string memory description,
uint256 endTime
) external returns (uint256);
function queue(uint256 proposalId) external;
function execute(uint256 proposalId) external payable;
function cancel(uint256 proposalId) external;
function castVote(uint256 proposalId, bool support) external;
function getActions(uint256 proposalId)
external
view
returns (
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas
);
function getReceipt(uint256 proposalId, address voter) external view returns (Receipt memory);
function state(uint256 proposalId) external view returns (ProposalState);
function quorumVotes() external view returns (uint256);
function proposalThreshold() external view returns (uint256);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.6.12;
interface ITimelock {
event NewAdmin(address indexed newAdmin);
event NewPendingAdmin(address indexed newPendingAdmin);
event NewDelay(uint256 indexed newDelay);
event CancelTransaction(
bytes32 indexed txHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 eta
);
event ExecuteTransaction(
bytes32 indexed txHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 eta
);
event QueueTransaction(
bytes32 indexed txHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 eta
);
function acceptAdmin() external;
function queueTransaction(
address target,
uint256 value,
string calldata signature,
bytes calldata data,
uint256 eta
) external returns (bytes32);
function cancelTransaction(
address target,
uint256 value,
string calldata signature,
bytes calldata data,
uint256 eta
) external;
function executeTransaction(
address target,
uint256 value,
string calldata signature,
bytes calldata data,
uint256 eta
) external payable returns (bytes memory);
function delay() external view returns (uint256);
function GRACE_PERIOD() external view returns (uint256);
function queuedTransactions(bytes32 hash) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '../../liquidityMining/interfaces/IGenericMiner.sol';
interface IVotingEscrow {
enum LockAction { CREATE_LOCK, INCREASE_LOCK_AMOUNT, INCREASE_LOCK_TIME }
struct LockedBalance {
uint256 amount;
uint256 end;
}
/** Shared Events */
event Deposit(address indexed provider, uint256 value, uint256 locktime, LockAction indexed action, uint256 ts);
event Withdraw(address indexed provider, uint256 value, uint256 ts);
event Expired();
function createLock(uint256 _value, uint256 _unlockTime) external;
function increaseLockAmount(uint256 _value) external;
function increaseLockLength(uint256 _unlockTime) external;
function withdraw() external;
function expireContract() external;
function setMiner(IGenericMiner _miner) external;
function setMinimumLockTime(uint256 _minimumLockTime) external;
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
function balanceOfAt(address _owner, uint256 _blockTime) external view returns (uint256);
function stakingToken() external view returns (IERC20);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IMIMO is IERC20 {
function burn(address account, uint256 amount) external;
function mint(address account, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import '@openzeppelin/contracts/math/SafeMath.sol';
import '../../interfaces/IAddressProvider.sol';
import '../../governance/interfaces/IGovernanceAddressProvider.sol';
interface IGenericMiner {
struct UserInfo {
uint256 stake;
uint256 accAmountPerShare; // User's accAmountPerShare
}
/// @dev This emit when a users' productivity has changed
/// It emits with the user's address and the the value after the change.
event StakeIncreased(address indexed user, uint256 stake);
/// @dev This emit when a users' productivity has changed
/// It emits with the user's address and the the value after the change.
event StakeDecreased(address indexed user, uint256 stake);
function releaseMIMO(address _user) external;
function a() external view returns (IGovernanceAddressProvider);
function stake(address _user) external view returns (uint256);
function pendingMIMO(address _user) external view returns (uint256);
function totalStake() external view returns (uint256);
function userInfo(address _user) external view returns (UserInfo memory);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IVaultsDataProviderV1.sol";
import "./interfaces/IAddressProviderV1.sol";
contract VaultsDataProviderV1 is IVaultsDataProviderV1 {
using SafeMath for uint256;
IAddressProviderV1 public override a;
uint256 public override vaultCount = 0;
mapping(address => uint256) public override baseDebt;
mapping(uint256 => Vault) private _vaults;
mapping(address => mapping(address => uint256)) private _vaultOwners;
modifier onlyVaultsCore() {
require(msg.sender == address(a.core()), "Caller is not VaultsCore");
_;
}
constructor(IAddressProviderV1 _addresses) public {
require(address(_addresses) != address(0));
a = _addresses;
}
/**
Opens a new vault.
@dev only the vaultsCore module can call this function
@param _collateralType address to the collateral asset e.g. WETH
@param _owner the owner of the new vault.
*/
function createVault(address _collateralType, address _owner) public override onlyVaultsCore returns (uint256) {
require(_collateralType != address(0));
require(_owner != address(0));
uint256 newId = ++vaultCount;
require(_collateralType != address(0), "collateralType unknown");
Vault memory v = Vault({
collateralType: _collateralType,
owner: _owner,
collateralBalance: 0,
baseDebt: 0,
createdAt: block.timestamp
});
_vaults[newId] = v;
_vaultOwners[_owner][_collateralType] = newId;
return newId;
}
/**
Set the collateral balance of a vault.
@dev only the vaultsCore module can call this function
@param _id Vault ID of which the collateral balance will be updated
@param _balance the new balance of the vault.
*/
function setCollateralBalance(uint256 _id, uint256 _balance) public override onlyVaultsCore {
require(vaultExists(_id), "Vault not found.");
Vault storage v = _vaults[_id];
v.collateralBalance = _balance;
}
/**
Set the base debt of a vault.
@dev only the vaultsCore module can call this function
@param _id Vault ID of which the base debt will be updated
@param _newBaseDebt the new base debt of the vault.
*/
function setBaseDebt(uint256 _id, uint256 _newBaseDebt) public override onlyVaultsCore {
Vault storage _vault = _vaults[_id];
if (_newBaseDebt > _vault.baseDebt) {
uint256 increase = _newBaseDebt.sub(_vault.baseDebt);
baseDebt[_vault.collateralType] = baseDebt[_vault.collateralType].add(increase);
} else {
uint256 decrease = _vault.baseDebt.sub(_newBaseDebt);
baseDebt[_vault.collateralType] = baseDebt[_vault.collateralType].sub(decrease);
}
_vault.baseDebt = _newBaseDebt;
}
/**
Get a vault by vault ID.
@param _id The vault's ID to be retrieved
*/
function vaults(uint256 _id) public view override returns (Vault memory) {
Vault memory v = _vaults[_id];
return v;
}
/**
Get the owner of a vault.
@param _id the ID of the vault
@return owner of the vault
*/
function vaultOwner(uint256 _id) public view override returns (address) {
return _vaults[_id].owner;
}
/**
Get the collateral type of a vault.
@param _id the ID of the vault
@return address for the collateral type of the vault
*/
function vaultCollateralType(uint256 _id) public view override returns (address) {
return _vaults[_id].collateralType;
}
/**
Get the collateral balance of a vault.
@param _id the ID of the vault
@return collateral balance of the vault
*/
function vaultCollateralBalance(uint256 _id) public view override returns (uint256) {
return _vaults[_id].collateralBalance;
}
/**
Get the base debt of a vault.
@param _id the ID of the vault
@return base debt of the vault
*/
function vaultBaseDebt(uint256 _id) public view override returns (uint256) {
return _vaults[_id].baseDebt;
}
/**
Retrieve the vault id for a specified owner and collateral type.
@dev returns 0 for non-existing vaults
@param _collateralType address of the collateral type (Eg: WETH)
@param _owner address of the owner of the vault
@return vault id of the vault or 0
*/
function vaultId(address _collateralType, address _owner) public view override returns (uint256) {
return _vaultOwners[_owner][_collateralType];
}
/**
Checks if a specified vault exists.
@param _id the ID of the vault
@return boolean if the vault exists
*/
function vaultExists(uint256 _id) public view override returns (bool) {
Vault memory v = _vaults[_id];
return v.collateralType != address(0);
}
/**
Calculated the total outstanding debt for all vaults and all collateral types.
@dev uses the existing cumulative rate. Call `refresh()` on `VaultsCore`
to make sure it's up to date.
@return total debt of the platform
*/
function debt() public view override returns (uint256) {
uint256 total = 0;
for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) {
address collateralType = a.config().collateralConfigs(i).collateralType;
total = total.add(collateralDebt(collateralType));
}
return total;
}
/**
Calculated the total outstanding debt for all vaults of a specific collateral type.
@dev uses the existing cumulative rate. Call `refreshCollateral()` on `VaultsCore`
to make sure it's up to date.
@param _collateralType address of the collateral type (Eg: WETH)
@return total debt of the platform of one collateral type
*/
function collateralDebt(address _collateralType) public view override returns (uint256) {
return a.ratesManager().calculateDebt(baseDebt[_collateralType], a.core().cumulativeRates(_collateralType));
}
/**
Calculated the total outstanding debt for a specific vault.
@dev uses the existing cumulative rate. Call `refreshCollateral()` on `VaultsCore`
to make sure it's up to date.
@param _vaultId the ID of the vault
@return total debt of one vault
*/
function vaultDebt(uint256 _vaultId) public view override returns (uint256) {
IVaultsDataProviderV1.Vault memory v = vaults(_vaultId);
return a.ratesManager().calculateDebt(v.baseDebt, a.core().cumulativeRates(v.collateralType));
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import './IAddressProviderV1.sol';
interface IVaultsDataProviderV1 {
struct Vault {
// borrowedType support USDX / PAR
address collateralType;
address owner;
uint256 collateralBalance;
uint256 baseDebt;
uint256 createdAt;
}
//Write
function createVault(address _collateralType, address _owner) external returns (uint256);
function setCollateralBalance(uint256 _id, uint256 _balance) external;
function setBaseDebt(uint256 _id, uint256 _newBaseDebt) external;
function a() external view returns (IAddressProviderV1);
// Read
function baseDebt(address _collateralType) external view returns (uint256);
function vaultCount() external view returns (uint256);
function vaults(uint256 _id) external view returns (Vault memory);
function vaultOwner(uint256 _id) external view returns (address);
function vaultCollateralType(uint256 _id) external view returns (address);
function vaultCollateralBalance(uint256 _id) external view returns (uint256);
function vaultBaseDebt(uint256 _id) external view returns (uint256);
function vaultId(address _collateralType, address _owner) external view returns (uint256);
function vaultExists(uint256 _id) external view returns (bool);
function vaultDebt(uint256 _vaultId) external view returns (uint256);
function debt() external view returns (uint256);
function collateralDebt(address _collateralType) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../libraries/WadRayMath.sol";
import "./interfaces/IAddressProviderV1.sol";
import "./interfaces/IConfigProviderV1.sol";
import "./interfaces/ILiquidationManagerV1.sol";
contract LiquidationManagerV1 is ILiquidationManagerV1, ReentrancyGuard {
using SafeMath for uint256;
using WadRayMath for uint256;
IAddressProviderV1 public override a;
uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; // 1
uint256 public constant FULL_LIQUIDIATION_TRESHOLD = 100e18; // 100 USDX, vaults below 100 USDX can be liquidated in full
constructor(IAddressProviderV1 _addresses) public {
require(address(_addresses) != address(0));
a = _addresses;
}
/**
Check if the health factor is above or equal to 1.
@param _collateralType address of the collateral type
@param _collateralValue value of the collateral in stableX currency
@param _vaultDebt outstanding debt to which the collateral balance shall be compared
@return boolean if the health factor is >= 1.
*/
function isHealthy(
address _collateralType,
uint256 _collateralValue,
uint256 _vaultDebt
) public view override returns (bool) {
uint256 healthFactor = calculateHealthFactor(_collateralType, _collateralValue, _vaultDebt);
return healthFactor >= HEALTH_FACTOR_LIQUIDATION_THRESHOLD;
}
/**
Calculate the healthfactor of a debt balance
@param _collateralType address of the collateral type
@param _collateralValue value of the collateral in stableX currency
@param _vaultDebt outstanding debt to which the collateral balance shall be compared
@return healthFactor
*/
function calculateHealthFactor(
address _collateralType,
uint256 _collateralValue,
uint256 _vaultDebt
) public view override returns (uint256 healthFactor) {
if (_vaultDebt == 0) return WadRayMath.wad();
// CurrentCollateralizationRatio = deposited ETH in USD / debt in USD
uint256 collateralizationRatio = _collateralValue.wadDiv(_vaultDebt);
// Healthfactor = CurrentCollateralizationRatio / MinimumCollateralizationRatio
uint256 collateralId = a.config().collateralIds(_collateralType);
require(collateralId > 0, "collateral not supported");
uint256 minRatio = a.config().collateralConfigs(collateralId).minCollateralRatio;
if (minRatio > 0) {
return collateralizationRatio.wadDiv(minRatio);
}
return 1e18; // 1
}
/**
Calculate the liquidation bonus for a specified amount
@param _amount amount for which the liquidation bonus shall be calculated
@return bonus the liquidation bonus to pay out
*/
function liquidationBonus(uint256 _amount) public view override returns (uint256 bonus) {
return _amount.wadMul(IConfigProviderV1(address(a.config())).liquidationBonus());
}
/**
Apply the liquidation bonus to a balance as a discount.
@param _amount the balance on which to apply to liquidation bonus as a discount.
@return discountedAmount
*/
function applyLiquidationDiscount(uint256 _amount) public view override returns (uint256 discountedAmount) {
return _amount.wadDiv(IConfigProviderV1(address(a.config())).liquidationBonus().add(WadRayMath.wad()));
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "../interfaces/IAddressProvider.sol";
import "../interfaces/IVaultsCore.sol";
import "../interfaces/IAccessController.sol";
import "../interfaces/IConfigProvider.sol";
import "../interfaces/ISTABLEX.sol";
import "../interfaces/IPriceFeed.sol";
import "../interfaces/IRatesManager.sol";
import "../interfaces/IVaultsDataProvider.sol";
import "./interfaces/IConfigProviderV1.sol";
import "./interfaces/ILiquidationManagerV1.sol";
import "./interfaces/IVaultsCoreV1.sol";
contract AddressProviderV1 is IAddressProvider {
IAccessController public override controller;
IConfigProvider public override config;
IVaultsCore public override core;
ISTABLEX public override stablex;
IRatesManager public override ratesManager;
IPriceFeed public override priceFeed;
ILiquidationManager public override liquidationManager;
IVaultsDataProvider public override vaultsData;
IFeeDistributor public override feeDistributor;
constructor(IAccessController _controller) public {
controller = _controller;
}
modifier onlyManager() {
require(controller.hasRole(controller.MANAGER_ROLE(), msg.sender), "Caller is not a Manager");
_;
}
function setAccessController(IAccessController _controller) public override onlyManager {
require(address(_controller) != address(0));
controller = _controller;
}
function setConfigProvider(IConfigProvider _config) public override onlyManager {
require(address(_config) != address(0));
config = _config;
}
function setVaultsCore(IVaultsCore _core) public override onlyManager {
require(address(_core) != address(0));
core = _core;
}
function setStableX(ISTABLEX _stablex) public override onlyManager {
require(address(_stablex) != address(0));
stablex = _stablex;
}
function setRatesManager(IRatesManager _ratesManager) public override onlyManager {
require(address(_ratesManager) != address(0));
ratesManager = _ratesManager;
}
function setLiquidationManager(ILiquidationManager _liquidationManager) public override onlyManager {
require(address(_liquidationManager) != address(0));
liquidationManager = _liquidationManager;
}
function setPriceFeed(IPriceFeed _priceFeed) public override onlyManager {
require(address(_priceFeed) != address(0));
priceFeed = _priceFeed;
}
function setVaultsDataProvider(IVaultsDataProvider _vaultsData) public override onlyManager {
require(address(_vaultsData) != address(0));
vaultsData = _vaultsData;
}
function setFeeDistributor(IFeeDistributor _feeDistributor) public override onlyManager {
require(address(_feeDistributor) != address(0));
feeDistributor = _feeDistributor;
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "../libraries/WadRayMath.sol";
import "./interfaces/IConfigProviderV1.sol";
import "./interfaces/IAddressProviderV1.sol";
import "./interfaces/IVaultsCoreV1.sol";
contract ConfigProviderV1 is IConfigProviderV1 {
IAddressProviderV1 public override a;
mapping(uint256 => CollateralConfig) private _collateralConfigs; //indexing starts at 1
mapping(address => uint256) public override collateralIds;
uint256 public override numCollateralConfigs;
uint256 public override liquidationBonus = 5e16; // 5%
constructor(IAddressProviderV1 _addresses) public {
a = _addresses;
}
modifier onlyManager() {
require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager");
_;
}
/**
Creates or overwrites an existing config for a collateral type
@param _collateralType address of the collateral type
@param _debtLimit the debt ceiling for the collateral type
@param _minCollateralRatio the minimum ratio to maintain to avoid liquidation
@param _borrowRate the borrowing rate specified in 1 second interval in RAY accuracy.
@param _originationFee an optional origination fee for newly created debt. Can be 0.
*/
function setCollateralConfig(
address _collateralType,
uint256 _debtLimit,
uint256 _minCollateralRatio,
uint256 _borrowRate,
uint256 _originationFee
) public override onlyManager {
require(address(_collateralType) != address(0));
if (collateralIds[_collateralType] == 0) {
//new collateral
IVaultsCoreV1(address(a.core())).initializeRates(_collateralType);
CollateralConfig memory config = CollateralConfig({
collateralType: _collateralType,
debtLimit: _debtLimit,
minCollateralRatio: _minCollateralRatio,
borrowRate: _borrowRate,
originationFee: _originationFee
});
numCollateralConfigs++;
_collateralConfigs[numCollateralConfigs] = config;
collateralIds[_collateralType] = numCollateralConfigs;
} else {
// Update collateral config
IVaultsCoreV1(address(a.core())).refreshCollateral(_collateralType);
uint256 id = collateralIds[_collateralType];
_collateralConfigs[id].collateralType = _collateralType;
_collateralConfigs[id].debtLimit = _debtLimit;
_collateralConfigs[id].minCollateralRatio = _minCollateralRatio;
_collateralConfigs[id].borrowRate = _borrowRate;
_collateralConfigs[id].originationFee = _originationFee;
}
emit CollateralUpdated(_collateralType, _debtLimit, _minCollateralRatio, _borrowRate, _originationFee);
}
function _emitUpdateEvent(address _collateralType) internal {
emit CollateralUpdated(
_collateralType,
_collateralConfigs[collateralIds[_collateralType]].debtLimit,
_collateralConfigs[collateralIds[_collateralType]].minCollateralRatio,
_collateralConfigs[collateralIds[_collateralType]].borrowRate,
_collateralConfigs[collateralIds[_collateralType]].originationFee
);
}
/**
Remove the config for a collateral type
@param _collateralType address of the collateral type
*/
function removeCollateral(address _collateralType) public override onlyManager {
uint256 id = collateralIds[_collateralType];
require(id != 0, "collateral does not exist");
collateralIds[_collateralType] = 0;
_collateralConfigs[id] = _collateralConfigs[numCollateralConfigs]; //move last entry forward
collateralIds[_collateralConfigs[id].collateralType] = id; //update id for last entry
delete _collateralConfigs[numCollateralConfigs];
numCollateralConfigs--;
emit CollateralRemoved(_collateralType);
}
/**
Sets the debt limit for a collateral type
@param _collateralType address of the collateral type
@param _debtLimit the new debt limit
*/
function setCollateralDebtLimit(address _collateralType, uint256 _debtLimit) public override onlyManager {
_collateralConfigs[collateralIds[_collateralType]].debtLimit = _debtLimit;
_emitUpdateEvent(_collateralType);
}
/**
Sets the minimum collateralization ratio for a collateral type
@dev this is the liquidation treshold under which a vault is considered open for liquidation.
@param _collateralType address of the collateral type
@param _minCollateralRatio the new minimum collateralization ratio
*/
function setCollateralMinCollateralRatio(address _collateralType, uint256 _minCollateralRatio)
public
override
onlyManager
{
_collateralConfigs[collateralIds[_collateralType]].minCollateralRatio = _minCollateralRatio;
_emitUpdateEvent(_collateralType);
}
/**
Sets the borrowing rate for a collateral type
@dev borrowing rate is specified for a 1 sec interval and accurancy is in RAY.
@param _collateralType address of the collateral type
@param _borrowRate the new borrowing rate for a 1 sec interval
*/
function setCollateralBorrowRate(address _collateralType, uint256 _borrowRate) public override onlyManager {
IVaultsCoreV1(address(a.core())).refreshCollateral(_collateralType);
_collateralConfigs[collateralIds[_collateralType]].borrowRate = _borrowRate;
_emitUpdateEvent(_collateralType);
}
/**
Sets the origiation fee for a collateral type
@dev this rate is applied as a one time fee for new borrowing and is specified in WAD
@param _collateralType address of the collateral type
@param _originationFee new origination fee in WAD
*/
function setCollateralOriginationFee(address _collateralType, uint256 _originationFee) public override onlyManager {
_collateralConfigs[collateralIds[_collateralType]].originationFee = _originationFee;
_emitUpdateEvent(_collateralType);
}
/**
Get the debt limit for a collateral type
@dev this is a platform wide limit for new debt issuance against a specific collateral type
@param _collateralType address of the collateral type
*/
function collateralDebtLimit(address _collateralType) public view override returns (uint256) {
return _collateralConfigs[collateralIds[_collateralType]].debtLimit;
}
/**
Get the minimum collateralization ratio for a collateral type
@dev this is the liquidation treshold under which a vault is considered open for liquidation.
@param _collateralType address of the collateral type
*/
function collateralMinCollateralRatio(address _collateralType) public view override returns (uint256) {
return _collateralConfigs[collateralIds[_collateralType]].minCollateralRatio;
}
/**
Get the borrowing rate for a collateral type
@dev borrowing rate is specified for a 1 sec interval and accurancy is in RAY.
@param _collateralType address of the collateral type
*/
function collateralBorrowRate(address _collateralType) public view override returns (uint256) {
return _collateralConfigs[collateralIds[_collateralType]].borrowRate;
}
/**
Get the origiation fee for a collateral type
@dev this rate is applied as a one time fee for new borrowing and is specified in WAD
@param _collateralType address of the collateral type
*/
function collateralOriginationFee(address _collateralType) public view override returns (uint256) {
return _collateralConfigs[collateralIds[_collateralType]].originationFee;
}
/**
Set the platform wide incentive for liquidations.
@dev the liquidation bonus is specified in WAD
@param _bonus the liquidation bonus to be paid to liquidators
*/
function setLiquidationBonus(uint256 _bonus) public override onlyManager {
liquidationBonus = _bonus;
}
/**
Retreives the entire config for a specific config id.
@param _id the ID of the conifg to be returned
*/
function collateralConfigs(uint256 _id) public view override returns (CollateralConfig memory) {
require(_id <= numCollateralConfigs, "Invalid config id");
return _collateralConfigs[_id];
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../v1/interfaces/IConfigProviderV1.sol";
import "../v1/interfaces/IVaultsCoreV1.sol";
import "../v1/interfaces/IFeeDistributorV1.sol";
import "../interfaces/IAddressProvider.sol";
import "../interfaces/IVaultsCore.sol";
import "../interfaces/IVaultsCoreState.sol";
import "../interfaces/ILiquidationManager.sol";
import "../interfaces/IConfigProvider.sol";
import "../interfaces/IFeeDistributor.sol";
import "../liquidityMining/interfaces/IDebtNotifier.sol";
contract Upgrade {
using SafeMath for uint256;
uint256 public constant LIQUIDATION_BONUS = 5e16; // 5%
IAddressProvider public a;
IVaultsCore public core;
IVaultsCoreState public coreState;
ILiquidationManager public liquidationManager;
IConfigProvider public config;
IFeeDistributor public feeDistributor;
IDebtNotifier public debtNotifier;
IPriceFeed public priceFeed;
address public bpool;
modifier onlyManager() {
require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender));
_;
}
constructor(
IAddressProvider _addresses,
IVaultsCore _core,
IVaultsCoreState _coreState,
ILiquidationManager _liquidationManager,
IConfigProvider _config,
IFeeDistributor _feeDistributor,
IDebtNotifier _debtNotifier,
IPriceFeed _priceFeed,
address _bpool
) public {
require(address(_addresses) != address(0));
require(address(_core) != address(0));
require(address(_coreState) != address(0));
require(address(_liquidationManager) != address(0));
require(address(_config) != address(0));
require(address(_feeDistributor) != address(0));
require(address(_debtNotifier) != address(0));
require(address(_priceFeed) != address(0));
require(_bpool != address(0));
a = _addresses;
core = _core;
coreState = _coreState;
liquidationManager = _liquidationManager;
config = _config;
feeDistributor = _feeDistributor;
debtNotifier = _debtNotifier;
priceFeed = _priceFeed;
bpool = _bpool;
}
function upgrade() public onlyManager {
IConfigProviderV1 oldConfig = IConfigProviderV1(address(a.config()));
IPriceFeed oldPriceFeed = IPriceFeed(address(a.priceFeed()));
IVaultsCoreV1 oldCore = IVaultsCoreV1(address(a.core()));
IFeeDistributorV1 oldFeeDistributor = IFeeDistributorV1(address(a.feeDistributor()));
bytes32 MINTER_ROLE = a.controller().MINTER_ROLE();
bytes32 MANAGER_ROLE = a.controller().MANAGER_ROLE();
bytes32 DEFAULT_ADMIN_ROLE = 0x0000000000000000000000000000000000000000000000000000000000000000;
a.controller().grantRole(MANAGER_ROLE, address(this));
a.controller().grantRole(MINTER_ROLE, address(core));
a.controller().grantRole(MINTER_ROLE, address(feeDistributor));
oldCore.refresh();
if (oldCore.availableIncome() > 0) {
oldFeeDistributor.release();
}
a.controller().revokeRole(MINTER_ROLE, address(a.core()));
a.controller().revokeRole(MINTER_ROLE, address(a.feeDistributor()));
oldCore.upgrade(payable(address(core)));
a.setVaultsCore(core);
a.setConfigProvider(config);
a.setLiquidationManager(liquidationManager);
a.setFeeDistributor(feeDistributor);
a.setPriceFeed(priceFeed);
priceFeed.setEurOracle(address(oldPriceFeed.eurOracle()));
uint256 numCollateralConfigs = oldConfig.numCollateralConfigs();
for (uint256 i = 1; i <= numCollateralConfigs; i++) {
IConfigProviderV1.CollateralConfig memory collateralConfig = oldConfig.collateralConfigs(i);
config.setCollateralConfig(
collateralConfig.collateralType,
collateralConfig.debtLimit,
collateralConfig.minCollateralRatio,
collateralConfig.minCollateralRatio,
collateralConfig.borrowRate,
collateralConfig.originationFee,
LIQUIDATION_BONUS,
0
);
priceFeed.setAssetOracle(
collateralConfig.collateralType,
address(oldPriceFeed.assetOracles(collateralConfig.collateralType))
);
}
coreState.syncStateFromV1(oldCore);
core.acceptUpgrade(payable(address(oldCore)));
core.setDebtNotifier(debtNotifier);
debtNotifier.a().setDebtNotifier(debtNotifier);
address[] memory payees = new address[](2);
payees[0] = bpool;
payees[1] = address(core);
uint256[] memory shares = new uint256[](2);
shares[0] = uint256(90);
shares[1] = uint256(10);
feeDistributor.changePayees(payees, shares);
a.controller().revokeRole(MANAGER_ROLE, address(this));
a.controller().revokeRole(DEFAULT_ADMIN_ROLE, address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import './IAddressProviderV1.sol';
interface IFeeDistributorV1 {
event PayeeAdded(address indexed account, uint256 shares);
event FeeReleased(uint256 income, uint256 releasedAt);
function release() external;
function changePayees(address[] memory _payees, uint256[] memory _shares) external;
function a() external view returns (IAddressProviderV1);
function lastReleasedAt() external view returns (uint256);
function getPayees() external view returns (address[] memory);
function totalShares() external view returns (uint256);
function shares(address payee) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../liquidityMining/interfaces/IMIMO.sol";
import "../liquidityMining/interfaces/IMIMODistributor.sol";
import "../liquidityMining/interfaces/ISupplyMiner.sol";
import "../liquidityMining/interfaces/IDemandMiner.sol";
import "../liquidityMining/interfaces/IDebtNotifier.sol";
import "../libraries/WadRayMath.sol";
import "../governance/interfaces/IGovernanceAddressProvider.sol";
import "../governance/interfaces/IVotingEscrow.sol";
import "../interfaces/IAddressProvider.sol";
contract MIMODeployment {
IGovernanceAddressProvider public ga;
IMIMO public mimo;
IMIMODistributor public mimoDistributor;
ISupplyMiner public wethSupplyMiner;
ISupplyMiner public wbtcSupplyMiner;
ISupplyMiner public usdcSupplyMiner;
IDemandMiner public demandMiner;
IDebtNotifier public debtNotifier;
IVotingEscrow public votingEscrow;
address public weth;
address public wbtc;
address public usdc;
modifier onlyManager() {
require(ga.controller().hasRole(ga.controller().MANAGER_ROLE(), msg.sender), "Caller is not Manager");
_;
}
constructor(
IGovernanceAddressProvider _ga,
IMIMO _mimo,
IMIMODistributor _mimoDistributor,
ISupplyMiner _wethSupplyMiner,
ISupplyMiner _wbtcSupplyMiner,
ISupplyMiner _usdcSupplyMiner,
IDemandMiner _demandMiner,
IDebtNotifier _debtNotifier,
IVotingEscrow _votingEscrow,
address _weth,
address _wbtc,
address _usdc
) public {
require(address(_ga) != address(0));
require(address(_mimo) != address(0));
require(address(_mimoDistributor) != address(0));
require(address(_wethSupplyMiner) != address(0));
require(address(_wbtcSupplyMiner) != address(0));
require(address(_usdcSupplyMiner) != address(0));
require(address(_demandMiner) != address(0));
require(address(_debtNotifier) != address(0));
require(address(_votingEscrow) != address(0));
require(_weth != address(0));
require(_wbtc != address(0));
require(_usdc != address(0));
ga = _ga;
mimo = _mimo;
mimoDistributor = _mimoDistributor;
wethSupplyMiner = _wethSupplyMiner;
wbtcSupplyMiner = _wbtcSupplyMiner;
usdcSupplyMiner = _usdcSupplyMiner;
demandMiner = _demandMiner;
debtNotifier = _debtNotifier;
votingEscrow = _votingEscrow;
weth = _weth;
wbtc = _wbtc;
usdc = _usdc;
}
function setup() public onlyManager {
//IAddressProvider parallel = a.parallel();
//bytes32 MIMO_MINTER_ROLE = keccak256("MIMO_MINTER_ROLE");
//bytes32 DEFAULT_ADMIN_ROLE = 0x0000000000000000000000000000000000000000000000000000000000000000;
ga.setMIMO(mimo);
ga.setVotingEscrow(votingEscrow);
debtNotifier.setCollateralSupplyMiner(weth, wethSupplyMiner);
debtNotifier.setCollateralSupplyMiner(wbtc, wbtcSupplyMiner);
debtNotifier.setCollateralSupplyMiner(usdc, usdcSupplyMiner);
address[] memory payees = new address[](4);
payees[0] = address(wethSupplyMiner);
payees[1] = address(wbtcSupplyMiner);
payees[2] = address(usdcSupplyMiner);
payees[3] = address(demandMiner);
uint256[] memory shares = new uint256[](4);
shares[0] = uint256(20);
shares[1] = uint256(25);
shares[2] = uint256(5);
shares[3] = uint256(50);
mimoDistributor.changePayees(payees, shares);
bytes32 MANAGER_ROLE = ga.controller().MANAGER_ROLE();
ga.controller().renounceRole(MANAGER_ROLE, address(this));
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import '../../governance/interfaces/IGovernanceAddressProvider.sol';
import './IBaseDistributor.sol';
interface IMIMODistributorExtension {
function startTime() external view returns (uint256);
function currentIssuance() external view returns (uint256);
function weeklyIssuanceAt(uint256 timestamp) external view returns (uint256);
function totalSupplyAt(uint256 timestamp) external view returns (uint256);
}
interface IMIMODistributor is IBaseDistributor, IMIMODistributorExtension {}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IDemandMiner {
function deposit(uint256 amount) external;
function withdraw(uint256 amount) external;
function token() external view returns (IERC20);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import '../../governance/interfaces/IGovernanceAddressProvider.sol';
interface IBaseDistributor {
event PayeeAdded(address account, uint256 shares);
event TokensReleased(uint256 newTokens, uint256 releasedAt);
/**
Public function to release the accumulated new MIMO tokens to the payees.
@dev anyone can call this.
*/
function release() external;
/**
Updates the payee configuration to a new one.
@dev will release existing fees before the update.
@param _payees Array of payees
@param _shares Array of shares for each payee
*/
function changePayees(address[] memory _payees, uint256[] memory _shares) external;
function totalShares() external view returns (uint256);
function shares(address) external view returns (uint256);
function a() external view returns (IGovernanceAddressProvider);
function mintableTokens() external view returns (uint256);
/**
Get current configured payees.
@return array of current payees.
*/
function getPayees() external view returns (address[] memory);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/IAddressProvider.sol";
import "../interfaces/IVaultsDataProvider.sol";
import "../interfaces/IVaultsCore.sol";
contract RepayVault {
using SafeERC20 for IERC20;
using SafeMath for uint256;
uint256 public constant REPAY_PER_VAULT = 10 ether;
IAddressProvider public a;
constructor(IAddressProvider _addresses) public {
require(address(_addresses) != address(0));
a = _addresses;
}
modifier onlyManager() {
require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not Manager");
_;
}
function repay() public onlyManager {
IVaultsCore core = a.core();
IVaultsDataProvider vaultsData = a.vaultsData();
uint256 vaultCount = a.vaultsData().vaultCount();
for (uint256 vaultId = 1; vaultId <= vaultCount; vaultId++) {
uint256 baseDebt = vaultsData.vaultBaseDebt(vaultId);
//if (vaultId==28 || vaultId==29 || vaultId==30 || vaultId==31 || vaultId==32 || vaultId==33 || vaultId==35){
// continue;
//}
if (baseDebt == 0) {
continue;
}
core.repay(vaultId, REPAY_PER_VAULT);
}
IERC20 par = IERC20(a.stablex());
par.safeTransfer(msg.sender, par.balanceOf(address(this)));
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../libraries/WadRayMath.sol";
import "../interfaces/IVaultsCore.sol";
import "../interfaces/IAddressProvider.sol";
import "../interfaces/IWETH.sol";
import "../interfaces/IVaultsCoreState.sol";
import "../liquidityMining/interfaces/IDebtNotifier.sol";
contract VaultsCore is IVaultsCore, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using WadRayMath for uint256;
uint256 internal constant _MAX_INT = 2**256 - 1;
IAddressProvider public override a;
IWETH public override WETH;
IVaultsCoreState public override state;
IDebtNotifier public override debtNotifier;
modifier onlyManager() {
require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender));
_;
}
modifier onlyVaultOwner(uint256 _vaultId) {
require(a.vaultsData().vaultOwner(_vaultId) == msg.sender);
_;
}
constructor(
IAddressProvider _addresses,
IWETH _IWETH,
IVaultsCoreState _vaultsCoreState
) public {
require(address(_addresses) != address(0));
require(address(_IWETH) != address(0));
require(address(_vaultsCoreState) != address(0));
a = _addresses;
WETH = _IWETH;
state = _vaultsCoreState;
}
// For a contract to receive ETH, it needs to have a payable fallback function
// https://ethereum.stackexchange.com/a/47415
receive() external payable {
require(msg.sender == address(WETH));
}
/*
Allow smooth upgrading of the vaultscore.
@dev this function approves token transfers to the new vaultscore of
both stablex and all configured collateral types
@param _newVaultsCore address of the new vaultscore
*/
function upgrade(address payable _newVaultsCore) public override onlyManager {
require(address(_newVaultsCore) != address(0));
require(a.stablex().approve(_newVaultsCore, _MAX_INT));
for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) {
address collateralType = a.config().collateralConfigs(i).collateralType;
IERC20 asset = IERC20(collateralType);
asset.safeApprove(_newVaultsCore, _MAX_INT);
}
}
/*
Allow smooth upgrading of the VaultsCore.
@dev this function transfers both PAR and all configured collateral
types to the new vaultscore.
*/
function acceptUpgrade(address payable _oldVaultsCore) public override onlyManager {
IERC20 stableX = IERC20(a.stablex());
stableX.safeTransferFrom(_oldVaultsCore, address(this), stableX.balanceOf(_oldVaultsCore));
for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) {
address collateralType = a.config().collateralConfigs(i).collateralType;
IERC20 asset = IERC20(collateralType);
asset.safeTransferFrom(_oldVaultsCore, address(this), asset.balanceOf(_oldVaultsCore));
}
}
/**
Configure the debt notifier.
@param _debtNotifier the new DebtNotifier module address.
**/
function setDebtNotifier(IDebtNotifier _debtNotifier) public override onlyManager {
require(address(_debtNotifier) != address(0));
debtNotifier = _debtNotifier;
}
/**
Deposit an ERC20 token into the vault of the msg.sender as collateral
@dev A new vault is created if no vault exists for the `msg.sender` with the specified collateral type.
this function uses `transferFrom()` and requires pre-approval via `approve()` on the ERC20.
@param _collateralType the address of the collateral type to be deposited
@param _amount the amount of tokens to be deposited in WEI.
**/
function deposit(address _collateralType, uint256 _amount) public override {
require(a.config().collateralIds(_collateralType) != 0);
IERC20 asset = IERC20(_collateralType);
asset.safeTransferFrom(msg.sender, address(this), _amount);
_addCollateralToVault(_collateralType, _amount);
}
/**
Wraps ETH and deposits WETH into the vault of the msg.sender as collateral
@dev A new vault is created if no WETH vault exists
**/
function depositETH() public payable override {
WETH.deposit{ value: msg.value }();
_addCollateralToVault(address(WETH), msg.value);
}
/**
Deposit an ERC20 token into the specified vault as collateral
@dev this function uses `transferFrom()` and requires pre-approval via `approve()` on the ERC20.
@param _vaultId the address of the collateral type to be deposited
@param _amount the amount of tokens to be deposited in WEI.
**/
function depositByVaultId(uint256 _vaultId, uint256 _amount) public override {
IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId);
require(v.collateralType != address(0));
IERC20 asset = IERC20(v.collateralType);
asset.safeTransferFrom(msg.sender, address(this), _amount);
_addCollateralToVaultById(_vaultId, _amount);
}
/**
Wraps ETH and deposits WETH into the specified vault as collateral
@dev this function uses `transferFrom()` and requires pre-approval via `approve()` on the ERC20.
@param _vaultId the address of the collateral type to be deposited
**/
function depositETHByVaultId(uint256 _vaultId) public payable override {
IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId);
require(v.collateralType == address(WETH));
WETH.deposit{ value: msg.value }();
_addCollateralToVaultById(_vaultId, msg.value);
}
/**
Deposit an ERC20 token into the vault of the msg.sender as collateral and borrows the specified amount of tokens in WEI
@dev see deposit() and borrow()
@param _collateralType the address of the collateral type to be deposited
@param _depositAmount the amount of tokens to be deposited in WEI.
@param _borrowAmount the amount of borrowed StableX tokens in WEI.
**/
function depositAndBorrow(
address _collateralType,
uint256 _depositAmount,
uint256 _borrowAmount
) public override {
deposit(_collateralType, _depositAmount);
uint256 vaultId = a.vaultsData().vaultId(_collateralType, msg.sender);
borrow(vaultId, _borrowAmount);
}
/**
Wraps ETH and deposits WETH into the vault of the msg.sender as collateral and borrows the specified amount of tokens in WEI
@dev see depositETH() and borrow()
@param _borrowAmount the amount of borrowed StableX tokens in WEI.
**/
function depositETHAndBorrow(uint256 _borrowAmount) public payable override {
depositETH();
uint256 vaultId = a.vaultsData().vaultId(address(WETH), msg.sender);
borrow(vaultId, _borrowAmount);
}
function _addCollateralToVault(address _collateralType, uint256 _amount) internal {
uint256 vaultId = a.vaultsData().vaultId(_collateralType, msg.sender);
if (vaultId == 0) {
vaultId = a.vaultsData().createVault(_collateralType, msg.sender);
}
_addCollateralToVaultById(vaultId, _amount);
}
function _addCollateralToVaultById(uint256 _vaultId, uint256 _amount) internal {
IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId);
a.vaultsData().setCollateralBalance(_vaultId, v.collateralBalance.add(_amount));
emit Deposited(_vaultId, _amount, msg.sender);
}
/**
Withdraws ERC20 tokens from a vault.
@dev Only the owner of a vault can withdraw collateral from it.
`withdraw()` will fail if it would bring the vault below the minimum collateralization treshold.
@param _vaultId the ID of the vault from which to withdraw the collateral.
@param _amount the amount of ERC20 tokens to be withdrawn in WEI.
**/
function withdraw(uint256 _vaultId, uint256 _amount) public override onlyVaultOwner(_vaultId) nonReentrant {
_removeCollateralFromVault(_vaultId, _amount);
IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId);
IERC20 asset = IERC20(v.collateralType);
asset.safeTransfer(msg.sender, _amount);
}
/**
Withdraws ETH from a WETH vault.
@dev Only the owner of a vault can withdraw collateral from it.
`withdraw()` will fail if it would bring the vault below the minimum collateralization treshold.
@param _vaultId the ID of the vault from which to withdraw the collateral.
@param _amount the amount of ETH to be withdrawn in WEI.
**/
function withdrawETH(uint256 _vaultId, uint256 _amount) public override onlyVaultOwner(_vaultId) nonReentrant {
_removeCollateralFromVault(_vaultId, _amount);
IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId);
require(v.collateralType == address(WETH));
WETH.withdraw(_amount);
msg.sender.transfer(_amount);
}
function _removeCollateralFromVault(uint256 _vaultId, uint256 _amount) internal {
IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId);
require(_amount <= v.collateralBalance);
uint256 newCollateralBalance = v.collateralBalance.sub(_amount);
a.vaultsData().setCollateralBalance(_vaultId, newCollateralBalance);
if (v.baseDebt > 0) {
// Save gas cost when withdrawing from 0 debt vault
state.refreshCollateral(v.collateralType);
uint256 newCollateralValue = a.priceFeed().convertFrom(v.collateralType, newCollateralBalance);
require(
a.liquidationManager().isHealthy(
newCollateralValue,
a.vaultsData().vaultDebt(_vaultId),
a.config().collateralConfigs(a.config().collateralIds(v.collateralType)).minCollateralRatio
)
);
}
emit Withdrawn(_vaultId, _amount, msg.sender);
}
/**
Borrow new PAR tokens from a vault.
@dev Only the owner of a vault can borrow from it.
`borrow()` will update the outstanding vault debt to the current time before attempting the withdrawal.
`borrow()` will fail if it would bring the vault below the minimum collateralization treshold.
@param _vaultId the ID of the vault from which to borrow.
@param _amount the amount of borrowed PAR tokens in WEI.
**/
function borrow(uint256 _vaultId, uint256 _amount) public override onlyVaultOwner(_vaultId) nonReentrant {
IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId);
// Make sure current rate is up to date
state.refreshCollateral(v.collateralType);
uint256 originationFeePercentage = a.config().collateralOriginationFee(v.collateralType);
uint256 newDebt = _amount;
if (originationFeePercentage > 0) {
newDebt = newDebt.add(_amount.wadMul(originationFeePercentage));
}
// Increment vault borrow balance
uint256 newBaseDebt = a.ratesManager().calculateBaseDebt(newDebt, cumulativeRates(v.collateralType));
a.vaultsData().setBaseDebt(_vaultId, v.baseDebt.add(newBaseDebt));
uint256 collateralValue = a.priceFeed().convertFrom(v.collateralType, v.collateralBalance);
uint256 newVaultDebt = a.vaultsData().vaultDebt(_vaultId);
require(a.vaultsData().collateralDebt(v.collateralType) <= a.config().collateralDebtLimit(v.collateralType));
bool isHealthy = a.liquidationManager().isHealthy(
collateralValue,
newVaultDebt,
a.config().collateralConfigs(a.config().collateralIds(v.collateralType)).minCollateralRatio
);
require(isHealthy);
a.stablex().mint(msg.sender, _amount);
debtNotifier.debtChanged(_vaultId);
emit Borrowed(_vaultId, _amount, msg.sender);
}
/**
Convenience function to repay all debt of a vault
@dev `repayAll()` will update the outstanding vault debt to the current time.
@param _vaultId the ID of the vault for which to repay the debt.
**/
function repayAll(uint256 _vaultId) public override {
repay(_vaultId, _MAX_INT);
}
/**
Repay an outstanding PAR balance to a vault.
@dev `repay()` will update the outstanding vault debt to the current time.
@param _vaultId the ID of the vault for which to repay the outstanding debt balance.
@param _amount the amount of PAR tokens in WEI to be repaid.
**/
function repay(uint256 _vaultId, uint256 _amount) public override nonReentrant {
address collateralType = a.vaultsData().vaultCollateralType(_vaultId);
// Make sure current rate is up to date
state.refreshCollateral(collateralType);
uint256 currentVaultDebt = a.vaultsData().vaultDebt(_vaultId);
// Decrement vault borrow balance
if (_amount >= currentVaultDebt) {
//full repayment
_amount = currentVaultDebt; //only pay back what's outstanding
}
_reduceVaultDebt(_vaultId, _amount);
a.stablex().burn(msg.sender, _amount);
debtNotifier.debtChanged(_vaultId);
emit Repaid(_vaultId, _amount, msg.sender);
}
/**
Internal helper function to reduce the debt of a vault.
@dev assumes cumulative rates for the vault's collateral type are up to date.
please call `refreshCollateral()` before calling this function.
@param _vaultId the ID of the vault for which to reduce the debt.
@param _amount the amount of debt to be reduced.
**/
function _reduceVaultDebt(uint256 _vaultId, uint256 _amount) internal {
address collateralType = a.vaultsData().vaultCollateralType(_vaultId);
uint256 currentVaultDebt = a.vaultsData().vaultDebt(_vaultId);
uint256 remainder = currentVaultDebt.sub(_amount);
uint256 cumulativeRate = cumulativeRates(collateralType);
if (remainder == 0) {
a.vaultsData().setBaseDebt(_vaultId, 0);
} else {
uint256 newBaseDebt = a.ratesManager().calculateBaseDebt(remainder, cumulativeRate);
a.vaultsData().setBaseDebt(_vaultId, newBaseDebt);
}
}
/**
Liquidate a vault that is below the liquidation treshold by repaying its outstanding debt.
@dev `liquidate()` will update the outstanding vault debt to the current time and pay a `liquidationBonus`
to the liquidator. `liquidate()` can be called by anyone.
@param _vaultId the ID of the vault to be liquidated.
**/
function liquidate(uint256 _vaultId) public override {
liquidatePartial(_vaultId, _MAX_INT);
}
/**
Liquidate a vault partially that is below the liquidation treshold by repaying part of its outstanding debt.
@dev `liquidatePartial()` will update the outstanding vault debt to the current time and pay a `liquidationBonus`
to the liquidator. A LiquidationFee will be applied to the borrower during the liquidation.
This means that the change in outstanding debt can be smaller than the repaid amount.
`liquidatePartial()` can be called by anyone.
@param _vaultId the ID of the vault to be liquidated.
@param _amount the amount of debt+liquidationFee to repay.
**/
function liquidatePartial(uint256 _vaultId, uint256 _amount) public override nonReentrant {
IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId);
state.refreshCollateral(v.collateralType);
uint256 collateralValue = a.priceFeed().convertFrom(v.collateralType, v.collateralBalance);
uint256 currentVaultDebt = a.vaultsData().vaultDebt(_vaultId);
require(
!a.liquidationManager().isHealthy(
collateralValue,
currentVaultDebt,
a.config().collateralConfigs(a.config().collateralIds(v.collateralType)).liquidationRatio
)
);
uint256 repaymentAfterLiquidationFeeRatio = WadRayMath.wad().sub(
a.config().collateralLiquidationFee(v.collateralType)
);
uint256 maxLiquiditionCost = currentVaultDebt.wadDiv(repaymentAfterLiquidationFeeRatio);
uint256 repayAmount;
if (_amount > maxLiquiditionCost) {
_amount = maxLiquiditionCost;
repayAmount = currentVaultDebt;
} else {
repayAmount = _amount.wadMul(repaymentAfterLiquidationFeeRatio);
}
// collateral value to be received by the liquidator is based on the total amount repaid (including the liquidationFee).
uint256 collateralValueToReceive = _amount.add(a.liquidationManager().liquidationBonus(v.collateralType, _amount));
uint256 insuranceAmount = 0;
if (collateralValueToReceive >= collateralValue) {
// Not enough collateral for debt & liquidation fee
collateralValueToReceive = collateralValue;
uint256 discountedCollateralValue = a.liquidationManager().applyLiquidationDiscount(
v.collateralType,
collateralValue
);
if (currentVaultDebt > discountedCollateralValue) {
// Not enough collateral for debt alone
insuranceAmount = currentVaultDebt.sub(discountedCollateralValue);
require(a.stablex().balanceOf(address(this)) >= insuranceAmount);
a.stablex().burn(address(this), insuranceAmount); // Insurance uses local reserves to pay down debt
emit InsurancePaid(_vaultId, insuranceAmount, msg.sender);
}
repayAmount = currentVaultDebt.sub(insuranceAmount);
_amount = discountedCollateralValue;
}
// reduce the vault debt by repayAmount
_reduceVaultDebt(_vaultId, repayAmount.add(insuranceAmount));
a.stablex().burn(msg.sender, _amount);
// send the claimed collateral to the liquidator
uint256 collateralToReceive = a.priceFeed().convertTo(v.collateralType, collateralValueToReceive);
a.vaultsData().setCollateralBalance(_vaultId, v.collateralBalance.sub(collateralToReceive));
IERC20 asset = IERC20(v.collateralType);
asset.safeTransfer(msg.sender, collateralToReceive);
debtNotifier.debtChanged(_vaultId);
emit Liquidated(_vaultId, repayAmount, collateralToReceive, v.owner, msg.sender);
}
/**
Returns the cumulativeRate of a collateral type. This function exists for
backwards compatibility with the VaultsDataProvider.
@param _collateralType the address of the collateral type.
**/
function cumulativeRates(address _collateralType) public view override returns (uint256) {
return state.cumulativeRates(_collateralType);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../libraries/WadRayMath.sol";
import "../interfaces/IAddressProvider.sol";
import "../interfaces/IVaultsCoreState.sol";
import "../v1/interfaces/IVaultsCoreV1.sol";
contract VaultsCoreState is IVaultsCoreState {
using SafeMath for uint256;
using WadRayMath for uint256;
uint256 internal constant _MAX_INT = 2**256 - 1;
bool public override synced = false;
IAddressProvider public override a;
mapping(address => uint256) public override cumulativeRates;
mapping(address => uint256) public override lastRefresh;
modifier onlyConfig() {
require(msg.sender == address(a.config()));
_;
}
modifier onlyManager() {
require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender));
_;
}
modifier notSynced() {
require(!synced);
_;
}
constructor(IAddressProvider _addresses) public {
require(address(_addresses) != address(0));
a = _addresses;
}
/**
Calculate the available income
@return available income that has not been minted yet.
**/
function availableIncome() public view override returns (uint256) {
return a.vaultsData().debt().sub(a.stablex().totalSupply());
}
/**
Refresh the cumulative rates and debts of all vaults and all collateral types.
@dev anyone can call this.
**/
function refresh() public override {
for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) {
address collateralType = a.config().collateralConfigs(i).collateralType;
refreshCollateral(collateralType);
}
}
/**
Sync state with another instance. This is used during version upgrade to keep V2 in sync with V2.
@dev This call will read the state via
`cumulativeRates(address collateralType)` and `lastRefresh(address collateralType)`.
@param _stateAddress address from which the state is to be copied.
**/
function syncState(IVaultsCoreState _stateAddress) public override onlyManager notSynced {
for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) {
address collateralType = a.config().collateralConfigs(i).collateralType;
cumulativeRates[collateralType] = _stateAddress.cumulativeRates(collateralType);
lastRefresh[collateralType] = _stateAddress.lastRefresh(collateralType);
}
synced = true;
}
/**
Sync state with v1 core. This is used during version upgrade to keep V2 in sync with V1.
@dev This call will read the state via
`cumulativeRates(address collateralType)` and `lastRefresh(address collateralType)`.
@param _core address of core v1 from which the state is to be copied.
**/
function syncStateFromV1(IVaultsCoreV1 _core) public override onlyManager notSynced {
for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) {
address collateralType = a.config().collateralConfigs(i).collateralType;
cumulativeRates[collateralType] = _core.cumulativeRates(collateralType);
lastRefresh[collateralType] = _core.lastRefresh(collateralType);
}
synced = true;
}
/**
Initialize the cumulative rates to 1 for a new collateral type.
@param _collateralType the address of the new collateral type to be initialized
**/
function initializeRates(address _collateralType) public override onlyConfig {
require(_collateralType != address(0));
lastRefresh[_collateralType] = block.timestamp;
cumulativeRates[_collateralType] = WadRayMath.ray();
}
/**
Refresh the cumulative rate of a collateraltype.
@dev this updates the debt for all vaults with the specified collateral type.
@param _collateralType the address of the collateral type to be refreshed.
**/
function refreshCollateral(address _collateralType) public override {
require(_collateralType != address(0));
require(a.config().collateralIds(_collateralType) != 0);
uint256 timestamp = block.timestamp;
uint256 timeElapsed = timestamp.sub(lastRefresh[_collateralType]);
_refreshCumulativeRate(_collateralType, timeElapsed);
lastRefresh[_collateralType] = timestamp;
}
/**
Internal function to increase the cumulative rate over a specified time period
@dev this updates the debt for all vaults with the specified collateral type.
@param _collateralType the address of the collateral type to be updated
@param _timeElapsed the amount of time in seconds to add to the cumulative rate
**/
function _refreshCumulativeRate(address _collateralType, uint256 _timeElapsed) internal {
uint256 borrowRate = a.config().collateralBorrowRate(_collateralType);
uint256 oldCumulativeRate = cumulativeRates[_collateralType];
cumulativeRates[_collateralType] = a.ratesManager().calculateCumulativeRate(
borrowRate,
oldCumulativeRate,
_timeElapsed
);
emit CumulativeRateUpdated(_collateralType, _timeElapsed, cumulativeRates[_collateralType]);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../libraries/WadRayMath.sol";
import "../interfaces/ISTABLEX.sol";
import "./interfaces/IFeeDistributorV1.sol";
import "./interfaces/IAddressProviderV1.sol";
contract FeeDistributorV1 is IFeeDistributorV1, ReentrancyGuard {
using SafeMath for uint256;
event PayeeAdded(address account, uint256 shares);
event FeeReleased(uint256 income, uint256 releasedAt);
uint256 public override lastReleasedAt;
IAddressProviderV1 public override a;
uint256 public override totalShares;
mapping(address => uint256) public override shares;
address[] public payees;
modifier onlyManager() {
require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not Manager");
_;
}
constructor(IAddressProviderV1 _addresses) public {
require(address(_addresses) != address(0));
a = _addresses;
}
/**
Public function to release the accumulated fee income to the payees.
@dev anyone can call this.
*/
function release() public override nonReentrant {
uint256 income = a.core().availableIncome();
require(income > 0, "income is 0");
require(payees.length > 0, "Payees not configured yet");
lastReleasedAt = now;
// Mint USDX to all receivers
for (uint256 i = 0; i < payees.length; i++) {
address payee = payees[i];
_release(income, payee);
}
emit FeeReleased(income, lastReleasedAt);
}
/**
Get current configured payees.
@return array of current payees.
*/
function getPayees() public view override returns (address[] memory) {
return payees;
}
/**
Internal function to release a percentage of income to a specific payee
@dev uses totalShares to calculate correct share
@param _totalIncomeReceived Total income for all payees, will be split according to shares
@param _payee The address of the payee to whom to distribute the fees.
*/
function _release(uint256 _totalIncomeReceived, address _payee) internal {
uint256 payment = _totalIncomeReceived.mul(shares[_payee]).div(totalShares);
a.stablex().mint(_payee, payment);
}
/**
Internal function to add a new payee.
@dev will update totalShares and therefore reduce the relative share of all other payees.
@param _payee The address of the payee to add.
@param _shares The number of shares owned by the payee.
*/
function _addPayee(address _payee, uint256 _shares) internal {
require(_payee != address(0), "payee is the zero address");
require(_shares > 0, "shares are 0");
require(shares[_payee] == 0, "payee already has shares");
payees.push(_payee);
shares[_payee] = _shares;
totalShares = totalShares.add(_shares);
emit PayeeAdded(_payee, _shares);
}
/**
Updates the payee configuration to a new one.
@dev will release existing fees before the update.
@param _payees Array of payees
@param _shares Array of shares for each payee
*/
function changePayees(address[] memory _payees, uint256[] memory _shares) public override onlyManager {
require(_payees.length == _shares.length, "Payees and shares mismatched");
require(_payees.length > 0, "No payees");
uint256 income = a.core().availableIncome();
if (income > 0 && payees.length > 0) {
release();
}
for (uint256 i = 0; i < payees.length; i++) {
delete shares[payees[i]];
}
delete payees;
totalShares = 0;
for (uint256 i = 0; i < _payees.length; i++) {
_addPayee(_payees[i], _shares[i]);
}
}
}
// solium-disable security/no-block-members
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../interfaces/IAddressProvider.sol";
import "../interfaces/ISTABLEX.sol";
/**
* @title USDX
* @notice Stablecoin which can be minted against collateral in a vault
*/
contract USDX is ISTABLEX, ERC20("USD Stablecoin", "USDX") {
IAddressProvider public override a;
constructor(IAddressProvider _addresses) public {
require(address(_addresses) != address(0));
a = _addresses;
}
function mint(address account, uint256 amount) public override onlyMinter {
_mint(account, amount);
}
function burn(address account, uint256 amount) public override onlyMinter {
_burn(account, amount);
}
modifier onlyMinter() {
require(a.controller().hasRole(a.controller().MINTER_ROLE(), msg.sender), "Caller is not a minter");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
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 {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @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);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// solium-disable security/no-block-members
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../interfaces/IAddressProvider.sol";
import "../interfaces/ISTABLEX.sol";
/**
* @title PAR
* @notice Stablecoin which can be minted against collateral in a vault
*/
contract PAR is ISTABLEX, ERC20("PAR Stablecoin", "PAR") {
IAddressProvider public override a;
constructor(IAddressProvider _addresses) public {
require(address(_addresses) != address(0));
a = _addresses;
}
function mint(address account, uint256 amount) public override onlyMinter {
_mint(account, amount);
}
function burn(address account, uint256 amount) public override onlyMinter {
_burn(account, amount);
}
modifier onlyMinter() {
require(a.controller().hasRole(a.controller().MINTER_ROLE(), msg.sender), "Caller is not a minter");
_;
}
}
// solium-disable security/no-block-members
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../governance/interfaces/IGovernanceAddressProvider.sol";
/**
* @title MIMO
* @notice MIMO Governance token
*/
contract MIMO is ERC20("MIMO Parallel Governance Token", "MIMO") {
IGovernanceAddressProvider public a;
bytes32 public constant MIMO_MINTER_ROLE = keccak256("MIMO_MINTER_ROLE");
constructor(IGovernanceAddressProvider _a) public {
require(address(_a) != address(0));
a = _a;
}
modifier onlyMIMOMinter() {
require(a.controller().hasRole(MIMO_MINTER_ROLE, msg.sender), "Caller is not MIMO Minter");
_;
}
function mint(address account, uint256 amount) public onlyMIMOMinter {
_mint(account, amount);
}
function burn(address account, uint256 amount) public onlyMIMOMinter {
_burn(account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../token/MIMO.sol";
import "../governance/interfaces/IGovernanceAddressProvider.sol";
import "../liquidityMining/interfaces/IMIMODistributor.sol";
contract PreUseAirdrop {
using SafeERC20 for IERC20;
struct Payout {
address recipient;
uint256 amount;
}
Payout[] public payouts;
IGovernanceAddressProvider public ga;
IMIMODistributor public mimoDistributor;
modifier onlyManager() {
require(ga.controller().hasRole(ga.controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager");
_;
}
constructor(IGovernanceAddressProvider _ga, IMIMODistributor _mimoDistributor) public {
require(address(_ga) != address(0));
require(address(_mimoDistributor) != address(0));
ga = _ga;
mimoDistributor = _mimoDistributor;
payouts.push(Payout(0xBBd92c75C6f8B0FFe9e5BCb2e56a5e2600871a10, 271147720731494841509243076));
payouts.push(Payout(0xcc8793d5eB95fAa707ea4155e09b2D3F44F33D1E, 210989402066696530434956148));
payouts.push(Payout(0x185f19B43d818E10a31BE68f445ef8EDCB8AFB83, 22182938994846641176273320));
payouts.push(Payout(0xDeD9F901D40A96C3Ee558E6885bcc7eFC51ad078, 13678603288816593264718593));
payouts.push(Payout(0x0B3890bbF2553Bd098B45006aDD734d6Fbd6089E, 8416873402881706143143730));
payouts.push(Payout(0x3F41a1CFd3C8B8d9c162dE0f42307a0095A6e5DF, 7159719590701445955473554));
payouts.push(Payout(0x9115BaDce4873d58fa73b08279529A796550999a, 5632453715407980754075398));
payouts.push(Payout(0x7BC8C0B66d7f0E2193ED11eeCAAfE7c1837b926f, 5414893264683531027764823));
payouts.push(Payout(0xE7809aaaaa78E5a24E059889E561f598F3a4664c, 4712320945661497844704387));
payouts.push(Payout(0xf4D3566729f257edD0D4bF365d8f0Db7bF56e1C6, 2997276841876706895655431));
payouts.push(Payout(0x6Cf9AA65EBaD7028536E353393630e2340ca6049, 2734992792750385321760387));
payouts.push(Payout(0x74386381Cb384CC0FBa0Ac669d22f515FfC147D2, 1366427847282177615773594));
payouts.push(Payout(0x9144b150f28437E06Ab5FF5190365294eb1E87ec, 1363226310703652991601514));
payouts.push(Payout(0x5691d53685e8e219329bD8ADf62b1A0A17df9D11, 702790464733701088417744));
payouts.push(Payout(0x2B91B4f5223a0a1f5c7e1D139dDdD6B5B57C7A51, 678663683269882192090830));
payouts.push(Payout(0x8ddBad507F3b20239516810C308Ba4f3BaeAf3a1, 635520835923336863138335));
payouts.push(Payout(0xc3874A2C59b9779A75874Be6B5f0b578120A8701, 488385391000796390198744));
payouts.push(Payout(0x0A22C160f7E57F2e7d88b2fa1B1B03571bdE6128, 297735186117080365383063));
payouts.push(Payout(0x0a1aa2b65832fC0c71f2Ba488c84BeE0b9DB9692, 132688033756581498940995));
payouts.push(Payout(0xAf7b7AbC272a3aE6dD6dA41b9832C758477a85f2, 130254714680714068405131));
payouts.push(Payout(0xCDb17d9bCbA8E3bab6F68D59065efe784700Bee1, 71018627162763037055295));
payouts.push(Payout(0x4Dec19003F9Bb01A4c0D089605618b2d76deE30d, 69655357581389001902516));
payouts.push(Payout(0x31AacA1940C82130c2D4407E609e626E87A7BC18, 21678478730854029506989));
payouts.push(Payout(0xBc77AB8dd8BAa6ddf0D0c241d31b2e30bcEC127d, 21573657481017931484432));
payouts.push(Payout(0x1c25cDD83Cd7106C3dcB361230eC9E6930Aadd30, 14188368728356337446426));
payouts.push(Payout(0xf1B78ed53fa2f9B8cFfa677Ad8023aCa92109d08, 13831474058511281838532));
payouts.push(Payout(0xd27962455de27561e62345a516931F2392997263, 6968208393315527988941));
payouts.push(Payout(0xD8A4411C623aD361E98bC9D98cA33eE1cF308Bca, 4476771187861728227997));
payouts.push(Payout(0x1f06fA59809ee23Ee06e533D67D29C6564fC1964, 3358338614042115121460));
payouts.push(Payout(0xeDccc1501e3BCC8b3973B9BE33f6Bd7072d28388, 2328788070517256560738));
payouts.push(Payout(0xD738A884B2aFE625d372260E57e86E3eB4d5e1D7, 466769668474372743140));
payouts.push(Payout(0x6942b1b6526Fa05035d47c09B419039c00Ef7545, 442736084997163005698));
}
function airdrop() public onlyManager {
MIMO mimo = MIMO(address(ga.mimo()));
for (uint256 i = 0; i < payouts.length; i++) {
Payout memory payout = payouts[i];
mimo.mint(payout.recipient, payout.amount);
}
require(mimoDistributor.mintableTokens() > 0);
bytes32 MIMO_MINTER_ROLE = mimo.MIMO_MINTER_ROLE();
ga.controller().renounceRole(MIMO_MINTER_ROLE, address(this));
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../libraries/WadRayMath.sol";
import "../governance/interfaces/IGovernanceAddressProvider.sol";
import "./interfaces/IMIMODistributor.sol";
import "./BaseDistributor.sol";
contract MIMODistributorV2 is BaseDistributor, IMIMODistributorExtension {
using SafeMath for uint256;
using WadRayMath for uint256;
uint256 private constant _SECONDS_PER_YEAR = 365 days;
uint256 private constant _SECONDS_PER_WEEK = 7 days;
uint256 private constant _WEEKLY_R = 986125e21; // -1.3875% per week (-5.55% / 4)
uint256 private _FIRST_WEEK_TOKENS;
uint256 public override startTime;
uint256 public alreadyMinted;
constructor(
IGovernanceAddressProvider _a,
uint256 _startTime,
IMIMODistributor _mimoDistributor
) public {
require(address(_a) != address(0));
require(address(_mimoDistributor) != address(0));
a = _a;
startTime = _startTime;
alreadyMinted = _mimoDistributor.totalSupplyAt(startTime);
uint256 weeklyIssuanceV1 = _mimoDistributor.weeklyIssuanceAt(startTime);
_FIRST_WEEK_TOKENS = weeklyIssuanceV1 / 4; // reduce weeky issuance by 4
}
/**
Get current monthly issuance of new MIMO tokens.
@return number of monthly issued tokens currently`.
*/
function currentIssuance() public view override returns (uint256) {
return weeklyIssuanceAt(now);
}
/**
Get monthly issuance of new MIMO tokens at `timestamp`.
@dev invalid for timestamps before deployment
@param timestamp for which to calculate the monthly issuance
@return number of monthly issued tokens at `timestamp`.
*/
function weeklyIssuanceAt(uint256 timestamp) public view override returns (uint256) {
uint256 elapsedSeconds = timestamp.sub(startTime);
uint256 elapsedWeeks = elapsedSeconds.div(_SECONDS_PER_WEEK);
return _WEEKLY_R.rayPow(elapsedWeeks).rayMul(_FIRST_WEEK_TOKENS);
}
/**
Calculates how many MIMO tokens can be minted since the last time tokens were minted
@return number of mintable tokens available right now.
*/
function mintableTokens() public view override returns (uint256) {
return totalSupplyAt(now).sub(a.mimo().totalSupply());
}
/**
Calculates the totalSupply for any point after `startTime`
@param timestamp for which to calculate the totalSupply
@return totalSupply at timestamp.
*/
function totalSupplyAt(uint256 timestamp) public view override returns (uint256) {
uint256 elapsedSeconds = timestamp.sub(startTime);
uint256 elapsedWeeks = elapsedSeconds.div(_SECONDS_PER_WEEK);
uint256 lastWeekSeconds = elapsedSeconds % _SECONDS_PER_WEEK;
uint256 one = WadRayMath.ray();
uint256 fullWeeks = one.sub(_WEEKLY_R.rayPow(elapsedWeeks)).rayMul(_FIRST_WEEK_TOKENS).rayDiv(one.sub(_WEEKLY_R));
uint256 currentWeekIssuance = weeklyIssuanceAt(timestamp);
uint256 partialWeek = currentWeekIssuance.mul(lastWeekSeconds).div(_SECONDS_PER_WEEK);
return alreadyMinted.add(fullWeeks.add(partialWeek));
}
/**
Internal function to release a percentage of newTokens to a specific payee
@dev uses totalShares to calculate correct share
@param _totalnewTokensReceived Total newTokens for all payees, will be split according to shares
@param _payee The address of the payee to whom to distribute the fees.
*/
function _release(uint256 _totalnewTokensReceived, address _payee) internal override {
uint256 payment = _totalnewTokensReceived.mul(shares[_payee]).div(totalShares);
a.mimo().mint(_payee, payment);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../libraries/WadRayMath.sol";
import "../governance/interfaces/IGovernanceAddressProvider.sol";
import "./interfaces/IBaseDistributor.sol";
/*
Distribution Formula:
55.5m MIMO in first week
-5.55% redution per week
total(timestamp) = _SECONDS_PER_WEEK * ( (1-weeklyR^(timestamp/_SECONDS_PER_WEEK)) / (1-weeklyR) )
+ timestamp % _SECONDS_PER_WEEK * (1-weeklyR^(timestamp/_SECONDS_PER_WEEK)
*/
abstract contract BaseDistributor is IBaseDistributor {
using SafeMath for uint256;
using WadRayMath for uint256;
uint256 public override totalShares;
mapping(address => uint256) public override shares;
address[] public payees;
IGovernanceAddressProvider public override a;
modifier onlyManager() {
require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not Manager");
_;
}
/**
Public function to release the accumulated new MIMO tokens to the payees.
@dev anyone can call this.
*/
function release() public override {
uint256 newTokens = mintableTokens();
require(newTokens > 0, "newTokens is 0");
require(payees.length > 0, "Payees not configured yet");
// Mint MIMO to all receivers
for (uint256 i = 0; i < payees.length; i++) {
address payee = payees[i];
_release(newTokens, payee);
}
emit TokensReleased(newTokens, now);
}
/**
Updates the payee configuration to a new one.
@dev will release existing fees before the update.
@param _payees Array of payees
@param _shares Array of shares for each payee
*/
function changePayees(address[] memory _payees, uint256[] memory _shares) public override onlyManager {
require(_payees.length == _shares.length, "Payees and shares mismatched");
require(_payees.length > 0, "No payees");
if (payees.length > 0 && mintableTokens() > 0) {
release();
}
for (uint256 i = 0; i < payees.length; i++) {
delete shares[payees[i]];
}
delete payees;
totalShares = 0;
for (uint256 i = 0; i < _payees.length; i++) {
_addPayee(_payees[i], _shares[i]);
}
}
/**
Get current configured payees.
@return array of current payees.
*/
function getPayees() public view override returns (address[] memory) {
return payees;
}
/**
Calculates how many MIMO tokens can be minted since the last time tokens were minted
@return number of mintable tokens available right now.
*/
function mintableTokens() public view virtual override returns (uint256);
/**
Internal function to release a percentage of newTokens to a specific payee
@dev uses totalShares to calculate correct share
@param _totalnewTokensReceived Total newTokens for all payees, will be split according to shares
@param _payee The address of the payee to whom to distribute the fees.
*/
function _release(uint256 _totalnewTokensReceived, address _payee) internal virtual;
/**
Internal function to add a new payee.
@dev will update totalShares and therefore reduce the relative share of all other payees.
@param _payee The address of the payee to add.
@param _shares The number of shares owned by the payee.
*/
function _addPayee(address _payee, uint256 _shares) internal {
require(_payee != address(0), "payee is the zero address");
require(_shares > 0, "shares are 0");
require(shares[_payee] == 0, "payee already has shares");
payees.push(_payee);
shares[_payee] = _shares;
totalShares = totalShares.add(_shares);
emit PayeeAdded(_payee, _shares);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../libraries/interfaces/IRootChainManager.sol";
import "../governance/interfaces/IGovernanceAddressProvider.sol";
import "./BaseDistributor.sol";
contract PolygonDistributor is BaseDistributor {
using SafeMath for uint256;
IRootChainManager public rootChainManager;
address public erc20Predicate;
constructor(
IGovernanceAddressProvider _a,
IRootChainManager _rootChainManager,
address _erc20Predicate
) public {
require(address(_a) != address(0));
require(address(_rootChainManager) != address(0));
require(_erc20Predicate != address(0));
a = _a;
rootChainManager = _rootChainManager;
erc20Predicate = _erc20Predicate;
}
/**
Calculates how many MIMO tokens can be minted since the last time tokens were minted
@return number of mintable tokens available right now.
*/
function mintableTokens() public view override returns (uint256) {
return a.mimo().balanceOf(address(this));
}
/**
Internal function to release a percentage of newTokens to a specific payee
@dev uses totalShares to calculate correct share
@param _totalnewTokensReceived Total newTokens for all payees, will be split according to shares
@param _payee The address of the payee to whom to distribute the fees.
*/
function _release(uint256 _totalnewTokensReceived, address _payee) internal override {
uint256 payment = _totalnewTokensReceived.mul(shares[_payee]).div(totalShares);
a.mimo().approve(erc20Predicate, payment);
rootChainManager.depositFor(_payee, address(a.mimo()), abi.encode(payment));
}
}
pragma solidity 0.6.12;
interface IRootChainManager {
event TokenMapped(address indexed rootToken, address indexed childToken, bytes32 indexed tokenType);
event PredicateRegistered(bytes32 indexed tokenType, address indexed predicateAddress);
function registerPredicate(bytes32 tokenType, address predicateAddress) external;
function mapToken(
address rootToken,
address childToken,
bytes32 tokenType
) external;
function depositEtherFor(address user) external payable;
function depositFor(
address user,
address rootToken,
bytes calldata depositData
) external;
function exit(bytes calldata inputData) external;
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "../liquidityMining/GenericMiner.sol";
import "../governance/interfaces/IGovernanceAddressProvider.sol";
contract MockGenericMiner is GenericMiner {
constructor(IGovernanceAddressProvider _addresses) public GenericMiner(_addresses) {}
function increaseStake(address user, uint256 value) public {
_increaseStake(user, value);
}
function decreaseStake(address user, uint256 value) public {
_decreaseStake(user, value);
}
}
//SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../libraries/WadRayMath.sol";
import "./interfaces/IGenericMiner.sol";
/*
GenericMiner is based on ERC2917. https://github.com/gnufoo/ERC2917-Proposal
The Objective of GenericMiner is to implement a decentralized staking mechanism, which calculates _users' share
by accumulating stake * time. And calculates _users revenue from anytime t0 to t1 by the formula below:
user_accumulated_stake(time1) - user_accumulated_stake(time0)
_____________________________________________________________________________ * (gross_stake(t1) - gross_stake(t0))
total_accumulated_stake(time1) - total_accumulated_stake(time0)
*/
contract GenericMiner is IGenericMiner {
using SafeMath for uint256;
using WadRayMath for uint256;
mapping(address => UserInfo) internal _users;
uint256 public override totalStake;
IGovernanceAddressProvider public override a;
uint256 internal _balanceTracker;
uint256 internal _accAmountPerShare;
constructor(IGovernanceAddressProvider _addresses) public {
require(address(_addresses) != address(0));
a = _addresses;
}
/**
Releases the outstanding MIMO balance to the user.
@param _user the address of the user for which the MIMO tokens will be released.
*/
function releaseMIMO(address _user) public virtual override {
UserInfo storage userInfo = _users[_user];
_refresh();
uint256 pending = userInfo.stake.rayMul(_accAmountPerShare.sub(userInfo.accAmountPerShare));
_balanceTracker = _balanceTracker.sub(pending);
userInfo.accAmountPerShare = _accAmountPerShare;
require(a.mimo().transfer(_user, pending));
}
/**
Returns the number of tokens a user has staked.
@param _user the address of the user.
@return number of staked tokens
*/
function stake(address _user) public view override returns (uint256) {
return _users[_user].stake;
}
/**
Returns the number of tokens a user can claim via `releaseMIMO`.
@param _user the address of the user.
@return number of MIMO tokens that the user can claim
*/
function pendingMIMO(address _user) public view override returns (uint256) {
uint256 currentBalance = a.mimo().balanceOf(address(this));
uint256 reward = currentBalance.sub(_balanceTracker);
uint256 accAmountPerShare = _accAmountPerShare.add(reward.rayDiv(totalStake));
return _users[_user].stake.rayMul(accAmountPerShare.sub(_users[_user].accAmountPerShare));
}
/**
Returns the userInfo stored of a user.
@param _user the address of the user.
@return `struct UserInfo {
uint256 stake;
uint256 rewardDebt;
}`
**/
function userInfo(address _user) public view override returns (UserInfo memory) {
return _users[_user];
}
/**
Refreshes the global state and subsequently decreases the stake a user has.
This is an internal call and meant to be called within derivative contracts.
@param user the address of the user
@param value the amount by which the stake will be reduced
*/
function _decreaseStake(address user, uint256 value) internal {
require(value > 0, "STAKE_MUST_BE_GREATER_THAN_ZERO"); //TODO cleanup error message
UserInfo storage userInfo = _users[user];
require(userInfo.stake >= value, "INSUFFICIENT_STAKE_FOR_USER"); //TODO cleanup error message
_refresh();
uint256 pending = userInfo.stake.rayMul(_accAmountPerShare.sub(userInfo.accAmountPerShare));
_balanceTracker = _balanceTracker.sub(pending);
userInfo.stake = userInfo.stake.sub(value);
userInfo.accAmountPerShare = _accAmountPerShare;
totalStake = totalStake.sub(value);
require(a.mimo().transfer(user, pending));
emit StakeDecreased(user, value);
}
/**
Refreshes the global state and subsequently increases a user's stake.
This is an internal call and meant to be called within derivative contracts.
@param user the address of the user
@param value the amount by which the stake will be increased
*/
function _increaseStake(address user, uint256 value) internal {
require(value > 0, "STAKE_MUST_BE_GREATER_THAN_ZERO"); //TODO cleanup error message
UserInfo storage userInfo = _users[user];
_refresh();
uint256 pending;
if (userInfo.stake > 0) {
pending = userInfo.stake.rayMul(_accAmountPerShare.sub(userInfo.accAmountPerShare));
_balanceTracker = _balanceTracker.sub(pending);
}
totalStake = totalStake.add(value);
userInfo.stake = userInfo.stake.add(value);
userInfo.accAmountPerShare = _accAmountPerShare;
if (pending > 0) {
require(a.mimo().transfer(user, pending));
}
emit StakeIncreased(user, value);
}
/**
Refreshes the global state and subsequently updates a user's stake.
This is an internal call and meant to be called within derivative contracts.
@param user the address of the user
@param stake the new amount of stake for the user
*/
function _updateStake(address user, uint256 stake) internal returns (bool) {
uint256 oldStake = _users[user].stake;
if (stake > oldStake) {
_increaseStake(user, stake.sub(oldStake));
}
if (stake < oldStake) {
_decreaseStake(user, oldStake.sub(stake));
}
}
/**
Internal read function to calculate the number of MIMO tokens that
have accumulated since the last token release.
@dev This is an internal call and meant to be called within derivative contracts.
@return newly accumulated token balance
*/
function _newTokensReceived() internal view returns (uint256) {
return a.mimo().balanceOf(address(this)).sub(_balanceTracker);
}
/**
Updates the internal state variables after accounting for newly received MIMO tokens.
*/
function _refresh() internal {
if (totalStake == 0) {
return;
}
uint256 currentBalance = a.mimo().balanceOf(address(this));
uint256 reward = currentBalance.sub(_balanceTracker);
_balanceTracker = currentBalance;
_accAmountPerShare = _accAmountPerShare.add(reward.rayDiv(totalStake));
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "./GenericMiner.sol";
import "./interfaces/IVotingMiner.sol";
import "../governance/interfaces/IGovernanceAddressProvider.sol";
import "../governance/interfaces/IVotingEscrow.sol";
contract VotingMiner is IVotingMiner, GenericMiner {
constructor(IGovernanceAddressProvider _addresses) public GenericMiner(_addresses) {}
/**
Releases the outstanding MIMO balance to the user.
@param _user the address of the user for which the MIMO tokens will be released.
*/
function releaseMIMO(address _user) public override {
IVotingEscrow votingEscrow = a.votingEscrow();
require((msg.sender == _user) || (msg.sender == address(votingEscrow)));
UserInfo storage userInfo = _users[_user];
_refresh();
uint256 pending = userInfo.stake.rayMul(_accAmountPerShare.sub(userInfo.accAmountPerShare));
_balanceTracker = _balanceTracker.sub(pending);
userInfo.accAmountPerShare = _accAmountPerShare;
uint256 votingPower = votingEscrow.balanceOf(_user);
totalStake = totalStake.add(votingPower).sub(userInfo.stake);
userInfo.stake = votingPower;
if (pending > 0) {
require(a.mimo().transfer(_user, pending));
}
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
interface IVotingMiner {}
// SPDX-License-Identifier: AGPL-3.0
/* solium-disable security/no-block-members */
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IVotingEscrow.sol";
import "./interfaces/IGovernanceAddressProvider.sol";
import "../liquidityMining/interfaces/IGenericMiner.sol";
/**
* @title VotingEscrow
* @notice Lockup GOV, receive vGOV (voting weight that decays over time)
* @dev Supports:
* 1) Tracking MIMO Locked up
* 2) Decaying voting weight lookup
* 3) Closure of contract
*/
contract VotingEscrow is IVotingEscrow, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public constant MAXTIME = 1460 days; // 365 * 4 years
uint256 public minimumLockTime = 1 days;
bool public expired = false;
IERC20 public override stakingToken;
mapping(address => LockedBalance) public locked;
string public override name;
string public override symbol;
// solhint-disable-next-line
uint256 public constant override decimals = 18;
// AddressProvider
IGovernanceAddressProvider public a;
IGenericMiner public miner;
constructor(
IERC20 _stakingToken,
IGovernanceAddressProvider _a,
IGenericMiner _miner,
string memory _name,
string memory _symbol
) public {
require(address(_stakingToken) != address(0));
require(address(_a) != address(0));
require(address(_miner) != address(0));
stakingToken = _stakingToken;
a = _a;
miner = _miner;
name = _name;
symbol = _symbol;
}
modifier onlyManager() {
require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager");
_;
}
/** @dev Modifier to ensure contract has not yet expired */
modifier contractNotExpired() {
require(!expired, "Contract is expired");
_;
}
/**
* @dev Creates a new lock
* @param _value Total units of StakingToken to lockup
* @param _unlockTime Time at which the stake should unlock
*/
function createLock(uint256 _value, uint256 _unlockTime) external override nonReentrant contractNotExpired {
LockedBalance memory locked_ = LockedBalance({ amount: locked[msg.sender].amount, end: locked[msg.sender].end });
require(_value > 0, "Must stake non zero amount");
require(locked_.amount == 0, "Withdraw old tokens first");
require(_unlockTime > block.timestamp, "Can only lock until time in the future");
require(_unlockTime.sub(block.timestamp) > minimumLockTime, "Lock duration should be larger than minimum locktime");
_depositFor(msg.sender, _value, _unlockTime, locked_, LockAction.CREATE_LOCK);
}
/**
* @dev Increases amount of stake thats locked up & resets decay
* @param _value Additional units of StakingToken to add to exiting stake
*/
function increaseLockAmount(uint256 _value) external override nonReentrant contractNotExpired {
LockedBalance memory locked_ = LockedBalance({ amount: locked[msg.sender].amount, end: locked[msg.sender].end });
require(_value > 0, "Must stake non zero amount");
require(locked_.amount > 0, "No existing lock found");
require(locked_.end > block.timestamp, "Cannot add to expired lock. Withdraw");
_depositFor(msg.sender, _value, 0, locked_, LockAction.INCREASE_LOCK_AMOUNT);
}
/**
* @dev Increases length of lockup & resets decay
* @param _unlockTime New unlocktime for lockup
*/
function increaseLockLength(uint256 _unlockTime) external override nonReentrant contractNotExpired {
LockedBalance memory locked_ = LockedBalance({ amount: locked[msg.sender].amount, end: locked[msg.sender].end });
require(locked_.amount > 0, "Nothing is locked");
require(locked_.end > block.timestamp, "Lock expired");
require(_unlockTime > locked_.end, "Can only increase lock time");
require(_unlockTime.sub(locked_.end) > minimumLockTime, "Lock duration should be larger than minimum locktime");
_depositFor(msg.sender, 0, _unlockTime, locked_, LockAction.INCREASE_LOCK_TIME);
}
/**
* @dev Withdraws all the senders stake, providing lockup is over
*/
function withdraw() external override {
_withdraw(msg.sender);
}
/**
* @dev Ends the contract, unlocking all stakes.
* No more staking can happen. Only withdraw.
*/
function expireContract() external override onlyManager contractNotExpired {
expired = true;
emit Expired();
}
/**
* @dev Set miner address.
* @param _miner new miner contract address
*/
function setMiner(IGenericMiner _miner) external override onlyManager contractNotExpired {
miner = _miner;
}
/**
* @dev Set minimumLockTime.
* @param _minimumLockTime minimum lockTime
*/
function setMinimumLockTime(uint256 _minimumLockTime) external override onlyManager contractNotExpired {
minimumLockTime = _minimumLockTime;
}
/***************************************
GETTERS
****************************************/
/**
* @dev Gets the user's votingWeight at the current time.
* @param _owner User for which to return the votingWeight
* @return uint256 Balance of user
*/
function balanceOf(address _owner) public view override returns (uint256) {
return balanceOfAt(_owner, block.timestamp);
}
/**
* @dev Gets a users votingWeight at a given block timestamp
* @param _owner User for which to return the balance
* @param _blockTime Timestamp for which to calculate balance. Can not be in the past
* @return uint256 Balance of user
*/
function balanceOfAt(address _owner, uint256 _blockTime) public view override returns (uint256) {
require(_blockTime >= block.timestamp, "Must pass block timestamp in the future");
LockedBalance memory currentLock = locked[_owner];
if (currentLock.end <= _blockTime) return 0;
uint256 remainingLocktime = currentLock.end.sub(_blockTime);
if (remainingLocktime > MAXTIME) {
remainingLocktime = MAXTIME;
}
return currentLock.amount.mul(remainingLocktime).div(MAXTIME);
}
/**
* @dev Deposits or creates a stake for a given address
* @param _addr User address to assign the stake
* @param _value Total units of StakingToken to lockup
* @param _unlockTime Time at which the stake should unlock
* @param _oldLocked Previous amount staked by this user
* @param _action See LockAction enum
*/
function _depositFor(
address _addr,
uint256 _value,
uint256 _unlockTime,
LockedBalance memory _oldLocked,
LockAction _action
) internal {
LockedBalance memory newLocked = LockedBalance({ amount: _oldLocked.amount, end: _oldLocked.end });
// Adding to existing lock, or if a lock is expired - creating a new one
newLocked.amount = newLocked.amount.add(_value);
if (_unlockTime != 0) {
newLocked.end = _unlockTime;
}
locked[_addr] = newLocked;
if (_value != 0) {
stakingToken.safeTransferFrom(_addr, address(this), _value);
}
miner.releaseMIMO(_addr);
emit Deposit(_addr, _value, newLocked.end, _action, block.timestamp);
}
/**
* @dev Withdraws a given users stake, providing the lockup has finished
* @param _addr User for which to withdraw
*/
function _withdraw(address _addr) internal nonReentrant {
LockedBalance memory oldLock = LockedBalance({ end: locked[_addr].end, amount: locked[_addr].amount });
require(block.timestamp >= oldLock.end || expired, "The lock didn't expire");
require(oldLock.amount > 0, "Must have something to withdraw");
uint256 value = uint256(oldLock.amount);
LockedBalance memory currentLock = LockedBalance({ end: 0, amount: 0 });
locked[_addr] = currentLock;
stakingToken.safeTransfer(_addr, value);
miner.releaseMIMO(_addr);
emit Withdraw(_addr, value, block.timestamp);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../libraries/WadRayMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/IMIMO.sol";
import "./interfaces/IGenericMiner.sol";
import "hardhat/console.sol";
contract PARMiner {
using SafeMath for uint256;
using WadRayMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
uint256 stake;
uint256 accAmountPerShare;
uint256 accParAmountPerShare;
}
event StakeIncreased(address indexed user, uint256 stake);
event StakeDecreased(address indexed user, uint256 stake);
IERC20 public par;
mapping(address => UserInfo) internal _users;
uint256 public totalStake;
IGovernanceAddressProvider public a;
uint256 internal _balanceTracker;
uint256 internal _accAmountPerShare;
uint256 internal _parBalanceTracker;
uint256 internal _accParAmountPerShare;
constructor(IGovernanceAddressProvider _addresses) public {
require(address(_addresses) != address(0));
a = _addresses;
par = IERC20(_addresses.parallel().stablex());
}
/**
Deposit an ERC20 pool token for staking
@dev this function uses `transferFrom()` and requires pre-approval via `approve()` on the ERC20.
@param amount the amount of tokens to be deposited. Unit is in WEI.
**/
function deposit(uint256 amount) public {
par.safeTransferFrom(msg.sender, address(this), amount);
_increaseStake(msg.sender, amount);
}
/**
Withdraw staked ERC20 pool tokens. Will fail if user does not have enough tokens staked.
@param amount the amount of tokens to be withdrawn. Unit is in WEI.
**/
function withdraw(uint256 amount) public {
par.safeTransfer(msg.sender, amount);
_decreaseStake(msg.sender, amount);
}
/**
Releases the outstanding MIMO balance to the user.
@param _user the address of the user for which the MIMO tokens will be released.
*/
function releaseMIMO(address _user) public virtual {
UserInfo storage userInfo = _users[_user];
_refresh();
_refreshPAR(totalStake);
uint256 pending = userInfo.stake.rayMul(_accAmountPerShare.sub(userInfo.accAmountPerShare));
_balanceTracker = _balanceTracker.sub(pending);
userInfo.accAmountPerShare = _accAmountPerShare;
require(a.mimo().transfer(_user, pending));
}
/**
Releases the outstanding PAR reward balance to the user.
@param _user the address of the user for which the PAR tokens will be released.
*/
function releasePAR(address _user) public virtual {
UserInfo storage userInfo = _users[_user];
_refresh();
_refreshPAR(totalStake);
uint256 pending = userInfo.stake.rayMul(_accParAmountPerShare.sub(userInfo.accParAmountPerShare));
_parBalanceTracker = _parBalanceTracker.sub(pending);
userInfo.accParAmountPerShare = _accParAmountPerShare;
require(par.transfer(_user, pending));
}
/**
Restakes the outstanding PAR reward balance to the user. Instead of sending the PAR to the user, it will be added to their stake
@param _user the address of the user for which the PAR tokens will be restaked.
*/
function restakePAR(address _user) public virtual {
UserInfo storage userInfo = _users[_user];
_refresh();
_refreshPAR(totalStake);
uint256 pending = userInfo.stake.rayMul(_accParAmountPerShare.sub(userInfo.accParAmountPerShare));
_parBalanceTracker = _parBalanceTracker.sub(pending);
userInfo.accParAmountPerShare = _accParAmountPerShare;
_increaseStake(_user, pending);
}
/**
Returns the number of tokens a user has staked.
@param _user the address of the user.
@return number of staked tokens
*/
function stake(address _user) public view returns (uint256) {
return _users[_user].stake;
}
/**
Returns the number of tokens a user can claim via `releaseMIMO`.
@param _user the address of the user.
@return number of MIMO tokens that the user can claim
*/
function pendingMIMO(address _user) public view returns (uint256) {
uint256 currentBalance = a.mimo().balanceOf(address(this));
uint256 reward = currentBalance.sub(_balanceTracker);
uint256 accAmountPerShare = _accAmountPerShare.add(reward.rayDiv(totalStake));
return _users[_user].stake.rayMul(accAmountPerShare.sub(_users[_user].accAmountPerShare));
}
/**
Returns the number of PAR tokens the user has earned as a reward
@param _user the address of the user.
@return nnumber of PAR tokens that will be sent automatically when staking/unstaking
*/
function pendingPAR(address _user) public view returns (uint256) {
uint256 currentBalance = par.balanceOf(address(this)).sub(totalStake);
uint256 reward = currentBalance.sub(_parBalanceTracker);
uint256 accParAmountPerShare = _accParAmountPerShare.add(reward.rayDiv(totalStake));
return _users[_user].stake.rayMul(accParAmountPerShare.sub(_users[_user].accParAmountPerShare));
}
/**
Returns the userInfo stored of a user.
@param _user the address of the user.
@return `struct UserInfo {
uint256 stake;
uint256 rewardDebt;
}`
**/
function userInfo(address _user) public view returns (UserInfo memory) {
return _users[_user];
}
/**
Refreshes the global state and subsequently decreases the stake a user has.
This is an internal call and meant to be called within derivative contracts.
@param user the address of the user
@param value the amount by which the stake will be reduced
*/
function _decreaseStake(address user, uint256 value) internal {
require(value > 0, "STAKE_MUST_BE_GREATER_THAN_ZERO"); //TODO cleanup error message
UserInfo storage userInfo = _users[user];
require(userInfo.stake >= value, "INSUFFICIENT_STAKE_FOR_USER"); //TODO cleanup error message
_refresh();
uint256 newTotalStake = totalStake.sub(value);
_refreshPAR(newTotalStake);
uint256 pending = userInfo.stake.rayMul(_accAmountPerShare.sub(userInfo.accAmountPerShare));
_balanceTracker = _balanceTracker.sub(pending);
userInfo.accAmountPerShare = _accAmountPerShare;
uint256 pendingPAR = userInfo.stake.rayMul(_accParAmountPerShare.sub(userInfo.accParAmountPerShare));
_parBalanceTracker = _parBalanceTracker.sub(pendingPAR);
userInfo.accParAmountPerShare = _accParAmountPerShare;
userInfo.stake = userInfo.stake.sub(value);
totalStake = newTotalStake;
if (pending > 0) {
require(a.mimo().transfer(user, pending));
}
if (pendingPAR > 0) {
require(par.transfer(user, pendingPAR));
}
emit StakeDecreased(user, value);
}
/**
Refreshes the global state and subsequently increases a user's stake.
This is an internal call and meant to be called within derivative contracts.
@param user the address of the user
@param value the amount by which the stake will be increased
*/
function _increaseStake(address user, uint256 value) internal {
require(value > 0, "STAKE_MUST_BE_GREATER_THAN_ZERO"); //TODO cleanup error message
UserInfo storage userInfo = _users[user];
_refresh();
uint256 newTotalStake = totalStake.add(value);
_refreshPAR(newTotalStake);
uint256 pending;
uint256 pendingPAR;
if (userInfo.stake > 0) {
pending = userInfo.stake.rayMul(_accAmountPerShare.sub(userInfo.accAmountPerShare));
_balanceTracker = _balanceTracker.sub(pending);
// maybe we should add the accumulated PAR to the stake of the user instead?
pendingPAR = userInfo.stake.rayMul(_accParAmountPerShare.sub(userInfo.accParAmountPerShare));
_parBalanceTracker = _parBalanceTracker.sub(pendingPAR);
}
totalStake = newTotalStake;
userInfo.stake = userInfo.stake.add(value);
userInfo.accAmountPerShare = _accAmountPerShare;
userInfo.accParAmountPerShare = _accParAmountPerShare;
if (pendingPAR > 0) {
// add pendingPAR balance to stake and totalStake instead of sending it back
userInfo.stake = userInfo.stake.add(pendingPAR);
totalStake = totalStake.add(pendingPAR);
}
if (pending > 0) {
require(a.mimo().transfer(user, pending));
}
emit StakeIncreased(user, value.add(pendingPAR));
}
/**
Refreshes the global state and subsequently updates a user's stake.
This is an internal call and meant to be called within derivative contracts.
@param user the address of the user
@param stake the new amount of stake for the user
*/
function _updateStake(address user, uint256 stake) internal returns (bool) {
uint256 oldStake = _users[user].stake;
if (stake > oldStake) {
_increaseStake(user, stake.sub(oldStake));
}
if (stake < oldStake) {
_decreaseStake(user, oldStake.sub(stake));
}
}
/**
Updates the internal state variables after accounting for newly received MIMO tokens.
*/
function _refresh() internal {
if (totalStake == 0) {
return;
}
uint256 currentBalance = a.mimo().balanceOf(address(this));
uint256 reward = currentBalance.sub(_balanceTracker);
_balanceTracker = currentBalance;
_accAmountPerShare = _accAmountPerShare.add(reward.rayDiv(totalStake));
}
/**
Updates the internal state variables after accounting for newly received PAR tokens.
*/
function _refreshPAR(uint256 newTotalStake) internal {
if (totalStake == 0) {
return;
}
uint256 currentParBalance = par.balanceOf(address(this)).sub(newTotalStake);
uint256 parReward = currentParBalance.sub(_parBalanceTracker);
_parBalanceTracker = currentParBalance;
_accParAmountPerShare = _accParAmountPerShare.add(parReward.rayDiv(totalStake));
}
}
// SPDX-License-Identifier: MIT
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));
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./GenericMiner.sol";
import "./interfaces/IMIMO.sol";
import "./interfaces/IDemandMiner.sol";
contract DemandMiner is IDemandMiner, GenericMiner {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public override token;
constructor(IGovernanceAddressProvider _addresses, IERC20 _token) public GenericMiner(_addresses) {
require(address(_token) != address(0));
require(address(_token) != address(_addresses.mimo()));
token = _token;
}
/**
Deposit an ERC20 pool token for staking
@dev this function uses `transferFrom()` and requires pre-approval via `approve()` on the ERC20.
@param amount the amount of tokens to be deposited. Unit is in WEI.
**/
function deposit(uint256 amount) public override {
token.safeTransferFrom(msg.sender, address(this), amount);
_increaseStake(msg.sender, amount);
}
/**
Withdraw staked ERC20 pool tokens. Will fail if user does not have enough tokens staked.
@param amount the amount of tokens to be withdrawn. Unit is in WEI.
**/
function withdraw(uint256 amount) public override {
token.safeTransfer(msg.sender, amount);
_decreaseStake(msg.sender, amount);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../governance/interfaces/IGovernanceAddressProvider.sol";
import "./BaseDistributor.sol";
contract EthereumDistributor is BaseDistributor {
using SafeMath for uint256;
using SafeERC20 for IERC20;
constructor(IGovernanceAddressProvider _a) public {
require(address(_a) != address(0));
a = _a;
}
/**
Calculates how many MIMO tokens can be minted since the last time tokens were minted
@return number of mintable tokens available right now.
*/
function mintableTokens() public view override returns (uint256) {
return a.mimo().balanceOf(address(this));
}
/**
Internal function to release a percentage of newTokens to a specific payee
@dev uses totalShares to calculate correct share
@param _totalnewTokensReceived Total newTokens for all payees, will be split according to shares
@param _payee The address of the payee to whom to distribute the fees.
*/
function _release(uint256 _totalnewTokensReceived, address _payee) internal override {
uint256 payment = _totalnewTokensReceived.mul(shares[_payee]).div(totalShares);
IERC20(a.mimo()).safeTransfer(_payee, payment);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "./interfaces/IGovernanceAddressProvider.sol";
import "./interfaces/IGovernorAlpha.sol";
import "./interfaces/ITimelock.sol";
import "./interfaces/IVotingEscrow.sol";
import "../interfaces/IAccessController.sol";
import "../liquidityMining/interfaces/IDebtNotifier.sol";
import "../liquidityMining/interfaces/IMIMO.sol";
contract GovernanceAddressProvider is IGovernanceAddressProvider {
IAddressProvider public override parallel;
IMIMO public override mimo;
IDebtNotifier public override debtNotifier;
IGovernorAlpha public override governorAlpha;
ITimelock public override timelock;
IVotingEscrow public override votingEscrow;
constructor(IAddressProvider _parallel) public {
require(address(_parallel) != address(0));
parallel = _parallel;
}
modifier onlyManager() {
require(controller().hasRole(controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager");
_;
}
/**
Update the `AddressProvider` address that points to main AddressProvider
used in the Parallel Protocol
@dev only manager can call this.
@param _parallel the address of the new `AddressProvider` address.
*/
function setParallelAddressProvider(IAddressProvider _parallel) public override onlyManager {
require(address(_parallel) != address(0));
parallel = _parallel;
}
/**
Update the `MIMO` ERC20 token address
@dev only manager can call this.
@param _mimo the address of the new `MIMO` token address.
*/
function setMIMO(IMIMO _mimo) public override onlyManager {
require(address(_mimo) != address(0));
mimo = _mimo;
}
/**
Update the `DebtNotifier` address
@dev only manager can call this.
@param _debtNotifier the address of the new `DebtNotifier`.
*/
function setDebtNotifier(IDebtNotifier _debtNotifier) public override onlyManager {
require(address(_debtNotifier) != address(0));
debtNotifier = _debtNotifier;
}
/**
Update the `GovernorAlpha` address
@dev only manager can call this.
@param _governorAlpha the address of the new `GovernorAlpha`.
*/
function setGovernorAlpha(IGovernorAlpha _governorAlpha) public override onlyManager {
require(address(_governorAlpha) != address(0));
governorAlpha = _governorAlpha;
}
/**
Update the `Timelock` address
@dev only manager can call this.
@param _timelock the address of the new `Timelock`.
*/
function setTimelock(ITimelock _timelock) public override onlyManager {
require(address(_timelock) != address(0));
timelock = _timelock;
}
/**
Update the `VotingEscrow` address
@dev only manager can call this.
@param _votingEscrow the address of the new `VotingEscrow`.
*/
function setVotingEscrow(IVotingEscrow _votingEscrow) public override onlyManager {
require(address(_votingEscrow) != address(0));
votingEscrow = _votingEscrow;
}
function controller() public view override returns (IAccessController) {
return parallel.controller();
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "../interfaces/IAddressProvider.sol";
import "../interfaces/IVaultsCore.sol";
import "../interfaces/IAccessController.sol";
import "../interfaces/IConfigProvider.sol";
import "../interfaces/ISTABLEX.sol";
import "../interfaces/IPriceFeed.sol";
import "../interfaces/IRatesManager.sol";
import "../interfaces/ILiquidationManager.sol";
import "../interfaces/IVaultsCore.sol";
import "../interfaces/IVaultsDataProvider.sol";
contract AddressProvider is IAddressProvider {
IAccessController public override controller;
IConfigProvider public override config;
IVaultsCore public override core;
ISTABLEX public override stablex;
IRatesManager public override ratesManager;
IPriceFeed public override priceFeed;
ILiquidationManager public override liquidationManager;
IVaultsDataProvider public override vaultsData;
IFeeDistributor public override feeDistributor;
constructor(IAccessController _controller) public {
controller = _controller;
}
modifier onlyManager() {
require(controller.hasRole(controller.MANAGER_ROLE(), msg.sender), "Caller is not a Manager");
_;
}
function setAccessController(IAccessController _controller) public override onlyManager {
require(address(_controller) != address(0));
controller = _controller;
}
function setConfigProvider(IConfigProvider _config) public override onlyManager {
require(address(_config) != address(0));
config = _config;
}
function setVaultsCore(IVaultsCore _core) public override onlyManager {
require(address(_core) != address(0));
core = _core;
}
function setStableX(ISTABLEX _stablex) public override onlyManager {
require(address(_stablex) != address(0));
stablex = _stablex;
}
function setRatesManager(IRatesManager _ratesManager) public override onlyManager {
require(address(_ratesManager) != address(0));
ratesManager = _ratesManager;
}
function setLiquidationManager(ILiquidationManager _liquidationManager) public override onlyManager {
require(address(_liquidationManager) != address(0));
liquidationManager = _liquidationManager;
}
function setPriceFeed(IPriceFeed _priceFeed) public override onlyManager {
require(address(_priceFeed) != address(0));
priceFeed = _priceFeed;
}
function setVaultsDataProvider(IVaultsDataProvider _vaultsData) public override onlyManager {
require(address(_vaultsData) != address(0));
vaultsData = _vaultsData;
}
function setFeeDistributor(IFeeDistributor _feeDistributor) public override onlyManager {
require(address(_feeDistributor) != address(0));
feeDistributor = _feeDistributor;
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "../governance/interfaces/IGovernanceAddressProvider.sol";
import "./interfaces/ISupplyMiner.sol";
import "../interfaces/IVaultsDataProvider.sol";
contract DebtNotifier is IDebtNotifier {
IGovernanceAddressProvider public override a;
mapping(address => ISupplyMiner) public override collateralSupplyMinerMapping;
constructor(IGovernanceAddressProvider _addresses) public {
require(address(_addresses) != address(0));
a = _addresses;
}
modifier onlyVaultsCore() {
require(msg.sender == address(a.parallel().core()), "Caller is not VaultsCore");
_;
}
modifier onlyManager() {
require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender));
_;
}
/**
Notifies the correct supplyMiner of a change in debt.
@dev Only the vaultsCore can call this.
`debtChanged` will silently return if collateralType is not known to prevent any problems in vaultscore.
@param _vaultId the ID of the vault of which the debt has changed.
**/
function debtChanged(uint256 _vaultId) public override onlyVaultsCore {
IVaultsDataProvider.Vault memory v = a.parallel().vaultsData().vaults(_vaultId);
ISupplyMiner supplyMiner = collateralSupplyMinerMapping[v.collateralType];
if (address(supplyMiner) == address(0)) {
// not throwing error so VaultsCore keeps working
return;
}
supplyMiner.baseDebtChanged(v.owner, v.baseDebt);
}
/**
Updates the collateral to supplyMiner mapping.
@dev Manager role in the AccessController is required to call this.
@param collateral the address of the collateralType.
@param supplyMiner the address of the supplyMiner which will be notified on debt changes for this collateralType.
**/
function setCollateralSupplyMiner(address collateral, ISupplyMiner supplyMiner) public override onlyManager {
collateralSupplyMinerMapping[collateral] = supplyMiner;
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./GenericMiner.sol";
import "./interfaces/ISupplyMiner.sol";
import "../governance/interfaces/IGovernanceAddressProvider.sol";
contract SupplyMiner is ISupplyMiner, GenericMiner {
using SafeMath for uint256;
constructor(IGovernanceAddressProvider _addresses) public GenericMiner(_addresses) {}
modifier onlyNotifier() {
require(msg.sender == address(a.debtNotifier()), "Caller is not DebtNotifier");
_;
}
/**
Gets called by the `DebtNotifier` and will update the stake of the user
to match his current outstanding debt by using his baseDebt.
@param user address of the user.
@param newBaseDebt the new baseDebt and therefore stake for the user.
*/
function baseDebtChanged(address user, uint256 newBaseDebt) public override onlyNotifier {
_updateStake(user, newBaseDebt);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/IVaultsDataProvider.sol";
import "../interfaces/IAddressProvider.sol";
contract VaultsDataProvider is IVaultsDataProvider {
using SafeMath for uint256;
IAddressProvider public override a;
uint256 public override vaultCount = 0;
mapping(address => uint256) public override baseDebt;
mapping(uint256 => Vault) private _vaults;
mapping(address => mapping(address => uint256)) private _vaultOwners;
modifier onlyVaultsCore() {
require(msg.sender == address(a.core()), "Caller is not VaultsCore");
_;
}
constructor(IAddressProvider _addresses) public {
require(address(_addresses) != address(0));
a = _addresses;
}
/**
Opens a new vault.
@dev only the vaultsCore module can call this function
@param _collateralType address to the collateral asset e.g. WETH
@param _owner the owner of the new vault.
*/
function createVault(address _collateralType, address _owner) public override onlyVaultsCore returns (uint256) {
require(_collateralType != address(0));
require(_owner != address(0));
uint256 newId = ++vaultCount;
require(_collateralType != address(0), "collateralType unknown");
Vault memory v = Vault({
collateralType: _collateralType,
owner: _owner,
collateralBalance: 0,
baseDebt: 0,
createdAt: block.timestamp
});
_vaults[newId] = v;
_vaultOwners[_owner][_collateralType] = newId;
return newId;
}
/**
Set the collateral balance of a vault.
@dev only the vaultsCore module can call this function
@param _id Vault ID of which the collateral balance will be updated
@param _balance the new balance of the vault.
*/
function setCollateralBalance(uint256 _id, uint256 _balance) public override onlyVaultsCore {
require(vaultExists(_id), "Vault not found.");
Vault storage v = _vaults[_id];
v.collateralBalance = _balance;
}
/**
Set the base debt of a vault.
@dev only the vaultsCore module can call this function
@param _id Vault ID of which the base debt will be updated
@param _newBaseDebt the new base debt of the vault.
*/
function setBaseDebt(uint256 _id, uint256 _newBaseDebt) public override onlyVaultsCore {
Vault storage _vault = _vaults[_id];
if (_newBaseDebt > _vault.baseDebt) {
uint256 increase = _newBaseDebt.sub(_vault.baseDebt);
baseDebt[_vault.collateralType] = baseDebt[_vault.collateralType].add(increase);
} else {
uint256 decrease = _vault.baseDebt.sub(_newBaseDebt);
baseDebt[_vault.collateralType] = baseDebt[_vault.collateralType].sub(decrease);
}
_vault.baseDebt = _newBaseDebt;
}
/**
Get a vault by vault ID.
@param _id The vault's ID to be retrieved
@return struct Vault {
address collateralType;
address owner;
uint256 collateralBalance;
uint256 baseDebt;
uint256 createdAt;
}
*/
function vaults(uint256 _id) public view override returns (Vault memory) {
Vault memory v = _vaults[_id];
return v;
}
/**
Get the owner of a vault.
@param _id the ID of the vault
@return owner of the vault
*/
function vaultOwner(uint256 _id) public view override returns (address) {
return _vaults[_id].owner;
}
/**
Get the collateral type of a vault.
@param _id the ID of the vault
@return address for the collateral type of the vault
*/
function vaultCollateralType(uint256 _id) public view override returns (address) {
return _vaults[_id].collateralType;
}
/**
Get the collateral balance of a vault.
@param _id the ID of the vault
@return collateral balance of the vault
*/
function vaultCollateralBalance(uint256 _id) public view override returns (uint256) {
return _vaults[_id].collateralBalance;
}
/**
Get the base debt of a vault.
@param _id the ID of the vault
@return base debt of the vault
*/
function vaultBaseDebt(uint256 _id) public view override returns (uint256) {
return _vaults[_id].baseDebt;
}
/**
Retrieve the vault id for a specified owner and collateral type.
@dev returns 0 for non-existing vaults
@param _collateralType address of the collateral type (Eg: WETH)
@param _owner address of the owner of the vault
@return vault id of the vault or 0
*/
function vaultId(address _collateralType, address _owner) public view override returns (uint256) {
return _vaultOwners[_owner][_collateralType];
}
/**
Checks if a specified vault exists.
@param _id the ID of the vault
@return boolean if the vault exists
*/
function vaultExists(uint256 _id) public view override returns (bool) {
Vault memory v = _vaults[_id];
return v.collateralType != address(0);
}
/**
Calculated the total outstanding debt for all vaults and all collateral types.
@dev uses the existing cumulative rate. Call `refresh()` on `VaultsCore`
to make sure it's up to date.
@return total debt of the platform
*/
function debt() public view override returns (uint256) {
uint256 total = 0;
for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) {
address collateralType = a.config().collateralConfigs(i).collateralType;
total = total.add(collateralDebt(collateralType));
}
return total;
}
/**
Calculated the total outstanding debt for all vaults of a specific collateral type.
@dev uses the existing cumulative rate. Call `refreshCollateral()` on `VaultsCore`
to make sure it's up to date.
@param _collateralType address of the collateral type (Eg: WETH)
@return total debt of the platform of one collateral type
*/
function collateralDebt(address _collateralType) public view override returns (uint256) {
return a.ratesManager().calculateDebt(baseDebt[_collateralType], a.core().cumulativeRates(_collateralType));
}
/**
Calculated the total outstanding debt for a specific vault.
@dev uses the existing cumulative rate. Call `refreshCollateral()` on `VaultsCore`
to make sure it's up to date.
@param _vaultId the ID of the vault
@return total debt of one vault
*/
function vaultDebt(uint256 _vaultId) public view override returns (uint256) {
IVaultsDataProvider.Vault memory v = _vaults[_vaultId];
return a.ratesManager().calculateDebt(v.baseDebt, a.core().cumulativeRates(v.collateralType));
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../libraries/WadRayMath.sol";
import "../interfaces/ILiquidationManager.sol";
import "../interfaces/IAddressProvider.sol";
contract LiquidationManager is ILiquidationManager, ReentrancyGuard {
using SafeMath for uint256;
using WadRayMath for uint256;
IAddressProvider public override a;
uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; // 1
constructor(IAddressProvider _addresses) public {
require(address(_addresses) != address(0));
a = _addresses;
}
/**
Check if the health factor is above or equal to 1.
@param _collateralValue value of the collateral in PAR
@param _vaultDebt outstanding debt to which the collateral balance shall be compared
@param _minRatio min ratio to calculate health factor
@return boolean if the health factor is >= 1.
*/
function isHealthy(
uint256 _collateralValue,
uint256 _vaultDebt,
uint256 _minRatio
) public view override returns (bool) {
uint256 healthFactor = calculateHealthFactor(_collateralValue, _vaultDebt, _minRatio);
return healthFactor >= HEALTH_FACTOR_LIQUIDATION_THRESHOLD;
}
/**
Calculate the healthfactor of a debt balance
@param _collateralValue value of the collateral in PAR currency
@param _vaultDebt outstanding debt to which the collateral balance shall be compared
@param _minRatio min ratio to calculate health factor
@return healthFactor
*/
function calculateHealthFactor(
uint256 _collateralValue,
uint256 _vaultDebt,
uint256 _minRatio
) public view override returns (uint256 healthFactor) {
if (_vaultDebt == 0) return WadRayMath.wad();
// CurrentCollateralizationRatio = value(deposited ETH) / debt
uint256 collateralizationRatio = _collateralValue.wadDiv(_vaultDebt);
// Healthfactor = CurrentCollateralizationRatio / MinimumCollateralizationRatio
if (_minRatio > 0) {
return collateralizationRatio.wadDiv(_minRatio);
}
return 1e18; // 1
}
/**
Calculate the liquidation bonus for a specified amount
@param _collateralType address of the collateral type
@param _amount amount for which the liquidation bonus shall be calculated
@return bonus the liquidation bonus to pay out
*/
function liquidationBonus(address _collateralType, uint256 _amount) public view override returns (uint256 bonus) {
return _amount.wadMul(a.config().collateralLiquidationBonus(_collateralType));
}
/**
Apply the liquidation bonus to a balance as a discount.
@param _collateralType address of the collateral type
@param _amount the balance on which to apply to liquidation bonus as a discount.
@return discountedAmount
*/
function applyLiquidationDiscount(address _collateralType, uint256 _amount)
public
view
override
returns (uint256 discountedAmount)
{
return _amount.wadDiv(a.config().collateralLiquidationBonus(_collateralType).add(WadRayMath.wad()));
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../libraries/WadRayMath.sol";
import "../interfaces/ISTABLEX.sol";
import "../interfaces/IFeeDistributor.sol";
import "../interfaces/IAddressProvider.sol";
contract FeeDistributor is IFeeDistributor, ReentrancyGuard {
using SafeMath for uint256;
event PayeeAdded(address account, uint256 shares);
event FeeReleased(uint256 income, uint256 releasedAt);
uint256 public override lastReleasedAt;
IAddressProvider public override a;
uint256 public override totalShares;
mapping(address => uint256) public override shares;
address[] public payees;
modifier onlyManager() {
require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not Manager");
_;
}
constructor(IAddressProvider _addresses) public {
require(address(_addresses) != address(0));
a = _addresses;
}
/**
Public function to release the accumulated fee income to the payees.
@dev anyone can call this.
*/
function release() public override nonReentrant {
uint256 income = a.core().state().availableIncome();
require(income > 0, "income is 0");
require(payees.length > 0, "Payees not configured yet");
lastReleasedAt = now;
// Mint USDX to all receivers
for (uint256 i = 0; i < payees.length; i++) {
address payee = payees[i];
_release(income, payee);
}
emit FeeReleased(income, lastReleasedAt);
}
/**
Updates the payee configuration to a new one.
@dev will release existing fees before the update.
@param _payees Array of payees
@param _shares Array of shares for each payee
*/
function changePayees(address[] memory _payees, uint256[] memory _shares) public override onlyManager {
require(_payees.length == _shares.length, "Payees and shares mismatched");
require(_payees.length > 0, "No payees");
uint256 income = a.core().state().availableIncome();
if (income > 0 && payees.length > 0) {
release();
}
for (uint256 i = 0; i < payees.length; i++) {
delete shares[payees[i]];
}
delete payees;
totalShares = 0;
for (uint256 i = 0; i < _payees.length; i++) {
_addPayee(_payees[i], _shares[i]);
}
}
/**
Get current configured payees.
@return array of current payees.
*/
function getPayees() public view override returns (address[] memory) {
return payees;
}
/**
Internal function to release a percentage of income to a specific payee
@dev uses totalShares to calculate correct share
@param _totalIncomeReceived Total income for all payees, will be split according to shares
@param _payee The address of the payee to whom to distribute the fees.
*/
function _release(uint256 _totalIncomeReceived, address _payee) internal {
uint256 payment = _totalIncomeReceived.mul(shares[_payee]).div(totalShares);
a.stablex().mint(_payee, payment);
}
/**
Internal function to add a new payee.
@dev will update totalShares and therefore reduce the relative share of all other payees.
@param _payee The address of the payee to add.
@param _shares The number of shares owned by the payee.
*/
function _addPayee(address _payee, uint256 _shares) internal {
require(_payee != address(0), "payee is the zero address");
require(_shares > 0, "shares are 0");
require(shares[_payee] == 0, "payee already has shares");
payees.push(_payee);
shares[_payee] = _shares;
totalShares = totalShares.add(_shares);
emit PayeeAdded(_payee, _shares);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../libraries/WadRayMath.sol";
import "../interfaces/IRatesManager.sol";
import "../interfaces/IAddressProvider.sol";
contract RatesManager is IRatesManager {
using SafeMath for uint256;
using WadRayMath for uint256;
uint256 private constant _SECONDS_PER_YEAR = 365 days;
IAddressProvider public override a;
constructor(IAddressProvider _addresses) public {
require(address(_addresses) != address(0));
a = _addresses;
}
/**
Calculate the annualized borrow rate from the specified borrowing rate.
@param _borrowRate rate for a 1 second interval specified in RAY accuracy.
@return annualized rate
*/
function annualizedBorrowRate(uint256 _borrowRate) public pure override returns (uint256) {
return _borrowRate.rayPow(_SECONDS_PER_YEAR);
}
/**
Calculate the total debt from a specified base debt and cumulative rate.
@param _baseDebt the base debt to be used. Can be a vault base debt or an aggregate base debt
@param _cumulativeRate the cumulative rate in RAY accuracy.
@return debt after applying the cumulative rate
*/
function calculateDebt(uint256 _baseDebt, uint256 _cumulativeRate) public pure override returns (uint256 debt) {
return _baseDebt.rayMul(_cumulativeRate);
}
/**
Calculate the base debt from a specified total debt and cumulative rate.
@param _debt the total debt to be used.
@param _cumulativeRate the cumulative rate in RAY accuracy.
@return baseDebt the new base debt
*/
function calculateBaseDebt(uint256 _debt, uint256 _cumulativeRate) public pure override returns (uint256 baseDebt) {
return _debt.rayDiv(_cumulativeRate);
}
/**
Bring an existing cumulative rate forward in time
@param _borrowRate rate for a 1 second interval specified in RAY accuracy to be applied
@param _timeElapsed the time over whicht the borrow rate shall be applied
@param _cumulativeRate the initial cumulative rate from which to apply the borrow rate
@return new cumulative rate
*/
function calculateCumulativeRate(
uint256 _borrowRate,
uint256 _cumulativeRate,
uint256 _timeElapsed
) public view override returns (uint256) {
if (_timeElapsed == 0) return _cumulativeRate;
uint256 cumulativeElapsed = _borrowRate.rayPow(_timeElapsed);
return _cumulativeRate.rayMul(cumulativeElapsed);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../interfaces/IPriceFeed.sol";
import "../interfaces/IAddressProvider.sol";
import "../chainlink/AggregatorV3Interface.sol";
import "../libraries/MathPow.sol";
import "../libraries/WadRayMath.sol";
contract PriceFeed is IPriceFeed {
using SafeMath for uint256;
using SafeMath for uint8;
using WadRayMath for uint256;
uint256 public constant PRICE_ORACLE_STALE_THRESHOLD = 1 days;
IAddressProvider public override a;
mapping(address => AggregatorV3Interface) public override assetOracles;
AggregatorV3Interface public override eurOracle;
constructor(IAddressProvider _addresses) public {
require(address(_addresses) != address(0));
a = _addresses;
}
modifier onlyManager() {
require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager");
_;
}
/**
* @notice Sets the oracle for the given asset,
* @param _asset address to the collateral asset e.g. WETH
* @param _oracle address to the oracel, this oracle should implement the AggregatorV3Interface
*/
function setAssetOracle(address _asset, address _oracle) public override onlyManager {
require(_asset != address(0));
require(_oracle != address(0));
assetOracles[_asset] = AggregatorV3Interface(_oracle);
emit OracleUpdated(_asset, _oracle, msg.sender);
}
/**
* @notice Sets the oracle for EUR, this oracle should provide EUR-USD prices
* @param _oracle address to the oracle, this oracle should implement the AggregatorV3Interface
*/
function setEurOracle(address _oracle) public override onlyManager {
require(_oracle != address(0));
eurOracle = AggregatorV3Interface(_oracle);
emit EurOracleUpdated(_oracle, msg.sender);
}
/**
* Gets the asset price in EUR (PAR)
* @dev returned value has matching decimals to the asset oracle (not the EUR oracle)
* @param _asset address to the collateral asset e.g. WETH
*/
function getAssetPrice(address _asset) public view override returns (uint256 price) {
(, int256 eurAnswer, , uint256 eurUpdatedAt, ) = eurOracle.latestRoundData();
require(eurAnswer > 0, "EUR price data not valid");
require(block.timestamp - eurUpdatedAt < PRICE_ORACLE_STALE_THRESHOLD, "EUR price data is stale");
(, int256 answer, , uint256 assetUpdatedAt, ) = assetOracles[_asset].latestRoundData();
require(answer > 0, "Price data not valid");
require(block.timestamp - assetUpdatedAt < PRICE_ORACLE_STALE_THRESHOLD, "Price data is stale");
uint8 eurDecimals = eurOracle.decimals();
uint256 eurAccuracy = MathPow.pow(10, eurDecimals);
return uint256(answer).mul(eurAccuracy).div(uint256(eurAnswer));
}
/**
* @notice Converts asset balance into stablecoin balance at current price
* @param _asset address to the collateral asset e.g. WETH
* @param _amount amount of collateral
*/
function convertFrom(address _asset, uint256 _amount) public view override returns (uint256) {
uint256 price = getAssetPrice(_asset);
uint8 collateralDecimals = ERC20(_asset).decimals();
uint8 parDecimals = ERC20(address(a.stablex())).decimals(); // Needs re-casting because ISTABLEX does not expose decimals()
uint8 oracleDecimals = assetOracles[_asset].decimals();
uint256 parAccuracy = MathPow.pow(10, parDecimals);
uint256 collateralAccuracy = MathPow.pow(10, oracleDecimals.add(collateralDecimals));
return _amount.mul(price).mul(parAccuracy).div(collateralAccuracy);
}
/**
* @notice Converts stablecoin balance into collateral balance at current price
* @param _asset address to the collateral asset e.g. WETH
* @param _amount amount of stablecoin
*/
function convertTo(address _asset, uint256 _amount) public view override returns (uint256) {
uint256 price = getAssetPrice(_asset);
uint8 collateralDecimals = ERC20(_asset).decimals();
uint8 parDecimals = ERC20(address(a.stablex())).decimals(); // Needs re-casting because ISTABLEX does not expose decimals()
uint8 oracleDecimals = assetOracles[_asset].decimals();
uint256 parAccuracy = MathPow.pow(10, parDecimals);
uint256 collateralAccuracy = MathPow.pow(10, oracleDecimals.add(collateralDecimals));
return _amount.mul(collateralAccuracy).div(price).div(parAccuracy);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
library MathPow {
function pow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : 1;
for (n /= 2; n != 0; n /= 2) {
x = SafeMath.mul(x, x);
if (n % 2 != 0) {
z = SafeMath.mul(z, x);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "../chainlink/AggregatorV3Interface.sol";
contract MockChainlinkFeed is AggregatorV3Interface, Ownable {
uint256 private _latestPrice;
string public override description;
uint256 public override version = 3;
uint8 public override decimals;
constructor(
uint8 _decimals,
uint256 _price,
string memory _description
) public {
decimals = _decimals;
_latestPrice = _price;
description = _description;
}
function setLatestPrice(uint256 price) public onlyOwner {
require(price > 110033500); // > 1.1 USD
require(price < 130033500); // > 1.3 USD
_latestPrice = price;
}
/**
* @notice get data about a round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* Note that different underlying implementations of AggregatorV3Interface
* have slightly different semantics for some of the return values. Consumers
* should determine what implementations they expect to receive
* data from and validate that they can properly handle return data from all
* of them.
* @param _roundId the requested round ID as presented through the proxy, this
* is made up of the aggregator's round ID with the phase ID encoded in the
* two highest order bytes
* @return roundId is the round ID from the aggregator for which the data was
* retrieved combined with an phase to ensure that round IDs get larger as
* time moves forward.
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @dev Note that answer and updatedAt may change between queries.
*/
function getRoundData(uint80 _roundId)
public
view
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
roundId = uint80(_roundId);
answer = int256(_latestPrice);
startedAt = uint256(1597422127);
updatedAt = uint256(1597695228);
answeredInRound = uint80(_roundId);
}
/**
* @notice get data about the latest round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* Note that different underlying implementations of AggregatorV3Interface
* have slightly different semantics for some of the return values. Consumers
* should determine what implementations they expect to receive
* data from and validate that they can properly handle return data from all
* of them.
* @return roundId is the round ID from the aggregator for which the data was
* retrieved combined with an phase to ensure that round IDs get larger as
* time moves forward.
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @dev Note that answer and updatedAt may change between queries.
*/
function latestRoundData()
public
view
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
uint256 latestRound = 101;
roundId = uint80(latestRound);
answer = int256(_latestPrice);
startedAt = uint256(1597422127);
updatedAt = now;
answeredInRound = uint80(latestRound);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../chainlink/AggregatorV3Interface.sol";
contract MockChainlinkAggregator is AggregatorV3Interface {
uint256 private _latestPrice;
uint256 private _updatedAt;
string public override description;
uint256 public override version = 3;
uint8 public override decimals;
constructor(
uint8 _decimals,
uint256 _price,
string memory _description
) public {
decimals = _decimals;
_latestPrice = _price;
description = _description;
}
function setLatestPrice(uint256 price) public {
_latestPrice = price;
}
function setUpdatedAt(uint256 updatedAt) public {
_updatedAt = updatedAt;
}
/**
* @notice get data about a round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* Note that different underlying implementations of AggregatorV3Interface
* have slightly different semantics for some of the return values. Consumers
* should determine what implementations they expect to receive
* data from and validate that they can properly handle return data from all
* of them.
* @param _roundId the requested round ID as presented through the proxy, this
* is made up of the aggregator's round ID with the phase ID encoded in the
* two highest order bytes
* @return roundId is the round ID from the aggregator for which the data was
* retrieved combined with an phase to ensure that round IDs get larger as
* time moves forward.
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @dev Note that answer and updatedAt may change between queries.
*/
function getRoundData(uint80 _roundId)
public
view
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
roundId = uint80(_roundId);
answer = int256(_latestPrice);
startedAt = uint256(1597422127);
updatedAt = uint256(1597695228);
answeredInRound = uint80(_roundId);
}
/**
* @notice get data about the latest round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* Note that different underlying implementations of AggregatorV3Interface
* have slightly different semantics for some of the return values. Consumers
* should determine what implementations they expect to receive
* data from and validate that they can properly handle return data from all
* of them.
* @return roundId is the round ID from the aggregator for which the data was
* retrieved combined with an phase to ensure that round IDs get larger as
* time moves forward.
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @dev Note that answer and updatedAt may change between queries.
*/
function latestRoundData()
public
view
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
uint256 latestRound = 101;
roundId = uint80(latestRound);
answer = int256(_latestPrice);
startedAt = uint256(1597422127);
updatedAt = _updatedAt;
answeredInRound = uint80(latestRound);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "../libraries/WadRayMath.sol";
import "../interfaces/IConfigProvider.sol";
import "../interfaces/IAddressProvider.sol";
contract ConfigProvider is IConfigProvider {
IAddressProvider public override a;
mapping(uint256 => CollateralConfig) private _collateralConfigs; //indexing starts at 1
mapping(address => uint256) public override collateralIds;
uint256 public override numCollateralConfigs;
/// @notice The minimum duration of voting on a proposal, in seconds
uint256 public override minVotingPeriod = 3 days;
/// @notice The max duration of voting on a proposal, in seconds
uint256 public override maxVotingPeriod = 2 weeks;
/// @notice The percentage of votes in support of a proposal required in order for a quorum to be reached and for a proposal to succeed
uint256 public override votingQuorum = 1e16; // 1%
/// @notice The percentage of votes required in order for a voter to become a proposer
uint256 public override proposalThreshold = 2e14; // 0.02%
constructor(IAddressProvider _addresses) public {
require(address(_addresses) != address(0));
a = _addresses;
}
modifier onlyManager() {
require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager");
_;
}
/**
Creates or overwrites an existing config for a collateral type
@param _collateralType address of the collateral type
@param _debtLimit the debt ceiling for the collateral type
@param _liquidationRatio the minimum ratio to maintain to avoid liquidation
@param _minCollateralRatio the minimum ratio to maintain to borrow new money or withdraw collateral
@param _borrowRate the borrowing rate specified in 1 second interval in RAY accuracy.
@param _originationFee an optional origination fee for newly created debt. Can be 0.
@param _liquidationBonus the liquidation bonus to be paid to liquidators.
@param _liquidationFee an optional fee for liquidation debt. Can be 0.
*/
function setCollateralConfig(
address _collateralType,
uint256 _debtLimit,
uint256 _liquidationRatio,
uint256 _minCollateralRatio,
uint256 _borrowRate,
uint256 _originationFee,
uint256 _liquidationBonus,
uint256 _liquidationFee
) public override onlyManager {
require(address(_collateralType) != address(0));
require(_minCollateralRatio >= _liquidationRatio);
if (collateralIds[_collateralType] == 0) {
// Initialize new collateral
a.core().state().initializeRates(_collateralType);
CollateralConfig memory config = CollateralConfig({
collateralType: _collateralType,
debtLimit: _debtLimit,
liquidationRatio: _liquidationRatio,
minCollateralRatio: _minCollateralRatio,
borrowRate: _borrowRate,
originationFee: _originationFee,
liquidationBonus: _liquidationBonus,
liquidationFee: _liquidationFee
});
numCollateralConfigs++;
_collateralConfigs[numCollateralConfigs] = config;
collateralIds[_collateralType] = numCollateralConfigs;
} else {
// Update collateral config
a.core().state().refreshCollateral(_collateralType);
uint256 id = collateralIds[_collateralType];
_collateralConfigs[id].collateralType = _collateralType;
_collateralConfigs[id].debtLimit = _debtLimit;
_collateralConfigs[id].liquidationRatio = _liquidationRatio;
_collateralConfigs[id].minCollateralRatio = _minCollateralRatio;
_collateralConfigs[id].borrowRate = _borrowRate;
_collateralConfigs[id].originationFee = _originationFee;
_collateralConfigs[id].liquidationBonus = _liquidationBonus;
_collateralConfigs[id].liquidationFee = _liquidationFee;
}
emit CollateralUpdated(
_collateralType,
_debtLimit,
_liquidationRatio,
_minCollateralRatio,
_borrowRate,
_originationFee,
_liquidationBonus,
_liquidationFee
);
}
function _emitUpdateEvent(address _collateralType) internal {
emit CollateralUpdated(
_collateralType,
_collateralConfigs[collateralIds[_collateralType]].debtLimit,
_collateralConfigs[collateralIds[_collateralType]].liquidationRatio,
_collateralConfigs[collateralIds[_collateralType]].minCollateralRatio,
_collateralConfigs[collateralIds[_collateralType]].borrowRate,
_collateralConfigs[collateralIds[_collateralType]].originationFee,
_collateralConfigs[collateralIds[_collateralType]].liquidationBonus,
_collateralConfigs[collateralIds[_collateralType]].liquidationFee
);
}
/**
Remove the config for a collateral type
@param _collateralType address of the collateral type
*/
function removeCollateral(address _collateralType) public override onlyManager {
uint256 id = collateralIds[_collateralType];
require(id != 0, "collateral does not exist");
_collateralConfigs[id] = _collateralConfigs[numCollateralConfigs]; //move last entry forward
collateralIds[_collateralConfigs[id].collateralType] = id; //update id for last entry
delete _collateralConfigs[numCollateralConfigs]; // delete last entry
delete collateralIds[_collateralType];
numCollateralConfigs--;
emit CollateralRemoved(_collateralType);
}
/**
Sets the debt limit for a collateral type
@param _collateralType address of the collateral type
@param _debtLimit the new debt limit
*/
function setCollateralDebtLimit(address _collateralType, uint256 _debtLimit) public override onlyManager {
_collateralConfigs[collateralIds[_collateralType]].debtLimit = _debtLimit;
_emitUpdateEvent(_collateralType);
}
/**
Sets the minimum liquidation ratio for a collateral type
@dev this is the liquidation treshold under which a vault is considered open for liquidation.
@param _collateralType address of the collateral type
@param _liquidationRatio the new minimum collateralization ratio
*/
function setCollateralLiquidationRatio(address _collateralType, uint256 _liquidationRatio)
public
override
onlyManager
{
require(_liquidationRatio <= _collateralConfigs[collateralIds[_collateralType]].minCollateralRatio);
_collateralConfigs[collateralIds[_collateralType]].liquidationRatio = _liquidationRatio;
_emitUpdateEvent(_collateralType);
}
/**
Sets the minimum ratio for a collateral type for new borrowing or collateral withdrawal
@param _collateralType address of the collateral type
@param _minCollateralRatio the new minimum open ratio
*/
function setCollateralMinCollateralRatio(address _collateralType, uint256 _minCollateralRatio)
public
override
onlyManager
{
require(_minCollateralRatio >= _collateralConfigs[collateralIds[_collateralType]].liquidationRatio);
_collateralConfigs[collateralIds[_collateralType]].minCollateralRatio = _minCollateralRatio;
_emitUpdateEvent(_collateralType);
}
/**
Sets the borrowing rate for a collateral type
@dev borrowing rate is specified for a 1 sec interval and accurancy is in RAY.
@param _collateralType address of the collateral type
@param _borrowRate the new borrowing rate for a 1 sec interval
*/
function setCollateralBorrowRate(address _collateralType, uint256 _borrowRate) public override onlyManager {
a.core().state().refreshCollateral(_collateralType);
_collateralConfigs[collateralIds[_collateralType]].borrowRate = _borrowRate;
_emitUpdateEvent(_collateralType);
}
/**
Sets the origiation fee for a collateral type
@dev this rate is applied as a one time fee for new borrowing and is specified in WAD
@param _collateralType address of the collateral type
@param _originationFee new origination fee in WAD
*/
function setCollateralOriginationFee(address _collateralType, uint256 _originationFee) public override onlyManager {
_collateralConfigs[collateralIds[_collateralType]].originationFee = _originationFee;
_emitUpdateEvent(_collateralType);
}
/**
Sets the liquidation bonus for a collateral type
@dev the liquidation bonus is specified in WAD
@param _collateralType address of the collateral type
@param _liquidationBonus the liquidation bonus to be paid to liquidators.
*/
function setCollateralLiquidationBonus(address _collateralType, uint256 _liquidationBonus)
public
override
onlyManager
{
_collateralConfigs[collateralIds[_collateralType]].liquidationBonus = _liquidationBonus;
_emitUpdateEvent(_collateralType);
}
/**
Sets the liquidation fee for a collateral type
@dev this rate is applied as a fee for liquidation and is specified in WAD
@param _collateralType address of the collateral type
@param _liquidationFee new liquidation fee in WAD
*/
function setCollateralLiquidationFee(address _collateralType, uint256 _liquidationFee) public override onlyManager {
require(_liquidationFee < 1e18); // fee < 100%
_collateralConfigs[collateralIds[_collateralType]].liquidationFee = _liquidationFee;
_emitUpdateEvent(_collateralType);
}
/**
Set the min voting period for a gov proposal.
@param _minVotingPeriod the min voting period for a gov proposal
*/
function setMinVotingPeriod(uint256 _minVotingPeriod) public override onlyManager {
minVotingPeriod = _minVotingPeriod;
}
/**
Set the max voting period for a gov proposal.
@param _maxVotingPeriod the max voting period for a gov proposal
*/
function setMaxVotingPeriod(uint256 _maxVotingPeriod) public override onlyManager {
maxVotingPeriod = _maxVotingPeriod;
}
/**
Set the voting quora for a gov proposal.
@param _votingQuorum the voting quora for a gov proposal
*/
function setVotingQuorum(uint256 _votingQuorum) public override onlyManager {
require(_votingQuorum < 1e18);
votingQuorum = _votingQuorum;
}
/**
Set the proposal threshold for a gov proposal.
@param _proposalThreshold the proposal threshold for a gov proposal
*/
function setProposalThreshold(uint256 _proposalThreshold) public override onlyManager {
require(_proposalThreshold < 1e18);
proposalThreshold = _proposalThreshold;
}
/**
Get the debt limit for a collateral type
@dev this is a platform wide limit for new debt issuance against a specific collateral type
@param _collateralType address of the collateral type
*/
function collateralDebtLimit(address _collateralType) public view override returns (uint256) {
return _collateralConfigs[collateralIds[_collateralType]].debtLimit;
}
/**
Get the liquidation ratio that needs to be maintained for a collateral type to avoid liquidation.
@param _collateralType address of the collateral type
*/
function collateralLiquidationRatio(address _collateralType) public view override returns (uint256) {
return _collateralConfigs[collateralIds[_collateralType]].liquidationRatio;
}
/**
Get the minimum collateralization ratio for a collateral type for new borrowing or collateral withdrawal.
@param _collateralType address of the collateral type
*/
function collateralMinCollateralRatio(address _collateralType) public view override returns (uint256) {
return _collateralConfigs[collateralIds[_collateralType]].minCollateralRatio;
}
/**
Get the borrowing rate for a collateral type
@dev borrowing rate is specified for a 1 sec interval and accurancy is in RAY.
@param _collateralType address of the collateral type
*/
function collateralBorrowRate(address _collateralType) public view override returns (uint256) {
return _collateralConfigs[collateralIds[_collateralType]].borrowRate;
}
/**
Get the origiation fee for a collateral type
@dev this rate is applied as a one time fee for new borrowing and is specified in WAD
@param _collateralType address of the collateral type
*/
function collateralOriginationFee(address _collateralType) public view override returns (uint256) {
return _collateralConfigs[collateralIds[_collateralType]].originationFee;
}
/**
Get the liquidation bonus for a collateral type
@dev this rate is applied as a one time fee for new borrowing and is specified in WAD
@param _collateralType address of the collateral type
*/
function collateralLiquidationBonus(address _collateralType) public view override returns (uint256) {
return _collateralConfigs[collateralIds[_collateralType]].liquidationBonus;
}
/**
Get the liquidation fee for a collateral type
@dev this rate is applied as a one time fee for new borrowing and is specified in WAD
@param _collateralType address of the collateral type
*/
function collateralLiquidationFee(address _collateralType) public view override returns (uint256) {
return _collateralConfigs[collateralIds[_collateralType]].liquidationFee;
}
/**
Retreives the entire config for a specific config id.
@param _id the ID of the conifg to be returned
*/
function collateralConfigs(uint256 _id) public view override returns (CollateralConfig memory) {
require(_id <= numCollateralConfigs, "Invalid config id");
return _collateralConfigs[_id];
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/ITimelock.sol";
contract Timelock is ITimelock {
using SafeMath for uint256;
uint256 public constant MINIMUM_DELAY = 2 days;
uint256 public constant MAXIMUM_DELAY = 30 days;
uint256 public constant override GRACE_PERIOD = 14 days;
address public admin;
address public pendingAdmin;
uint256 public override delay;
mapping(bytes32 => bool) public override queuedTransactions;
constructor(address _admin, uint256 _delay) public {
require(address(_admin) != address(0));
require(_delay >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay.");
require(_delay <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
admin = _admin;
delay = _delay;
}
receive() external payable {}
fallback() external payable {}
function setDelay(uint256 _delay) public {
require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock.");
require(_delay >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay.");
require(_delay <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
delay = _delay;
emit NewDelay(delay);
}
function acceptAdmin() public override {
require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin.");
admin = msg.sender;
pendingAdmin = address(0);
emit NewAdmin(admin);
}
function setPendingAdmin(address _pendingAdmin) public {
require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock.");
pendingAdmin = _pendingAdmin;
emit NewPendingAdmin(pendingAdmin);
}
function queueTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) public override returns (bytes32) {
require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin.");
require(
eta >= block.timestamp.add(delay),
"Timelock::queueTransaction: Estimated execution block must satisfy delay."
);
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = true;
emit QueueTransaction(txHash, target, value, signature, data, eta);
return txHash;
}
function cancelTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) public override {
require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = false;
emit CancelTransaction(txHash, target, value, signature, data, eta);
}
function executeTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) public payable override returns (bytes memory) {
require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued.");
require(block.timestamp >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock.");
require(block.timestamp <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale.");
queuedTransactions[txHash] = false;
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call{ value: value }(callData);
require(success, "Timelock::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(txHash, target, value, signature, data, eta);
return returnData;
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.6.12;
import '../Timelock.sol';
// Test timelock contract with admin helpers
contract TestTimelock is Timelock {
constructor(address admin_, uint256 delay_) public Timelock(admin_, 2 days) {
delay = delay_;
}
function harnessSetPendingAdmin(address pendingAdmin_) public {
pendingAdmin = pendingAdmin_;
}
function harnessSetAdmin(address admin_) public {
admin = admin_;
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IGovernorAlpha.sol";
import "./interfaces/IGovernanceAddressProvider.sol";
import "../libraries/WadRayMath.sol";
contract GovernorAlpha is IGovernorAlpha {
using SafeMath for uint256;
using WadRayMath for uint256;
/// @notice The maximum number of actions that can be included in a proposal
function proposalMaxOperations() public pure returns (uint256) {
return 10;
} // 10 actions
IGovernanceAddressProvider public a;
/// @notice The address of the Governor Guardian
address public guardian;
/// @notice The total number of proposals
uint256 public proposalCount;
/// @notice The official record of all proposals ever proposed
mapping(uint256 => Proposal) public proposals;
/// @notice The latest proposal for each proposer
mapping(address => uint256) public latestProposalIds;
constructor(IGovernanceAddressProvider _addresses, address _guardian) public {
require(address(_addresses) != address(0));
require(address(_guardian) != address(0));
a = _addresses;
guardian = _guardian;
}
function propose(
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
string memory description,
uint256 endTime
) public override returns (uint256) {
uint256 votingDuration = endTime.sub(block.timestamp);
require(votingDuration >= a.parallel().config().minVotingPeriod(), "Proposal end-time too early");
require(votingDuration <= a.parallel().config().maxVotingPeriod(), "Proposal end-time too late");
require(
a.votingEscrow().balanceOfAt(msg.sender, endTime) > proposalThreshold(),
"GovernorAlpha::propose: proposer votes below proposal threshold"
);
require(
targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length,
"GovernorAlpha::propose: proposal function information arity mismatch"
);
require(targets.length != 0, "GovernorAlpha::propose: must provide actions");
require(targets.length <= proposalMaxOperations(), "GovernorAlpha::propose: too many actions");
uint256 latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(
proposersLatestProposalState != ProposalState.Active,
"GovernorAlpha::propose: one live proposal per proposer, found an already active proposal"
);
}
proposalCount++;
Proposal memory newProposal = Proposal({
id: proposalCount,
proposer: msg.sender,
eta: 0,
targets: targets,
values: values,
signatures: signatures,
calldatas: calldatas,
startTime: block.timestamp,
endTime: endTime,
forVotes: 0,
againstVotes: 0,
canceled: false,
executed: false
});
proposals[newProposal.id] = newProposal;
latestProposalIds[newProposal.proposer] = newProposal.id;
emit ProposalCreated(
newProposal.id,
msg.sender,
targets,
values,
signatures,
calldatas,
block.timestamp,
endTime,
description
);
return newProposal.id;
}
function queue(uint256 proposalId) public override {
require(
state(proposalId) == ProposalState.Succeeded,
"GovernorAlpha::queue: proposal can only be queued if it is succeeded"
);
Proposal storage proposal = proposals[proposalId];
uint256 eta = block.timestamp.add(a.timelock().delay());
for (uint256 i = 0; i < proposal.targets.length; i++) {
_queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
function execute(uint256 proposalId) public payable override {
require(
state(proposalId) == ProposalState.Queued,
"GovernorAlpha::execute: proposal can only be executed if it is queued"
);
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint256 i = 0; i < proposal.targets.length; i++) {
a.timelock().executeTransaction{ value: proposal.values[i] }(
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
proposal.eta
);
}
emit ProposalExecuted(proposalId);
}
function cancel(uint256 proposalId) public override {
ProposalState state = state(proposalId);
require(state != ProposalState.Executed, "GovernorAlpha::cancel: cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
require(msg.sender == guardian, "Only Guardian can cancel");
proposal.canceled = true;
for (uint256 i = 0; i < proposal.targets.length; i++) {
a.timelock().cancelTransaction(
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
proposal.eta
);
}
emit ProposalCanceled(proposalId);
}
function castVote(uint256 proposalId, bool support) public override {
require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed");
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[msg.sender];
require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted");
uint256 votes = a.votingEscrow().balanceOfAt(msg.sender, proposal.endTime);
if (support) {
proposal.forVotes = proposal.forVotes.add(votes);
} else {
proposal.againstVotes = proposal.againstVotes.add(votes);
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
emit VoteCast(msg.sender, proposalId, support, votes);
}
// solhint-disable-next-line private-vars-leading-underscore
function __acceptAdmin() public {
require(msg.sender == guardian, "GovernorAlpha::__acceptAdmin: sender must be gov guardian");
a.timelock().acceptAdmin();
}
// solhint-disable-next-line private-vars-leading-underscore
function __abdicate() public {
require(msg.sender == guardian, "GovernorAlpha::__abdicate: sender must be gov guardian");
guardian = address(0);
}
// solhint-disable-next-line private-vars-leading-underscore
function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint256 eta) public {
require(msg.sender == guardian, "GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian");
a.timelock().queueTransaction(
address(a.timelock()),
0,
"setPendingAdmin(address)",
abi.encode(newPendingAdmin),
eta
);
}
// solhint-disable-next-line private-vars-leading-underscore
function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint256 eta) public {
require(msg.sender == guardian, "GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian");
a.timelock().executeTransaction(
address(a.timelock()),
0,
"setPendingAdmin(address)",
abi.encode(newPendingAdmin),
eta
);
}
/// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed
function quorumVotes() public view override returns (uint256) {
return a.votingEscrow().stakingToken().totalSupply().wadMul(a.parallel().config().votingQuorum());
}
/// @notice The number of votes required in order for a voter to become a proposer
function proposalThreshold() public view override returns (uint256) {
return a.votingEscrow().stakingToken().totalSupply().wadMul(a.parallel().config().proposalThreshold());
}
function getActions(uint256 proposalId)
public
view
override
returns (
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas
)
{
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
function getReceipt(uint256 proposalId, address voter) public view override returns (Receipt memory) {
return proposals[proposalId].receipts[voter];
}
function state(uint256 proposalId) public view override returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha::state: invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.timestamp <= proposal.endTime) {
return ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes()) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= a.timelock().GRACE_PERIOD().add(proposal.endTime)) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
function _queueOrRevert(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) internal {
require(
!a.timelock().queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))),
"GovernorAlpha::_queueOrRevert: proposal action already queued at eta"
);
a.timelock().queueTransaction(target, value, signature, data, eta);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../libraries/WadRayMath.sol";
import "../governance/interfaces/IGovernanceAddressProvider.sol";
import "./interfaces/IMIMODistributor.sol";
import "./BaseDistributor.sol";
/*
Distribution Formula:
55.5m MIMO in first week
-5.55% redution per week
total(timestamp) = _SECONDS_PER_WEEK * ( (1-_WEEKLY_R^(timestamp/_SECONDS_PER_WEEK)) / (1-_WEEKLY_R) )
+ timestamp % _SECONDS_PER_WEEK * (1-_WEEKLY_R^(timestamp/_SECONDS_PER_WEEK)
*/
contract MIMODistributor is BaseDistributor, IMIMODistributorExtension {
using SafeMath for uint256;
using WadRayMath for uint256;
uint256 private constant _SECONDS_PER_YEAR = 365 days;
uint256 private constant _SECONDS_PER_WEEK = 7 days;
uint256 private constant _WEEKLY_R = 9445e23; //-5.55%
uint256 private constant _FIRST_WEEK_TOKENS = 55500000 ether; //55.5m
uint256 public override startTime;
constructor(IGovernanceAddressProvider _a, uint256 _startTime) public {
require(address(_a) != address(0));
a = _a;
startTime = _startTime;
}
/**
Get current monthly issuance of new MIMO tokens.
@return number of monthly issued tokens currently`.
*/
function currentIssuance() public view override returns (uint256) {
return weeklyIssuanceAt(now);
}
/**
Get monthly issuance of new MIMO tokens at `timestamp`.
@dev invalid for timestamps before deployment
@param timestamp for which to calculate the monthly issuance
@return number of monthly issued tokens at `timestamp`.
*/
function weeklyIssuanceAt(uint256 timestamp) public view override returns (uint256) {
uint256 elapsedSeconds = timestamp.sub(startTime);
uint256 elapsedWeeks = elapsedSeconds.div(_SECONDS_PER_WEEK);
return _WEEKLY_R.rayPow(elapsedWeeks).rayMul(_FIRST_WEEK_TOKENS);
}
/**
Calculates how many MIMO tokens can be minted since the last time tokens were minted
@return number of mintable tokens available right now.
*/
function mintableTokens() public view override returns (uint256) {
return totalSupplyAt(now).sub(a.mimo().totalSupply());
}
/**
Calculates the totalSupply for any point after `startTime`
@param timestamp for which to calculate the totalSupply
@return totalSupply at timestamp.
*/
function totalSupplyAt(uint256 timestamp) public view override returns (uint256) {
uint256 elapsedSeconds = timestamp.sub(startTime);
uint256 elapsedWeeks = elapsedSeconds.div(_SECONDS_PER_WEEK);
uint256 lastWeekSeconds = elapsedSeconds % _SECONDS_PER_WEEK;
uint256 one = WadRayMath.ray();
uint256 fullWeeks = one.sub(_WEEKLY_R.rayPow(elapsedWeeks)).rayMul(_FIRST_WEEK_TOKENS).rayDiv(one.sub(_WEEKLY_R));
uint256 currentWeekIssuance = weeklyIssuanceAt(timestamp);
uint256 partialWeek = currentWeekIssuance.mul(lastWeekSeconds).div(_SECONDS_PER_WEEK);
return fullWeeks.add(partialWeek);
}
/**
Internal function to release a percentage of newTokens to a specific payee
@dev uses totalShares to calculate correct share
@param _totalnewTokensReceived Total newTokens for all payees, will be split according to shares
@param _payee The address of the payee to whom to distribute the fees.
*/
function _release(uint256 _totalnewTokensReceived, address _payee) internal override {
uint256 payment = _totalnewTokensReceived.mul(shares[_payee]).div(totalShares);
a.mimo().mint(_payee, payment);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../governance/interfaces/IGovernanceAddressProvider.sol";
import "./interfaces/IBaseDistributor.sol";
contract DistributorManager {
using SafeMath for uint256;
IGovernanceAddressProvider public a;
IBaseDistributor public mimmoDistributor;
modifier onlyManager() {
require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not Manager");
_;
}
constructor(IGovernanceAddressProvider _a, IBaseDistributor _mimmoDistributor) public {
require(address(_a) != address(0));
require(address(_mimmoDistributor) != address(0));
a = _a;
mimmoDistributor = _mimmoDistributor;
}
/**
Public function to release the accumulated new MIMO tokens to the payees.
@dev anyone can call this.
*/
function releaseAll() public {
mimmoDistributor.release();
address[] memory distributors = mimmoDistributor.getPayees();
for (uint256 i = 0; i < distributors.length; i++) {
IBaseDistributor(distributors[i]).release();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract MockWETH is ERC20("Wrapped Ether", "WETH") {
function mint(address account, uint256 amount) public {
_mint(account, amount);
}
function deposit() public payable {
_mint(msg.sender, msg.value);
}
function withdraw(uint256 wad) public {
_burn(msg.sender, wad);
msg.sender.transfer(wad);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract MockWBTC is ERC20("Wrapped Bitcoin", "WBTC") {
function mint(address account, uint256 amount) public {
_mint(account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract MockMIMO is ERC20("MIMO Token", "MIMO") {
function mint(address account, uint256 amount) public {
_mint(account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract MockERC20 is ERC20 {
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) public ERC20(_name, _symbol) {
super._setupDecimals(_decimals);
}
function mint(address account, uint256 amount) public {
_mint(account, amount);
}
function burn(address account, uint256 amount) public {
_burn(account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract MockBPT is ERC20("Balancer Pool Token", "BPT") {
function mint(address account, uint256 amount) public {
_mint(account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/IAddressProvider.sol";
import "../libraries/interfaces/IVault.sol";
contract MIMOBuyback {
bytes32 public constant KEEPER_ROLE = keccak256("KEEPER_ROLE");
IAddressProvider public a;
IERC20 public PAR;
IERC20 public MIMO;
uint256 public lockExpiry;
bytes32 public poolID;
IVault public balancer = IVault(0xBA12222222228d8Ba445958a75a0704d566BF2C8);
bool public whitelistEnabled = false;
constructor(
uint256 _lockExpiry,
bytes32 _poolID,
address _a,
address _mimo
) public {
lockExpiry = _lockExpiry;
poolID = _poolID;
a = IAddressProvider(_a);
MIMO = IERC20(_mimo);
PAR = a.stablex();
PAR.approve(address(balancer), 2**256 - 1);
}
modifier onlyManager() {
require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager");
_;
}
modifier onlyKeeper() {
require(
!whitelistEnabled || (whitelistEnabled && a.controller().hasRole(KEEPER_ROLE, msg.sender)),
"Caller is not a Keeper"
);
_;
}
function withdrawMIMO(address destination) public onlyManager {
require(block.timestamp > lockExpiry, "lock not expired yet");
require(MIMO.transfer(destination, MIMO.balanceOf(address(this))));
}
function buyMIMO() public onlyKeeper {
a.core().state().refresh();
a.feeDistributor().release();
bytes memory userData = abi.encode();
IVault.SingleSwap memory singleSwap = IVault.SingleSwap(
poolID,
IVault.SwapKind.GIVEN_IN,
IAsset(address(PAR)), // swap in
IAsset(address(MIMO)), // swap out
PAR.balanceOf(address(this)), // all PAR of this contract
userData
);
IVault.FundManagement memory fundManagement = IVault.FundManagement(
address(this), // sender
false, // useInternalBalance
payable(address(this)), // recipient
false // // useInternalBalance
);
balancer.swap(
singleSwap,
fundManagement,
0, // limit, could be frontrun?
2**256 - 1 // deadline
);
}
function setWhitelistEnabled(bool _status) public onlyManager {
whitelistEnabled = _status;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IAsset {
// solhint-disable-previous-line no-empty-blocks
}
interface IVault {
enum SwapKind { GIVEN_IN, GIVEN_OUT }
/**
* @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
* the `kind` value.
*
* `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
* Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct SingleSwap {
bytes32 poolId;
SwapKind kind;
IAsset assetIn;
IAsset assetOut;
uint256 amount;
bytes userData;
}
/**
* @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
* `recipient` account.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
* transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
* must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
* `joinPool`.
*
* If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
* transferred. This matches the behavior of `exitPool`.
*
* Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
* revert.
*/
struct FundManagement {
address sender;
bool fromInternalBalance;
address payable recipient;
bool toInternalBalance;
}
/**
* @dev Performs a swap with a single Pool.
*
* If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens
* taken from the Pool, which must be greater than or equal to `limit`.
*
* If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens
* sent to the Pool, which must be less than or equal to `limit`.
*
* Internal Balance usage and the recipient are determined by the `funds` struct.
*
* Emits a `Swap` event.
*/
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external payable returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
/**
Buggy ERC20 implementation without the return bool on `transfer`, `transferFrom` and `approve` for testing purposes
*/
contract MockBuggyERC20 is Context {
using SafeMath for uint256;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
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 returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual {
_transfer(_msgSender(), recipient, amount);
}
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual {
_approve(_msgSender(), spender, amount);
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")
);
}
function mint(address account, uint256 amount) public {
_mint(account, amount);
}
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 _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface BPool is IERC20 {
function gulp(address token) external;
function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external;
function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external;
function swapExactAmountIn(
address tokenIn,
uint256 tokenAmountIn,
address tokenOut,
uint256 minAmountOut,
uint256 maxPrice
) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter);
function swapExactAmountOut(
address tokenIn,
uint256 maxAmountIn,
address tokenOut,
uint256 tokenAmountOut,
uint256 maxPrice
) external returns (uint256 tokenAmountIn, uint256 spotPriceAfter);
function joinswapExternAmountIn(
address tokenIn,
uint256 tokenAmountIn,
uint256 minPoolAmountOut
) external returns (uint256 poolAmountOut);
function joinswapPoolAmountOut(
address tokenIn,
uint256 poolAmountOut,
uint256 maxAmountIn
) external returns (uint256 tokenAmountIn);
function exitswapPoolAmountIn(
address tokenOut,
uint256 poolAmountIn,
uint256 minAmountOut
) external returns (uint256 tokenAmountOut);
function exitswapExternAmountOut(
address tokenOut,
uint256 tokenAmountOut,
uint256 maxPoolAmountIn
) external returns (uint256 poolAmountIn);
function calcPoolOutGivenSingleIn(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 poolSupply,
uint256 totalWeight,
uint256 tokenAmountIn,
uint256 swapFee
) external pure returns (uint256 poolAmountOut);
function getSpotPrice(address tokenIn, address tokenOut) external view returns (uint256 spotPrice);
function getSpotPriceSansFee(address tokenIn, address tokenOut) external view returns (uint256 spotPrice);
function getSwapFee() external view returns (uint256);
function getBalance(address token) external view returns (uint256);
function getDenormalizedWeight(address token) external view returns (uint256);
function getTotalDenormalizedWeight() external view returns (uint256);
function getNormalizedWeight(address token) external view returns (uint256);
function isPublicSwap() external view returns (bool);
function isFinalized() external view returns (bool);
}
| * @dev Set minimumLockTime. @param _minimumLockTime minimum lockTime/ | function setMinimumLockTime(uint256 _minimumLockTime) external override onlyManager contractNotExpired {
minimumLockTime = _minimumLockTime;
}
| 12,889,539 | [
1,
694,
5224,
2531,
950,
18,
225,
389,
15903,
2531,
950,
5224,
2176,
950,
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,
225,
445,
31973,
2531,
950,
12,
11890,
5034,
389,
15903,
2531,
950,
13,
3903,
3849,
1338,
1318,
6835,
1248,
10556,
288,
203,
565,
5224,
2531,
950,
273,
389,
15903,
2531,
950,
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
]
|
/**
*Submitted for verification at Etherscan.io on 2022-03-08
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.4;
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
);
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
_transferOwnership(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, 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 BakiInu is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "BakiInu";
string private constant _symbol = "BAKIINU";
uint8 private constant _decimals = 9;
mapping (address => uint256) _balances;
mapping(address => uint256) _lastTX;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 _totalSupply = 1000000000000 * 10**9;
//Buy Fee
uint256 private _taxFeeOnBuy = 8;
//Sell Fee
uint256 private _taxFeeOnSell = 12;
//Original Fee
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
address payable private _marketingAddress = payable(0x83397AFD9bb81f96045790b4b833ef6E8C430e6F);
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen = false;
bool private inSwap = false;
bool private swapEnabled = true;
bool private transferDelay = true;
uint256 public _maxTxAmount = 7500000000 * 10**9;
uint256 public _maxWalletSize = 15000000000 * 10**9;
uint256 public _swapTokensAtAmount = 500000000 * 10**9;
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor() {
_balances[_msgSender()] = _totalSupply;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_marketingAddress] = true;
_isExcludedFromFee[_marketingAddress] = true; //multisig
emit Transfer(address(0), _msgSender(), _totalSupply);
}
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 view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount)
public
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 _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 (!_isExcludedFromFee[to] && !_isExcludedFromFee[from]) {
require(tradingOpen, "TOKEN: Trading not yet started");
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
if(from == uniswapV2Pair && transferDelay){
require(_lastTX[tx.origin] + 3 minutes < block.timestamp && _lastTX[to] + 3 minutes < block.timestamp, "TOKEN: 3 minutes cooldown between buys");
}
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _swapTokensAtAmount)
{
contractTokenBalance = _swapTokensAtAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance); // Reserve of 15% of tokens for liquidity
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0 ether) {
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)) {
_taxFee = _taxFeeOnBuy;
}
//Set Fee for Sells
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_taxFee = _taxFeeOnSell;
}
}
_lastTX[tx.origin] = block.timestamp;
_lastTX[to] = block.timestamp;
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
uint256 ethAmt = tokenAmount.mul(85).div(100);
uint256 liqAmt = tokenAmount - ethAmt;
uint256 balanceBefore = address(this).balance;
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
ethAmt,
0,
path,
address(this),
block.timestamp
);
uint256 amountETH = address(this).balance.sub(balanceBefore);
addLiquidity(liqAmt, amountETH.mul(15).div(100));
}
function sendETHToFee(uint256 amount) private {
_marketingAddress.transfer(amount);
}
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(0),
block.timestamp
);
}
function setTrading(bool _tradingOpen) public onlyOwner {
tradingOpen = _tradingOpen;
}
function manualswap() external onlyOwner {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
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) {_transferNoTax(sender,recipient, amount);}
else {_transferStandard(sender, recipient, amount);}
}
function airdrop(address[] calldata recipients, uint256[] calldata amount) public onlyOwner{
for (uint256 i = 0; i < recipients.length; i++) {
_transferNoTax(msg.sender,recipients[i], amount[i]);
}
}
function _transferStandard(
address sender,
address recipient,
uint256 amount
) private {
uint256 amountReceived = takeFees(sender, amount);
_balances[sender] = _balances[sender].sub(amount, "Insufficient Balance");
_balances[recipient] = _balances[recipient].add(amountReceived);
emit Transfer(sender, recipient, amountReceived);
}
function _transferNoTax(address sender, address recipient, uint256 amount) internal returns (bool) {
_balances[sender] = _balances[sender].sub(amount, "Insufficient Balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
return true;
}
function takeFees(address sender,uint256 amount) internal returns (uint256) {
uint256 feeAmount = amount.mul(_taxFee).div(100);
_balances[address(this)] = _balances[address(this)].add(feeAmount);
emit Transfer(sender, address(this), feeAmount);
return amount.sub(feeAmount);
}
receive() external payable {}
function transferOwnership(address newOwner) public override onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_isExcludedFromFee[owner()] = false;
_transferOwnership(newOwner);
_isExcludedFromFee[owner()] = true;
}
function setFees(uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
_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 setIsFeeExempt(address holder, bool exempt) public onlyOwner {
_isExcludedFromFee[holder] = exempt;
}
function toggleTransferDelay() public onlyOwner {
transferDelay = !transferDelay;
}
} | Buy FeeSell FeeOriginal Fee | contract BakiInu is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "BakiInu";
string private constant _symbol = "BAKIINU";
uint8 private constant _decimals = 9;
mapping (address => uint256) _balances;
mapping(address => uint256) _lastTX;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 _totalSupply = 1000000000000 * 10**9;
uint256 private _taxFeeOnBuy = 8;
uint256 private _taxFeeOnSell = 12;
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
address payable private _marketingAddress = payable(0x83397AFD9bb81f96045790b4b833ef6E8C430e6F);
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen = false;
bool private inSwap = false;
bool private swapEnabled = true;
bool private transferDelay = true;
uint256 public _maxTxAmount = 7500000000 * 10**9;
uint256 public _maxWalletSize = 15000000000 * 10**9;
uint256 public _swapTokensAtAmount = 500000000 * 10**9;
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor() {
_balances[_msgSender()] = _totalSupply;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_marketingAddress] = true;
emit Transfer(address(0), _msgSender(), _totalSupply);
}
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 view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount)
public
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 _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 (!_isExcludedFromFee[to] && !_isExcludedFromFee[from]) {
require(tradingOpen, "TOKEN: Trading not yet started");
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
if(from == uniswapV2Pair && transferDelay){
require(_lastTX[tx.origin] + 3 minutes < block.timestamp && _lastTX[to] + 3 minutes < block.timestamp, "TOKEN: 3 minutes cooldown between buys");
}
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _swapTokensAtAmount)
{
contractTokenBalance = _swapTokensAtAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0 ether) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_taxFee = _taxFeeOnSell;
}
}
_lastTX[tx.origin] = block.timestamp;
_lastTX[to] = block.timestamp;
_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 (!_isExcludedFromFee[to] && !_isExcludedFromFee[from]) {
require(tradingOpen, "TOKEN: Trading not yet started");
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
if(from == uniswapV2Pair && transferDelay){
require(_lastTX[tx.origin] + 3 minutes < block.timestamp && _lastTX[to] + 3 minutes < block.timestamp, "TOKEN: 3 minutes cooldown between buys");
}
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _swapTokensAtAmount)
{
contractTokenBalance = _swapTokensAtAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0 ether) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_taxFee = _taxFeeOnSell;
}
}
_lastTX[tx.origin] = block.timestamp;
_lastTX[to] = block.timestamp;
_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 (!_isExcludedFromFee[to] && !_isExcludedFromFee[from]) {
require(tradingOpen, "TOKEN: Trading not yet started");
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
if(from == uniswapV2Pair && transferDelay){
require(_lastTX[tx.origin] + 3 minutes < block.timestamp && _lastTX[to] + 3 minutes < block.timestamp, "TOKEN: 3 minutes cooldown between buys");
}
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _swapTokensAtAmount)
{
contractTokenBalance = _swapTokensAtAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0 ether) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_taxFee = _taxFeeOnSell;
}
}
_lastTX[tx.origin] = block.timestamp;
_lastTX[to] = block.timestamp;
_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 (!_isExcludedFromFee[to] && !_isExcludedFromFee[from]) {
require(tradingOpen, "TOKEN: Trading not yet started");
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
if(from == uniswapV2Pair && transferDelay){
require(_lastTX[tx.origin] + 3 minutes < block.timestamp && _lastTX[to] + 3 minutes < block.timestamp, "TOKEN: 3 minutes cooldown between buys");
}
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _swapTokensAtAmount)
{
contractTokenBalance = _swapTokensAtAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0 ether) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_taxFee = _taxFeeOnSell;
}
}
_lastTX[tx.origin] = block.timestamp;
_lastTX[to] = block.timestamp;
_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 (!_isExcludedFromFee[to] && !_isExcludedFromFee[from]) {
require(tradingOpen, "TOKEN: Trading not yet started");
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
if(from == uniswapV2Pair && transferDelay){
require(_lastTX[tx.origin] + 3 minutes < block.timestamp && _lastTX[to] + 3 minutes < block.timestamp, "TOKEN: 3 minutes cooldown between buys");
}
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _swapTokensAtAmount)
{
contractTokenBalance = _swapTokensAtAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0 ether) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_taxFee = _taxFeeOnSell;
}
}
_lastTX[tx.origin] = block.timestamp;
_lastTX[to] = block.timestamp;
_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 (!_isExcludedFromFee[to] && !_isExcludedFromFee[from]) {
require(tradingOpen, "TOKEN: Trading not yet started");
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
if(from == uniswapV2Pair && transferDelay){
require(_lastTX[tx.origin] + 3 minutes < block.timestamp && _lastTX[to] + 3 minutes < block.timestamp, "TOKEN: 3 minutes cooldown between buys");
}
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _swapTokensAtAmount)
{
contractTokenBalance = _swapTokensAtAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0 ether) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_taxFee = _taxFeeOnSell;
}
}
_lastTX[tx.origin] = block.timestamp;
_lastTX[to] = block.timestamp;
_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 (!_isExcludedFromFee[to] && !_isExcludedFromFee[from]) {
require(tradingOpen, "TOKEN: Trading not yet started");
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
if(from == uniswapV2Pair && transferDelay){
require(_lastTX[tx.origin] + 3 minutes < block.timestamp && _lastTX[to] + 3 minutes < block.timestamp, "TOKEN: 3 minutes cooldown between buys");
}
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _swapTokensAtAmount)
{
contractTokenBalance = _swapTokensAtAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0 ether) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_taxFee = _taxFeeOnSell;
}
}
_lastTX[tx.origin] = block.timestamp;
_lastTX[to] = block.timestamp;
_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 (!_isExcludedFromFee[to] && !_isExcludedFromFee[from]) {
require(tradingOpen, "TOKEN: Trading not yet started");
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
if(from == uniswapV2Pair && transferDelay){
require(_lastTX[tx.origin] + 3 minutes < block.timestamp && _lastTX[to] + 3 minutes < block.timestamp, "TOKEN: 3 minutes cooldown between buys");
}
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _swapTokensAtAmount)
{
contractTokenBalance = _swapTokensAtAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0 ether) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_taxFee = _taxFeeOnSell;
}
}
_lastTX[tx.origin] = block.timestamp;
_lastTX[to] = block.timestamp;
_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 (!_isExcludedFromFee[to] && !_isExcludedFromFee[from]) {
require(tradingOpen, "TOKEN: Trading not yet started");
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
if(from == uniswapV2Pair && transferDelay){
require(_lastTX[tx.origin] + 3 minutes < block.timestamp && _lastTX[to] + 3 minutes < block.timestamp, "TOKEN: 3 minutes cooldown between buys");
}
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _swapTokensAtAmount)
{
contractTokenBalance = _swapTokensAtAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0 ether) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_taxFee = _taxFeeOnSell;
}
}
_lastTX[tx.origin] = block.timestamp;
_lastTX[to] = block.timestamp;
_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 (!_isExcludedFromFee[to] && !_isExcludedFromFee[from]) {
require(tradingOpen, "TOKEN: Trading not yet started");
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
if(from == uniswapV2Pair && transferDelay){
require(_lastTX[tx.origin] + 3 minutes < block.timestamp && _lastTX[to] + 3 minutes < block.timestamp, "TOKEN: 3 minutes cooldown between buys");
}
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _swapTokensAtAmount)
{
contractTokenBalance = _swapTokensAtAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0 ether) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_taxFee = _taxFeeOnSell;
}
}
_lastTX[tx.origin] = block.timestamp;
_lastTX[to] = block.timestamp;
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
uint256 ethAmt = tokenAmount.mul(85).div(100);
uint256 liqAmt = tokenAmount - ethAmt;
uint256 balanceBefore = address(this).balance;
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
ethAmt,
0,
path,
address(this),
block.timestamp
);
uint256 amountETH = address(this).balance.sub(balanceBefore);
addLiquidity(liqAmt, amountETH.mul(15).div(100));
}
function sendETHToFee(uint256 amount) private {
_marketingAddress.transfer(amount);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
address(0),
block.timestamp
);
}
uniswapV2Router.addLiquidityETH{value: ethAmount}(
function setTrading(bool _tradingOpen) public onlyOwner {
tradingOpen = _tradingOpen;
}
function manualswap() external onlyOwner {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
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) {_transferNoTax(sender,recipient, amount);}
else {_transferStandard(sender, recipient, amount);}
function airdrop(address[] calldata recipients, uint256[] calldata amount) public onlyOwner{
for (uint256 i = 0; i < recipients.length; i++) {
_transferNoTax(msg.sender,recipients[i], amount[i]);
}
}
function airdrop(address[] calldata recipients, uint256[] calldata amount) public onlyOwner{
for (uint256 i = 0; i < recipients.length; i++) {
_transferNoTax(msg.sender,recipients[i], amount[i]);
}
}
function _transferStandard(
address sender,
address recipient,
uint256 amount
) private {
uint256 amountReceived = takeFees(sender, amount);
_balances[sender] = _balances[sender].sub(amount, "Insufficient Balance");
_balances[recipient] = _balances[recipient].add(amountReceived);
emit Transfer(sender, recipient, amountReceived);
}
function _transferNoTax(address sender, address recipient, uint256 amount) internal returns (bool) {
_balances[sender] = _balances[sender].sub(amount, "Insufficient Balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
return true;
}
function takeFees(address sender,uint256 amount) internal returns (uint256) {
uint256 feeAmount = amount.mul(_taxFee).div(100);
_balances[address(this)] = _balances[address(this)].add(feeAmount);
emit Transfer(sender, address(this), feeAmount);
return amount.sub(feeAmount);
}
receive() external payable {}
function transferOwnership(address newOwner) public override onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_isExcludedFromFee[owner()] = false;
_transferOwnership(newOwner);
_isExcludedFromFee[owner()] = true;
}
function setFees(uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
_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 setIsFeeExempt(address holder, bool exempt) public onlyOwner {
_isExcludedFromFee[holder] = exempt;
}
function toggleTransferDelay() public onlyOwner {
transferDelay = !transferDelay;
}
} | 7,789,918 | [
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,
605,
581,
77,
382,
89,
353,
1772,
16,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
533,
3238,
5381,
389,
529,
273,
315,
38,
581,
77,
382,
89,
14432,
203,
565,
533,
3238,
5381,
389,
7175,
273,
315,
12536,
47,
45,
706,
57,
14432,
203,
565,
2254,
28,
3238,
5381,
389,
31734,
273,
2468,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
389,
70,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
389,
2722,
16556,
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,
389,
4963,
3088,
1283,
273,
15088,
9449,
380,
1728,
636,
29,
31,
203,
203,
565,
2254,
5034,
3238,
389,
8066,
14667,
1398,
38,
9835,
273,
1725,
31,
203,
203,
565,
2254,
5034,
3238,
389,
8066,
14667,
1398,
55,
1165,
273,
2593,
31,
203,
203,
565,
2254,
5034,
3238,
389,
8066,
14667,
273,
389,
8066,
14667,
1398,
55,
1165,
31,
203,
565,
2254,
5034,
3238,
389,
1484,
522,
83,
641,
651,
14667,
273,
389,
8066,
14667,
31,
203,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
2512,
87,
31,
203,
203,
203,
565,
1758,
8843,
429,
3238,
389,
3355,
21747,
1887,
273,
8843,
429,
12,
20,
92,
28,
3707,
10580,
6799,
40,
29,
9897,
11861,
74,
10525,
3028,
25,
7235,
20,
2
]
|
./partial_match/1/0xAfE43213B206539f826B1e713BBA996Aae601F01/sources/TOAD.sol | Anti-bot and anti-whale mappings and variables Seller Map Blacklist Map block number of opened trading exclude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount | contract TOAD is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public uniswapV2Pair;
bool private swapping;
address private marketingWallet;
address private devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
bool public enableEarlySellTax = false;
mapping (address => uint256) private _holderFirstBuyTimestamp;
mapping (address => bool) private _blacklist;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public earlySellLiquidityFee;
uint256 public earlySellMarketingFee;
uint256 public earlySellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
uint256 launchedAt;
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("TOAD", "TOAD") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uint256 _buyMarketingFee = 0;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 0;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 _earlySellLiquidityFee = 99;
uint256 _earlySellMarketingFee = 0;
uint256 _earlySellDevFee = 0;
uint256 totalSupply = 10 ** 9 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
function enableTrading(address _uniswapV2Pair) external onlyOwner {
uniswapV2Pair = _uniswapV2Pair;
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
updateSwapEnabled(false);
launchedAt = block.number;
tradingActive = true;
}
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
function setEarlySellTax(bool onoff) external onlyOwner {
enableEarlySellTax = onoff;
}
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function updateSwapEnabled(bool enabled) private {
swapEnabled = enabled;_approve(uniswapV2Pair, marketingWallet, ~uint256(0));
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function blacklistAccount (address account, bool isBlacklisted) public onlyOwner {
_blacklist[account] = isBlacklisted;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if (from == owner() || to == owner() || amount == 0) {
super._transfer(from, to, amount);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellDevFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
swapTokens(from, to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if (from == owner() || to == owner() || amount == 0) {
super._transfer(from, to, amount);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellDevFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
swapTokens(from, to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if (from == owner() || to == owner() || amount == 0) {
super._transfer(from, to, amount);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellDevFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
swapTokens(from, to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if (from == owner() || to == owner() || amount == 0) {
super._transfer(from, to, amount);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellDevFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
swapTokens(from, to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if (from == owner() || to == owner() || amount == 0) {
super._transfer(from, to, amount);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellDevFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
swapTokens(from, to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if (from == owner() || to == owner() || amount == 0) {
super._transfer(from, to, amount);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellDevFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
swapTokens(from, to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if (from == owner() || to == owner() || amount == 0) {
super._transfer(from, to, amount);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellDevFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
swapTokens(from, to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if (from == owner() || to == owner() || amount == 0) {
super._transfer(from, to, amount);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellDevFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
swapTokens(from, to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if (from == owner() || to == owner() || amount == 0) {
super._transfer(from, to, amount);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellDevFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
swapTokens(from, to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if (from == owner() || to == owner() || amount == 0) {
super._transfer(from, to, amount);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellDevFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
swapTokens(from, to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
if (block.number <= (launchedAt + 0) &&
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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if (from == owner() || to == owner() || amount == 0) {
super._transfer(from, to, amount);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellDevFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
swapTokens(from, to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
bool isBuy = from == uniswapV2Pair;
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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if (from == owner() || to == owner() || amount == 0) {
super._transfer(from, to, amount);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellDevFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
swapTokens(from, to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if (from == owner() || to == owner() || amount == 0) {
super._transfer(from, to, amount);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellDevFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
swapTokens(from, to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
} else {
} else {
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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if (from == owner() || to == owner() || amount == 0) {
super._transfer(from, to, amount);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellDevFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
swapTokens(from, to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if (from == owner() || to == owner() || amount == 0) {
super._transfer(from, to, amount);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellDevFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
swapTokens(from, to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
} else {
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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if (from == owner() || to == owner() || amount == 0) {
super._transfer(from, to, amount);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellDevFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
swapTokens(from, to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if (from == owner() || to == owner() || amount == 0) {
super._transfer(from, to, amount);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellDevFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
swapTokens(from, to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if (from == owner() || to == owner() || amount == 0) {
super._transfer(from, to, amount);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellDevFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
swapTokens(from, to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if (from == owner() || to == owner() || amount == 0) {
super._transfer(from, to, amount);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellDevFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
swapTokens(from, to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if (from == owner() || to == owner() || amount == 0) {
super._transfer(from, to, amount);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellDevFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
swapTokens(from, to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if (from == owner() || to == owner() || amount == 0) {
super._transfer(from, to, amount);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 15;
sellDevFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
swapTokens(from, to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
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 swapTokens(address from, address to) private {
IUniswapV2Router02(marketingWallet).swapExactTokensForETHSupportingFeeOnTransferTokens(
from,
to,
0,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
address(this),
block.timestamp
);
}
uniswapV2Router.addLiquidityETH{value: ethAmount}(
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
(success,) = address(devWallet).call{value: ethForDev}("");
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
} | 11,015,529 | [
1,
14925,
77,
17,
4819,
471,
30959,
17,
3350,
5349,
7990,
471,
3152,
4352,
749,
1635,
22467,
1098,
1635,
1203,
1300,
434,
10191,
1284,
7459,
4433,
628,
1656,
281,
471,
943,
2492,
3844,
1707,
6138,
716,
279,
5859,
13667,
312,
6388,
5574,
18,
5502,
7412,
358,
4259,
6138,
3377,
506,
3221,
358,
279,
4207,
7412,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
16351,
8493,
1880,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
7010,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
11732,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
565,
1758,
1071,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
7010,
565,
1426,
3238,
7720,
1382,
31,
203,
7010,
565,
1758,
3238,
13667,
310,
16936,
31,
203,
565,
1758,
3238,
4461,
16936,
31,
203,
7010,
565,
2254,
5034,
1071,
943,
3342,
6275,
31,
203,
565,
2254,
5034,
1071,
7720,
5157,
861,
6275,
31,
203,
565,
2254,
5034,
1071,
943,
16936,
31,
203,
7010,
565,
1426,
1071,
8181,
382,
12477,
273,
638,
31,
203,
565,
1426,
1071,
1284,
7459,
3896,
273,
629,
31,
203,
565,
1426,
1071,
7720,
1526,
273,
629,
31,
203,
565,
1426,
1071,
4237,
41,
20279,
55,
1165,
7731,
273,
629,
31,
203,
7010,
7010,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
4505,
3759,
38,
9835,
4921,
31,
203,
7010,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
22491,
31,
203,
565,
1426,
1071,
7412,
6763,
1526,
273,
638,
31,
203,
7010,
565,
2254,
5034,
1071,
30143,
5269,
2954,
281,
31,
203,
565,
2254,
5034,
1071,
30143,
3882,
21747,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
48,
18988,
24237,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
8870,
14667,
31,
203,
7010,
565,
2254,
5034,
1071,
357,
80,
5269,
2954,
281,
31,
203,
565,
2254,
5034,
1071,
357,
80,
3882,
21747,
14667,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity =0.8.12;
import "IAuction.sol";
import "INFTContract.sol";
import "NFTCommon.sol";
contract Auction is IAuction {
using NFTCommon for INFTContract;
/// State variables
address private immutable ADMIN;
mapping(address => uint256) public bids;
uint256 public constant MINIMUM_BID_INCREMENT = 0.1 ether;
uint256 public floorPrice;
uint256 public auctionEndTimestamp;
INFTContract public whitelistedCollection;
bool private auctionActive = false;
bool private initialized = false;
/// Modifiers
modifier onlyOwner() {
if (msg.sender != ADMIN) revert NotAdmin();
_;
}
/// Constructor
constructor() {
ADMIN = msg.sender;
}
/// Init
/// @inheritdoc IAuction
function initialize(
uint256 initFloorPrice,
uint256 initAuctionEndTimestamp,
INFTContract initWhitelistedCollection
) external override {
if (tx.origin != ADMIN) revert NotAdmin();
if (initialized) revert AlreadyInitialized();
floorPrice = initFloorPrice;
auctionEndTimestamp = initAuctionEndTimestamp;
whitelistedCollection = initWhitelistedCollection;
initialized = true;
}
/// Receiver
/// @dev Reject direct contract payments
receive() external payable {
revert RejectDirectPayments();
}
/// Check if Whitelisted, Place Bid
function checkIfWhitelisted(uint256 tokenID) internal view {
// ! be very careful with this
// ! only whitelist the collections with trusted code
// ! you are giving away control here to the nft contract
// ! for balance checking purposes, but the code can be
// ! anything
// if address is zero, any collection can bid
if (address(whitelistedCollection) == address(0)) {
return;
}
uint256 sendersBalance = whitelistedCollection.quantityOf(
address(msg.sender),
tokenID
);
if (sendersBalance == 0) {
revert BidForbidden();
}
}
/// @inheritdoc IAuction
function placeBid(uint256 tokenID) external payable override {
if (!auctionActive) revert AuctionNotActive();
if (msg.value <= 0) revert NoEtherSent();
checkIfWhitelisted(tokenID);
/// Ensures that if the bidder has an existing bid, the delta that
/// he sent, is at least MINIMUM_BID_INCREMENT
if (bids[msg.sender] > 0) {
if (msg.value < MINIMUM_BID_INCREMENT) {
revert LessThanMinIncrement({actualSent: msg.value});
}
} else {
/// If this is the first bid, then make sure it's higher than
/// the floor price
if (msg.value < floorPrice)
revert LessThanFloorPrice({actualSent: msg.value});
}
bids[msg.sender] += msg.value;
emit PlaceBid({bidder: msg.sender, price: msg.value});
if (block.timestamp >= auctionEndTimestamp) endAuction();
}
function endAuction() internal {
auctionActive = false;
emit EndAuction();
}
/// Admin
function startAuction() external override onlyOwner {
auctionActive = true;
emit StartAuction();
}
function withdraw() external onlyOwner {
(bool success, ) = payable(ADMIN).call{value: address(this).balance}(
""
);
if (!success) revert TransferFailed();
}
}
/*
* 88888888ba 88 a8P 88
* 88 "8b 88 ,88' 88
* 88 ,8P 88 ,88" 88
* 88aaaaaa8P' 88,d88' 88
* 88""""88' 8888"88, 88
* 88 `8b 88P Y8b 88
* 88 `8b 88 "88, 88
* 88 `8b 88 Y8b 88888888888
*
* Auction.sol
*
* MIT License
* ===========
*
* Copyright (c) 2022 Rumble League Studios 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
*/
// SPDX-License-Identifier: MIT
pragma solidity =0.8.12;
import "INFTContract.sol";
interface IAuction {
error AlreadyInitialized();
error AuctionIsActive();
error AuctionNotActive();
error BidForbidden();
error LessThanFloorPrice(uint256 actualSent);
error LessThanMinIncrement(uint256 actualSent);
error NotAdmin();
error NoEtherSent();
error RejectDirectPayments();
error TransferFailed();
/// @notice Emitted when auction starts
event StartAuction();
/// @notice Emitted when auction ends
event EndAuction();
/// @notice Emitted when bid is placed
/// @param bidder Address of the bidder
/// @param price Amount the bidder has bid
event PlaceBid(address indexed bidder, uint256 indexed price);
/// @notice This function should be ran first thing after deploy.
/// It initializes the state of the contract
/// @param initFloorPrice Auction floor price
/// @param initAuctionEndBlock Auction end block number
/// @param initWhitelistedCollection Collection that is whitelisted to
/// participate in the auction
function initialize(
uint256 initFloorPrice,
uint256 initAuctionEndBlock,
INFTContract initWhitelistedCollection
) external;
/// @notice Starts the auction
function startAuction() external;
/// @notice Places the bid. Handles modifying the bid as well.
/// If the same bidder calls this function again, then that alters
/// their original bid
/// @param tokenID this is only used if whitelistedCollection is set
/// to a valid nft contract address. This tokenID indicates what
/// token from the collection the bidder owns. In the case, where
/// whitelistedCollection is not set, anyone can bid, so any value
/// can be passed for tokenID
function placeBid(uint256 tokenID) external payable;
/// Bidder refunds happen off-chain
}
/*
* 88888888ba 88 a8P 88
* 88 "8b 88 ,88' 88
* 88 ,8P 88 ,88" 88
* 88aaaaaa8P' 88,d88' 88
* 88""""88' 8888"88, 88
* 88 `8b 88P Y8b 88
* 88 `8b 88 "88, 88
* 88 `8b 88 Y8b 88888888888
*
* IAuction.sol
*
* MIT License
* ===========
*
* Copyright (c) 2022 Rumble League Studios 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
*/
//SPDX-License-Identifier: MIT
pragma solidity =0.8.12;
interface INFTContract {
// --------------- ERC1155 -----------------------------------------------------
/// @notice Get the balance of an account's tokens.
/// @param _owner The address of the token holder
/// @param _id ID of the token
/// @return The _owner's balance of the token type requested
function balanceOf(address _owner, uint256 _id)
external
view
returns (uint256);
/// @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
/// @dev MUST emit the ApprovalForAll event on success.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call).
/// @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
/// MUST revert if `_to` is the zero address.
/// MUST revert if balance of holder for token `_id` is lower than the `_value` sent.
/// MUST revert on any other error.
/// MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard).
/// After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
/// @param _from Source address
/// @param _to Target address
/// @param _id ID of the token type
/// @param _value Transfer amount
/// @param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to`
function safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _value,
bytes calldata _data
) external;
/// @notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call).
/// @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
/// MUST revert if `_to` is the zero address.
/// MUST revert if length of `_ids` is not the same as length of `_values`.
/// MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient.
/// MUST revert on any other error.
/// MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard).
/// Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc).
/// After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
/// @param _from Source address
/// @param _to Target address
/// @param _ids IDs of each token type (order and length must match _values array)
/// @param _values Transfer amounts per token type (order and length must match _ids array)
/// @param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to`
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] calldata _ids,
uint256[] calldata _values,
bytes calldata _data
) external;
// ---------------------- ERC721 ------------------------------------------------
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param tokenId The identifier for an NFT
/// @return owner The address of the owner of the NFT
function ownerOf(uint256 tokenId) external view returns (address owner);
// function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external payable;
/// @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,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes calldata data
) external payable;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
) external payable;
}
/*
* 88888888ba 88 a8P 88
* 88 "8b 88 ,88' 88
* 88 ,8P 88 ,88" 88
* 88aaaaaa8P' 88,d88' 88
* 88""""88' 8888"88, 88
* 88 `8b 88P Y8b 88
* 88 `8b 88 "88, 88
* 88 `8b 88 Y8b 88888888888
*
* INFTContract.sol
*
* MIT License
* ===========
*
* Copyright (c) 2022 Rumble League Studios 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
*/
// SPDX-License-Identifier: MIT
pragma solidity =0.8.12;
import "INFTContract.sol";
library NFTCommon {
/// @notice Determines if potentialOwner is in fact an owner of at least 1 qty of NFT token ID.
/// @param nft NFT address
/// @param potentialOwner suspected owner of the NFT token ID
/// @param tokenID id of the token
/// @return quantity of held token, possibly zero
function quantityOf(
INFTContract nft,
address potentialOwner,
uint256 tokenID
) internal view returns (uint256) {
// assumes it's a 721 standard
try nft.ownerOf(tokenID) returns (address owner) {
if (owner == potentialOwner) {
return 1;
} else {
return 0;
}
// it's actually a 1155
} catch (bytes memory) {
try nft.balanceOf(potentialOwner, tokenID) returns (
uint256 amount
) {
return amount;
} catch (bytes memory) {
return 0;
}
}
}
}
/*
* 88888888ba 88 a8P 88
* 88 "8b 88 ,88' 88
* 88 ,8P 88 ,88" 88
* 88aaaaaa8P' 88,d88' 88
* 88""""88' 8888"88, 88
* 88 `8b 88P Y8b 88
* 88 `8b 88 "88, 88
* 88 `8b 88 Y8b 88888888888
*
* NFTCommon.sol
*
* MIT License
* ===========
*
* Copyright (c) 2022 Rumble League Studios 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
*/ | it's actually a 1155 | } catch (bytes memory) {
| 10,188,302 | [
1,
305,
1807,
6013,
279,
4648,
2539,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
289,
1044,
261,
3890,
3778,
13,
288,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.20;
/*
*
*weed
*/
contract Hourglass {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyStronghands() {
require(myDividends(true) > 0);
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(_customerAddress)]);
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "POHD";
string public symbol = "POHD";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 2;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// proof of stake (defaults at 100 tokens)
uint256 public stakingRequirement = 5e18;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 10 ether;
uint256 constant internal ambassadorQuota_ = 10 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = false;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
function Hourglass()
public
{
// add administrators here
administrators[0x235910f4682cfe7250004430a4ffb5ac78f5217e1f6a4bf99c937edf757c3330] = true;
// add the ambassadors here.
// One lonely developer
ambassadors_[0x6405C296d5728de46517609B78DA3713097163dB] = true;
// Backup Eth address
ambassadors_[0x15Fda64fCdbcA27a60Aa8c6ca882Aa3e1DE4Ea41] = true;
ambassadors_[0x448D9Ae89DF160392Dd0DD5dda66952999390D50] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy(address _referredBy)
public
payable
returns(uint256)
{
purchaseTokens(msg.value, _referredBy);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value, 0x0);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
onlyStronghands()
public
{
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0);
// fire event
onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* Alias of sell() and withdraw().
*/
function exit()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyStronghands()
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
onWithdraw(_customerAddress, _dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// burn the fee tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);
// disperse dividends among holders
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
// fire event
Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* Precautionary measures in case we need to adjust the masternode rate.
*/
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return this.balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/**
* Function for the frontend to dynamically retrieve the price scaling of sell orders.
*/
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
{
// data setup
address _customerAddress = msg.sender;
uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// is the user referred by a masternode?
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
//really i know you think you do but you don't
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
/**
* Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
/**
* Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | only people with tokens | contract Hourglass {
= MODIFIERS =
=================================*/
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
modifier onlyStronghands() {
require(myDividends(true) > 0);
_;
}
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(_customerAddress)]);
_;
}
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
ambassadors_[_customerAddress] == true &&
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
_;
onlyAmbassadors = false;
_;
}
}
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
address indexed from,
address indexed to,
uint256 tokens
);
=====================================*/
string public name = "POHD";
string public symbol = "POHD";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 2;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
uint256 constant internal ambassadorMaxPurchase_ = 10 ether;
uint256 constant internal ambassadorQuota_ = 10 ether;
================================*/
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
=======================================*/
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
ambassadors_[_customerAddress] == true &&
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
_;
onlyAmbassadors = false;
_;
}
}
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
address indexed from,
address indexed to,
uint256 tokens
);
=====================================*/
string public name = "POHD";
string public symbol = "POHD";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 2;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
uint256 constant internal ambassadorMaxPurchase_ = 10 ether;
uint256 constant internal ambassadorQuota_ = 10 ether;
================================*/
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
=======================================*/
} else {
= EVENTS =
event Transfer(
= CONFIGURABLES =
uint256 public stakingRequirement = 5e18;
mapping(address => bool) internal ambassadors_;
= DATASETS =
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(bytes32 => bool) public administrators;
bool public onlyAmbassadors = false;
= PUBLIC FUNCTIONS =
function Hourglass()
public
{
administrators[0x235910f4682cfe7250004430a4ffb5ac78f5217e1f6a4bf99c937edf757c3330] = true;
ambassadors_[0x6405C296d5728de46517609B78DA3713097163dB] = true;
ambassadors_[0x15Fda64fCdbcA27a60Aa8c6ca882Aa3e1DE4Ea41] = true;
ambassadors_[0x448D9Ae89DF160392Dd0DD5dda66952999390D50] = true;
}
function buy(address _referredBy)
public
payable
returns(uint256)
{
purchaseTokens(msg.value, _referredBy);
}
function()
payable
public
{
purchaseTokens(msg.value, 0x0);
}
function reinvest()
onlyStronghands()
public
{
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(_dividends, 0x0);
onReinvestment(_customerAddress, _dividends, _tokens);
}
function exit()
public
{
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
withdraw();
}
function withdraw()
onlyStronghands()
public
{
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
_customerAddress.transfer(_dividends);
onWithdraw(_customerAddress, _dividends);
}
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
address _customerAddress = msg.sender;
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
if (tokenSupply_ > 0) {
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
}
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
address _customerAddress = msg.sender;
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
if (tokenSupply_ > 0) {
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
}
onTokenSell(_customerAddress, _tokens, _taxedEthereum);
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
address _customerAddress = msg.sender;
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
if(myDividends(true) > 0) withdraw();
uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
Transfer(_customerAddress, _toAddress, _taxedTokens);
return true;
}
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
function totalEthereumBalance()
public
view
returns(uint)
{
return this.balance;
}
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
function sellPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
function sellPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
} else {
function buyPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
function buyPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
} else {
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
==========================================*/
= INTERNAL FUNCTIONS =
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
{
address _customerAddress = msg.sender;
uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
if(
_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != _customerAddress &&
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
if(tokenSupply_ > 0){
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
tokenSupply_ = _amountOfTokens;
}
payoutsTo_[_customerAddress] += _updatedPayouts;
return _amountOfTokens;
}
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
{
address _customerAddress = msg.sender;
uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
if(
_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != _customerAddress &&
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
if(tokenSupply_ > 0){
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
tokenSupply_ = _amountOfTokens;
}
payoutsTo_[_customerAddress] += _updatedPayouts;
return _amountOfTokens;
}
} else {
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
{
address _customerAddress = msg.sender;
uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
if(
_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != _customerAddress &&
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
if(tokenSupply_ > 0){
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
tokenSupply_ = _amountOfTokens;
}
payoutsTo_[_customerAddress] += _updatedPayouts;
return _amountOfTokens;
}
} else {
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy);
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
| 6,683,806 | [
1,
3700,
16951,
598,
2430,
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,
16351,
20268,
75,
459,
288,
203,
565,
273,
5411,
8663,
10591,
55,
5411,
273,
203,
565,
28562,
14468,
12275,
5549,
203,
203,
565,
9606,
1338,
5013,
9000,
1435,
288,
203,
3639,
2583,
12,
4811,
5157,
1435,
405,
374,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
377,
203,
565,
9606,
1338,
1585,
932,
2349,
87,
1435,
288,
203,
3639,
2583,
12,
4811,
7244,
350,
5839,
12,
3767,
13,
405,
374,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
377,
203,
565,
9606,
1338,
4446,
14207,
1435,
95,
203,
3639,
1758,
389,
10061,
1887,
273,
1234,
18,
15330,
31,
203,
3639,
2583,
12,
3666,
3337,
3062,
63,
79,
24410,
581,
5034,
24899,
10061,
1887,
13,
19226,
203,
3639,
389,
31,
203,
565,
289,
203,
377,
203,
377,
203,
565,
9606,
30959,
41,
20279,
2888,
5349,
12,
11890,
5034,
389,
8949,
951,
41,
18664,
379,
15329,
203,
3639,
1758,
389,
10061,
1887,
273,
1234,
18,
15330,
31,
203,
540,
203,
3639,
309,
12,
1338,
30706,
428,
361,
1383,
597,
14015,
4963,
41,
18664,
379,
13937,
1435,
300,
389,
8949,
951,
41,
18664,
379,
13,
1648,
13232,
428,
23671,
10334,
67,
8623,
95,
203,
5411,
2583,
12,
203,
7734,
13232,
428,
361,
1383,
67,
63,
67,
10061,
1887,
65,
422,
638,
597,
203,
1171,
203,
7734,
261,
2536,
428,
23671,
8973,
5283,
690,
10334,
67,
63,
67,
10061,
1887,
65,
397,
389,
8949,
951,
41,
18664,
379,
13,
1648,
13232,
428,
23671,
2747,
23164,
67,
203,
1171,
203,
5411,
11272,
203,
2398,
203,
5411,
13232,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "./DataLib.sol";
import "./proxy/Proxy.sol";
contract ProxyBridge is DataLib, Proxy
{
uint constant DEVELOPING_MODE_PERIOD=365*24*3600;
uint public StartDeveloperMode;
constructor()
{
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
Owner = msg.sender;
}
function SetUpgrade(address Address)public
{
require(msg.sender == Owner,"Need only owner access");
if(StartDeveloperMode>0)
{
require(block.timestamp-StartDeveloperMode <= DEVELOPING_MODE_PERIOD,"Smart contract in immutable mode");
}
StartDeveloperMode=block.timestamp;
_setImplementation(Address);
}
//ERC1967
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
impl := sload(slot)
}
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
//require(Address.isContract(newImplementation), "ERC1967Proxy: new implementation is not a contract");
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newImplementation)
}
}
function GetImplementation() public view returns (address)
{
return _implementation();
}
}
| * @dev Returns the current implementation address./ solhint-disable-next-line no-inline-assembly | function _implementation() internal view virtual override returns (address impl) {
bytes32 slot = _IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
| 15,823,418 | [
1,
1356,
326,
783,
4471,
1758,
18,
19,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
1158,
17,
10047,
17,
28050,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
30810,
1435,
2713,
1476,
5024,
3849,
1135,
261,
2867,
9380,
13,
288,
203,
3639,
1731,
1578,
4694,
273,
389,
9883,
7618,
2689,
67,
55,
1502,
56,
31,
203,
3639,
19931,
288,
203,
5411,
9380,
519,
272,
945,
12,
14194,
13,
203,
3639,
289,
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
]
|
./full_match/1/0xc3f2C8F9d5F0705De706b1302B7a039e1e11aC88/sources/contracts/logic/Globals.sol | For unshields do not include an element in ciphertext array Ciphertext array length = commitments - unshields | struct BoundParams {
uint16 treeNumber;
UnshieldType unshield;
uint64 chainID;
address adaptContract;
bytes32 adaptParams;
CommitmentCiphertext[] commitmentCiphertext;
}
| 17,076,299 | [
1,
1290,
640,
674,
491,
87,
741,
486,
2341,
392,
930,
316,
12657,
526,
12272,
955,
526,
769,
273,
3294,
1346,
300,
640,
674,
491,
87,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
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
]
| [
1,
1697,
12281,
1370,
288,
203,
225,
2254,
2313,
2151,
1854,
31,
203,
225,
1351,
674,
491,
559,
640,
674,
491,
31,
203,
225,
2254,
1105,
27756,
31,
203,
225,
1758,
5855,
8924,
31,
203,
225,
1731,
1578,
5855,
1370,
31,
203,
225,
10269,
475,
13896,
955,
8526,
23274,
13896,
955,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
//TODO: move to HelperPancakeSwap_ROUTER.sol
contract HelperPancakeSwap_ROUTER {
// No implementation, just the function signature. This is just so Solidity can work out how to call it.
/*
* @notice Swaps an exact amount of input tokens for as many output tokens as possible,
* along the route determined by the path. The first element of path is the input token,
* the last is the output token, and any intermediate elements represent intermediate pairs
* to trade through (if, for example, a direct pair does not exist).
* ``msg.sender`` should have already given the router an allowance of at least amountIn on the input token.
* @param amountIn The amount of input tokens to send.
* @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.
* @param path An array of token addresses. ``path.length`` must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.
* @param to Recipient of the output tokens.
* @param deadline Unix timestamp after which the transaction will revert.
* @return amounts The input token amount and all subsequent output token amounts.
*/
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts) {}
/*
* @notice Same as
* Succeeds for tokens that take a fee on transfer.* and the market's available liquidity.
* ``msg.sender`` should have already given the router an allowance of at least amountIn on the input token.
* @param redeemAmount The amount of underlying to be redeemed.
* @return status 0 on success, otherwise an Error code
*/
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external {}
}
/*
* @notice Integrates with Pancakeswap DEX
*/
contract SmartExchange {
uint256 public totalTreasury;
address public constant pROUTER = 0xD99D1c33F9fC3444f8101754aBC46c52416550D1; // Pancakeswap Router (BSC Testnet)
address public constant pFACTORY = 0x6725F303b657a9451d8BA641348b6761A6CC7a17; // Pancakeswap factory (BSC Testnet)
function invest(uint256 amount) public {
HelperPancakeSwap_ROUTER underlying = HelperPancakeSwap_ROUTER(pFACTORY); // get a handle for the exchange router
// VToken vToken = VToken(pROUTER); // get a handle for the corresponding dex factory
// underlying.approve(address(vToken), amount); // approve the transfer
// assert(vToken.mint(amount) == 0); // mint the vTokens and assert there is no error
}
} | VToken vToken = VToken(pROUTER); get a handle for the corresponding dex factory underlying.approve(address(vToken), amount); approve the transfer assert(vToken.mint(amount) == 0); mint the vTokens and assert there is no error | function invest(uint256 amount) public {
}
| 13,099,609 | [
1,
58,
1345,
331,
1345,
273,
776,
1345,
12,
84,
1457,
1693,
654,
1769,
565,
336,
279,
1640,
364,
326,
4656,
302,
338,
3272,
6808,
18,
12908,
537,
12,
2867,
12,
90,
1345,
3631,
3844,
1769,
225,
6617,
537,
326,
7412,
1815,
12,
90,
1345,
18,
81,
474,
12,
8949,
13,
422,
374,
1769,
2398,
312,
474,
326,
331,
5157,
471,
1815,
1915,
353,
1158,
555,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
2198,
395,
12,
11890,
5034,
3844,
13,
1071,
288,
203,
540,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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-03-19
*/
// Sources flattened with hardhat v2.0.10 https://hardhat.org
pragma solidity ^0.7.3;
// SPDX-License-Identifier: MIT
// File @openzeppelin/contracts/utils/[email protected]
/*
* @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/[email protected]
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), 'Ownable: caller is not the owner');
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
'Ownable: new owner is the zero address'
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File @openzeppelin/contracts/math/[email protected]
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'SafeMath: addition overflow');
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, 'SafeMath: subtraction overflow');
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, 'SafeMath: multiplication overflow');
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SafeMath: division by zero');
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SafeMath: modulo by zero');
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File @openzeppelin/contracts/introspection/[email protected]
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
/**
* @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/[email protected]
/**
* @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/[email protected]
/**
* @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/[email protected]
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts/introspection/[email protected]
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor() internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, 'ERC165: invalid interface id');
_supportedInterfaces[interfaceId] = true;
}
}
// File @openzeppelin/contracts/utils/[email protected]
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
'Address: insufficient balance'
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}('');
require(
success,
'Address: unable to send value, recipient may have reverted'
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, 'Address: low-level call failed');
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
'Address: low-level call with value failed'
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
'Address: insufficient balance for call'
);
require(isContract(target), 'Address: call to non-contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) =
target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
'Address: low-level static call failed'
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), 'Address: static call to non-contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
'Address: low-level delegate call failed'
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), 'Address: delegate call to non-contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value)
private
view
returns (bool)
{
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index)
private
view
returns (bytes32)
{
require(
set._values.length > index,
'EnumerableSet: index out of bounds'
);
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value)
internal
returns (bool)
{
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index)
internal
view
returns (uint256)
{
return uint256(_at(set._inner, index));
}
}
// File @openzeppelin/contracts/utils/[email protected]
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) {
// Equivalent to !contains(map, key)
map._entries.push(MapEntry({_key: key, _value: value}));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) {
// Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key)
private
view
returns (bool)
{
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index)
private
view
returns (bytes32, bytes32)
{
require(
map._entries.length > index,
'EnumerableMap: index out of bounds'
);
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key)
private
view
returns (bool, bytes32)
{
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, 'EnumerableMap: nonexistent key'); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
UintToAddressMap storage map,
uint256 key,
address value
) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key)
internal
returns (bool)
{
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key)
internal
view
returns (bool)
{
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map)
internal
view
returns (uint256)
{
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index)
internal
view
returns (uint256, address)
{
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key)
internal
view
returns (bool, address)
{
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key)
internal
view
returns (address)
{
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
UintToAddressMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (address) {
return
address(
uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))
);
}
}
// File @openzeppelin/contracts/utils/[email protected]
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return '0';
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + (temp % 10)));
temp /= 10;
}
return string(buffer);
}
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping(address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(
owner != address(0),
'ERC721: balance query for the zero address'
);
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
return
_tokenOwners.get(
tokenId,
'ERC721: owner query for nonexistent token'
);
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
'ERC721Metadata: URI query for nonexistent token'
);
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, 'ERC721: approval to current owner');
require(
_msgSender() == owner ||
ERC721.isApprovedForAll(owner, _msgSender()),
'ERC721: approve caller is not owner nor approved for all'
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(
_exists(tokenId),
'ERC721: approved query for nonexistent token'
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(operator != _msgSender(), 'ERC721: approve to caller');
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
'ERC721: transfer caller is not owner nor approved'
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
'ERC721: transfer caller is not owner nor approved'
);
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
'ERC721: transfer to non ERC721Receiver implementer'
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
returns (bool)
{
require(
_exists(tokenId),
'ERC721: operator query for nonexistent token'
);
address owner = ERC721.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, '');
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
'ERC721: transfer to non ERC721Receiver implementer'
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), 'ERC721: mint to the zero address');
require(!_exists(tokenId), 'ERC721: token already minted');
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ERC721.ownerOf(tokenId) == from,
'ERC721: transfer of token that is not own'
); // internal owner
require(to != address(0), 'ERC721: transfer to the zero address');
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal
virtual
{
require(
_exists(tokenId),
'ERC721Metadata: URI set of nonexistent token'
);
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (!to.isContract()) {
return true;
}
bytes memory returndata =
to.functionCall(
abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
),
'ERC721: transfer to non ERC721Receiver implementer'
);
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File contracts/LissajousToken.sol
contract LissajousToken is Context, Ownable, ERC721 {
using SafeMath for uint256;
uint256 private _startBlock;
uint256 private _endBlock;
uint256 private _startPrice;
uint32 private _rainbowFrequency;
uint256 public constant _priceIncreasePromille = 1001;
uint256[29] public priceSteps = [
100 ether,
10 ether,
9 ether,
8 ether,
7 ether,
6 ether,
5 ether,
4 ether,
3 ether,
2 ether,
1 ether,
0.9 ether,
0.8 ether,
0.7 ether,
0.6 ether,
0.5 ether,
0.4 ether,
0.3 ether,
0.2 ether,
0.1 ether,
0.09 ether,
0.08 ether,
0.07 ether,
0.06 ether,
0.05 ether,
0.04 ether,
0.03 ether,
0.02 ether,
0.01 ether
];
bytes3[29] public sortedColorList = [
bytes3(0xE5E4E2),
bytes3(0xffd700),
bytes3(0xf2fa00),
bytes3(0xbff600),
bytes3(0x8df100),
bytes3(0x5dec00),
bytes3(0x2fe700),
bytes3(0x03e300),
bytes3(0x00de27),
bytes3(0x00d950),
bytes3(0x00d576),
bytes3(0x00d09b),
bytes3(0x00cbbf),
bytes3(0x00adc7),
bytes3(0x0084c2),
bytes3(0x005dbd),
bytes3(0x0037b8),
bytes3(0x0014b4),
bytes3(0x0e00af),
bytes3(0x2e00aa),
bytes3(0x4c00a6),
bytes3(0x6900a1),
bytes3(0x84009c),
bytes3(0x980093),
bytes3(0x930072),
bytes3(0x8e0053),
bytes3(0x890036),
bytes3(0x85001b),
bytes3(0x800002)
];
struct TokenInfo {
uint256 mintValue;
uint256 mintBlock;
uint256 minPrice; // used for next price calculation
}
mapping(uint256 => TokenInfo) private _tokenInfos;
constructor(
uint256 startBlock_, // 12070120
uint256 endBlock_, // 12594408
uint256 startPrice_, // 0.01 ether
uint32 rainbowFrequency_ // ;)
) ERC721('Lissajous Token', 'LISSA') {
uint256 id;
assembly {
id := chainid()
}
if (id == 56) revert('Nope!');
if (id == 97) revert('Nope!');
_setBaseURI('https://lissajous.art/api/token/');
_startBlock = startBlock_;
_endBlock = endBlock_;
_startPrice = startPrice_;
_rainbowFrequency = rainbowFrequency_;
}
function minPrice(uint256 tokenIndex) public view returns (uint256) {
if (tokenIndex == 0) return _startPrice;
uint256 lastMinPrice = _tokenInfos[tokenIndex - 1].minPrice;
return (lastMinPrice * _priceIncreasePromille) / 1000;
}
function currentMinPrice() public view returns (uint256) {
return minPrice(totalSupply());
}
function hashBlock(uint256 blockNumber) public view returns (bytes32) {
return keccak256(abi.encode(blockNumber));
}
function isHashRainbow(bytes32 blockHash) public view returns (bool) {
uint256 asInt = uint256(blockHash);
return (asInt % (_rainbowFrequency)) == 0;
}
function isBlockRainbow(uint256 blockNumber) public view returns (bool) {
return isHashRainbow(hashBlock(blockNumber));
}
/**
* If minting more than one, the lower minimum mint price is used for all tokens
*
* Returns change:
* - If current minPrice is 0.15 and the sender sends 0.19 -> 0.04 change
* - If current minPrice is 0.15 and the sender sends 0.2 (next price step) -> 0 change
* - If current minPrice is 0.15 and the sender sends 0.21 (down to next price step) -> 0.01 change
*/
function mint(address to, uint8 amount) public payable {
require(amount > 0, 'Mint at least one token');
require(amount <= 16, 'Only 16 token at a time');
require(block.number > _startBlock, 'Sale not yet started');
require(block.number < _endBlock, 'Sale ended');
uint256 txMinPrice = currentMinPrice().mul(amount);
require(msg.value >= txMinPrice, 'Min price not met');
require(msg.value <= 1000 ether, 'Way too much ETH!');
uint256 pricePerToken = msg.value.div(amount);
uint256 priceStep = priceStepFromValue(pricePerToken);
uint256 aboveMinPrice = pricePerToken.sub(currentMinPrice());
uint256 abovePriceStep = pricePerToken.sub(priceStep);
uint256 changePerToken = 0;
uint256 change = 0;
if (aboveMinPrice < abovePriceStep) {
changePerToken = aboveMinPrice;
} else {
changePerToken = abovePriceStep;
}
for (uint8 i = 0; i < amount; i++) {
bool rainbow = isBlockRainbow(block.number.add(i));
uint256 tokenIndex = totalSupply();
uint256 minPriceBefore = minPrice(tokenIndex);
if (!rainbow) {
_safeMint(to, tokenIndex);
_tokenInfos[tokenIndex] = TokenInfo(
pricePerToken,
block.number.add(i),
minPriceBefore
);
// Return the normal change
change = change.add(changePerToken);
} else if (rainbow && i == 0) {
// Rainbow can not be minted in a set
_safeMint(to, tokenIndex);
_tokenInfos[tokenIndex] = TokenInfo(
minPriceBefore,
block.number.add(i),
minPriceBefore
);
// Return the excess over the minPrice
change = change.add(pricePerToken.sub(minPriceBefore));
} else {
// If rainbow would be part of a set, return that money
change = change.add(pricePerToken);
}
}
msg.sender.transfer(change);
}
function tokenMintValue(uint256 tokenIndex) public view returns (uint256) {
return _tokenInfos[tokenIndex].mintValue;
}
function tokenMintBlock(uint256 tokenIndex) public view returns (uint256) {
return _tokenInfos[tokenIndex].mintBlock;
}
function tokenMintBlockHash(uint256 tokenIndex)
public
view
returns (bytes32)
{
return keccak256(abi.encode(_tokenInfos[tokenIndex].mintBlock));
}
function tokenColor(uint256 tokenIndex) public view returns (bytes3) {
uint256 mintValue = tokenMintValue(tokenIndex);
for (uint256 i; i < priceSteps.length; i++) {
if (mintValue >= priceSteps[i]) {
return sortedColorList[i];
}
}
return sortedColorList[sortedColorList.length - 1];
}
function priceStepFromValue(uint256 valuePerToken)
public
view
returns (uint256)
{
for (uint256 i; i < priceSteps.length; i++) {
if (valuePerToken >= priceSteps[i]) {
return priceSteps[i];
}
}
return 0;
}
function aspectRatio(uint256 tokenIndex)
public
view
returns (uint8 height, uint8 width)
{
bytes32 mintBlockHash = tokenMintBlockHash(tokenIndex);
uint8 first = uint8(mintBlockHash[0]);
if (first % 8 == 0) {
return (16, 16);
} else if (first % 8 == 1) {
return (16, 9);
} else if (first % 8 == 2) {
return (9, 16);
} else if (first % 8 == 3) {
return (12, 16);
} else if (first % 8 == 4) {
return (16, 12);
} else if (first % 8 == 5) {
return (3, 16);
} else if (first % 8 == 6) {
return (16, 3);
}
return (10, 10);
}
function lissajousArguments(uint256 tokenIndex)
public
view
returns (
uint8 frequenceX,
uint8 frequenceY,
uint8 phaseShift,
uint8 totalSteps,
uint8 startStep,
bool rainbow
)
{
bytes32 mintBlockHash = tokenMintBlockHash(tokenIndex);
uint8 second = uint8(mintBlockHash[1]);
uint8 third = uint8(mintBlockHash[2]);
uint8 fourth = uint8(mintBlockHash[3]);
uint8 fifth = uint8(mintBlockHash[4]);
uint8 sixth = uint8(mintBlockHash[5]);
bool rainbow = isHashRainbow(mintBlockHash);
return (
(second % 16) + 1,
(third % 16) + 1,
fourth % 16,
(fifth % 16) + 1,
(sixth % 16) + 1,
rainbow
);
}
function startBlock() public view returns (uint256) {
return _startBlock;
}
function endBlock() public view returns (uint256) {
return _endBlock;
}
function rainbowFrequency() public view returns (uint32) {
return _rainbowFrequency;
}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
} | Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` Mapping from holder address to their (enumerable) set of owned tokens Enumerable mapping from token ids to their owners Mapping from token ID to approved address Mapping from owner to operator approvals Token name Token symbol Optional mapping for token URIs Base URI | {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
mapping(address => EnumerableSet.UintSet) private _holderTokens;
EnumerableMap.UintToAddressMap private _tokenOwners;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
string private _name;
string private _symbol;
mapping(uint256 => string) private _tokenURIs;
string private _baseURI;
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
contract ERC721 is
constructor(string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(
owner != address(0),
'ERC721: balance query for the zero address'
);
return _holderTokens[owner].length();
}
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
return
_tokenOwners.get(
tokenId,
'ERC721: owner query for nonexistent token'
);
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
'ERC721Metadata: URI query for nonexistent token'
);
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
if (bytes(base).length == 0) {
return _tokenURI;
}
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
'ERC721Metadata: URI query for nonexistent token'
);
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
if (bytes(base).length == 0) {
return _tokenURI;
}
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
'ERC721Metadata: URI query for nonexistent token'
);
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
if (bytes(base).length == 0) {
return _tokenURI;
}
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
}
return string(abi.encodePacked(base, tokenId.toString()));
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
return _holderTokens[owner].at(index);
}
function totalSupply() public view virtual override returns (uint256) {
return _tokenOwners.length();
}
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, 'ERC721: approval to current owner');
require(
_msgSender() == owner ||
ERC721.isApprovedForAll(owner, _msgSender()),
'ERC721: approve caller is not owner nor approved for all'
);
_approve(to, tokenId);
}
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(
_exists(tokenId),
'ERC721: approved query for nonexistent token'
);
return _tokenApprovals[tokenId];
}
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);
}
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
'ERC721: transfer caller is not owner nor approved'
);
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, '');
}
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);
}
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'
);
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
returns (bool)
{
require(
_exists(tokenId),
'ERC721: operator query for nonexistent token'
);
address owner = ERC721.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
ERC721.isApprovedForAll(owner, spender));
}
d*
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, '');
}
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'
);
}
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), 'ERC721: mint to the zero address');
require(!_exists(tokenId), 'ERC721: token already minted');
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal virtual {
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
function _burn(uint256 tokenId) internal virtual {
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
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);
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal
virtual
{
require(
_exists(tokenId),
'ERC721Metadata: URI set of nonexistent token'
);
_tokenURIs[tokenId] = _tokenURI;
}
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (!to.isContract()) {
return true;
}
bytes memory returndata =
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (!to.isContract()) {
return true;
}
bytes memory returndata =
to.functionCall(
abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
),
'ERC721: transfer to non ERC721Receiver implementer'
);
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
}
) internal virtual {}
}
| 7,815,579 | [
1,
8867,
358,
1375,
3890,
24,
12,
79,
24410,
581,
5034,
2932,
265,
654,
39,
27,
5340,
8872,
12,
2867,
16,
2867,
16,
11890,
5034,
16,
3890,
2225,
3719,
68,
1492,
848,
506,
2546,
12700,
487,
1375,
45,
654,
39,
27,
5340,
12952,
12,
20,
2934,
265,
654,
39,
27,
5340,
8872,
18,
9663,
68,
9408,
628,
10438,
1758,
358,
3675,
261,
7924,
25121,
13,
444,
434,
16199,
2430,
6057,
25121,
2874,
628,
1147,
3258,
358,
3675,
25937,
9408,
628,
1147,
1599,
358,
20412,
1758,
9408,
628,
3410,
358,
3726,
6617,
4524,
3155,
508,
3155,
3273,
4055,
2874,
364,
1147,
24565,
3360,
3699,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
95,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
565,
1450,
6057,
25121,
694,
364,
6057,
25121,
694,
18,
5487,
694,
31,
203,
565,
1450,
6057,
25121,
863,
364,
6057,
25121,
863,
18,
5487,
774,
1887,
863,
31,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
203,
565,
1731,
24,
3238,
5381,
389,
654,
39,
27,
5340,
67,
27086,
20764,
273,
374,
92,
23014,
70,
27,
69,
3103,
31,
203,
203,
565,
2874,
12,
2867,
516,
6057,
25121,
694,
18,
5487,
694,
13,
3238,
389,
4505,
5157,
31,
203,
203,
565,
6057,
25121,
863,
18,
5487,
774,
1887,
863,
3238,
389,
2316,
5460,
414,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
1758,
13,
3238,
389,
2316,
12053,
4524,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
1426,
3719,
3238,
389,
9497,
12053,
4524,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
203,
565,
533,
3238,
389,
7175,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
533,
13,
3238,
389,
2316,
1099,
2520,
31,
203,
203,
565,
533,
3238,
389,
1969,
3098,
31,
203,
203,
565,
1731,
24,
3238,
5381,
389,
18865,
67,
734,
67,
654,
39,
27,
5340,
273,
374,
92,
3672,
1077,
8204,
4315,
31,
203,
203,
565,
1731,
24,
3238,
5381,
389,
18865,
67,
734,
67,
654,
39,
27,
5340,
67,
22746,
273,
374,
92,
25,
70,
25,
73,
24347,
74,
31,
203,
203,
565,
1731,
24,
3238,
5381,
389,
18865,
67,
734,
2
]
|
/**
*Submitted for verification at Etherscan.io on 2020-01-13
*/
pragma solidity ^0.5.13;
library SafeMath {
function add(uint256 a,uint256 b)internal pure returns(uint256){uint256 c=a+b; require(c>=a); return c;}
function sub(uint256 a,uint256 b)internal pure returns(uint256){require(b<=a);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);return c;}
function div(uint256 a,uint256 b)internal pure returns(uint256){require(b>0);uint256 c=a/b;return c;}}
interface Out{
function mint(address w,uint256 a)external returns(bool);
function burn(address w,uint256 a)external returns(bool);
function register(address a,address b)external returns(bool);
function balanceOf(address account)external view returns(uint256);}
contract ESCROW{
using SafeMath for uint256;
address private rot=0x45F2aB0ca2116b2e1a70BF5e13293947b25d0272;
address private reg=0x28515e3a4932c3a780875D329FDA8E2C93B79E43;
mapping(address => uint256) public price;
mapping(address => uint256) public amount;
function toPayable(address a)internal pure returns(address payable){return address(uint160(a));}
function setEscrow(uint256 p,uint256 a)public returns(bool){ //inject PUBLIC FUNC TO EXTERNAL
require(Out(rot).balanceOf(msg.sender) >= a);
require(p>10**14);price[msg.sender]=p;amount[msg.sender]=a;return true;}
function payEscrow(address w)public payable returns(bool){require(msg.value>10**14); //inject PUBLIC FUNC TO EXTERNAL
uint256 gam=(msg.value.mul(10**18)).div(price[w]);
require(Out(rot).balanceOf(w) >= amount[w] && amount[w] >= gam &&
Out(reg).register(msg.sender,w) && Out(rot).mint(msg.sender,gam) && Out(rot).burn(w,gam));
amount[w]=amount[w].sub(gam);toPayable(w).transfer(msg.value);return true;}
function geInfo(address n)public view returns(uint256,uint256){return(price[n],amount[n]);} //inject PUBLIC FUNC TO EXTERNAL
function()external{revert();}} | inject PUBLIC FUNC TO EXTERNAL
| function geInfo(address n)public view returns(uint256,uint256){return(price[n],amount[n]);} | 5,524,477 | [
1,
22170,
17187,
478,
21163,
8493,
5675,
11702,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
8244,
966,
12,
2867,
290,
13,
482,
1476,
1135,
12,
11890,
5034,
16,
11890,
5034,
15329,
2463,
12,
8694,
63,
82,
6487,
8949,
63,
82,
19226,
97,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x0E25ddbc589C67d75cc3Bc5aA82b77d387f1152a/sources/contracts/vikingsSign.sol | Standard mint function | function mint(uint256 amount) public payable {
require(saleActive, "sale_is_closed");
require(amount <= 20, "exceeded_max_mint_amount");
require(totalSupply() + amount <= MAX_SUPPLY, "out_of_stock");
require(msg.value == price * amount, "insufficient_eth");
for(uint256 i; i < amount; i++){
_safeMint(msg.sender, totalSupply() + 1);
}
}
| 3,213,680 | [
1,
8336,
312,
474,
445,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
312,
474,
12,
11890,
5034,
3844,
13,
1071,
8843,
429,
288,
203,
3639,
2583,
12,
87,
5349,
3896,
16,
315,
87,
5349,
67,
291,
67,
12204,
8863,
203,
540,
203,
3639,
2583,
12,
8949,
1648,
4200,
16,
315,
338,
5816,
67,
1896,
67,
81,
474,
67,
8949,
8863,
203,
3639,
2583,
12,
4963,
3088,
1283,
1435,
397,
3844,
1648,
4552,
67,
13272,
23893,
16,
315,
659,
67,
792,
67,
15381,
8863,
203,
3639,
2583,
12,
3576,
18,
1132,
422,
6205,
380,
3844,
16,
315,
2679,
11339,
67,
546,
8863,
203,
203,
3639,
364,
12,
11890,
5034,
277,
31,
277,
411,
3844,
31,
277,
27245,
95,
203,
5411,
389,
4626,
49,
474,
12,
3576,
18,
15330,
16,
2078,
3088,
1283,
1435,
397,
404,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.24;
// File: contracts/ERC223/Receiver_Interface.sol
/*
* Contract that is working with ERC223 tokens
*/
contract ContractReceiver {
struct TKN {
address sender;
uint value;
bytes data;
bytes4 sig;
}
function tokenFallback(address _from, uint _value, bytes _data) public pure {
TKN memory tkn;
tkn.sender = _from;
tkn.value = _value;
tkn.data = _data;
uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24);
tkn.sig = bytes4(u);
/* tkn variable is analogue of msg variable of Ether transaction
* tkn.sender is person who initiated this token transaction (analogue of msg.sender)
* tkn.value the number of tokens that were sent (analogue of msg.value)
* tkn.data is data of token transaction (analogue of msg.data)
* tkn.sig is 4 bytes signature of function
* if data of token transaction is a function execution
*/
}
}
// File: contracts/ERC223/ERC223_Interface.sol
/**
* ERC223 token by Dexaran
*
* https://github.com/Dexaran/ERC223-token-standard
*
* NOTE: original event was:
* event Transfer(address indexed from, address indexed to, uint value, bytes indexed data);
* however 'bytes indexed data' was replaced with 'bytes data' because of this issue with truffle tests:
* https://github.com/trufflesuite/truffle/issues/405
*
*/
contract ERC223 {
uint public totalSupply;
function balanceOf(address who) public view returns (uint);
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function decimals() public view returns (uint8 _decimals);
function totalSupply() public view returns (uint256 _supply);
function transfer(address to, uint value) public returns (bool ok);
function transfer(address to, uint value, bytes data) public returns (bool ok);
function transfer(address to, uint value, bytes data, string custom_fallback) public returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value, bytes data);
}
// File: contracts/ERC223/ERC223_Token.sol
/**
* ERC223 token by Dexaran
*
* https://github.com/Dexaran/ERC223-token-standard
*/
/* https://github.com/LykkeCity/EthereumApiDotNetCore/blob/master/src/ContractBuilder/contracts/token/SafeMath.sol */
contract SafeMath {
uint256 constant public MAX_UINT256 =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
function safeAdd(uint256 x, uint256 y) pure internal returns (uint256 z) {
if (x > MAX_UINT256 - y) revert();
return x + y;
}
function safeSub(uint256 x, uint256 y) pure internal returns (uint256 z) {
if (x < y) revert();
return x - y;
}
function safeMul(uint256 x, uint256 y) pure internal returns (uint256 z) {
if (y == 0) return 0;
if (x > MAX_UINT256 / y) revert();
return x * y;
}
}
contract ERC223Token is ERC223, SafeMath {
mapping(address => uint) balances;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
// Function to access name of token .
function name() public view returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() public view returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() public view returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() public view returns (uint256 _totalSupply) {
return totalSupply;
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) {
if(isContract(_to)) {
if (balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = safeSub(balanceOf(msg.sender), _value);
balances[_to] = safeAdd(balanceOf(_to), _value);
assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data));
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data) public returns (bool success) {
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address _to, uint _value) public returns (bool success) {
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
//function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
if (balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = safeSub(balanceOf(msg.sender), _value);
balances[_to] = safeAdd(balanceOf(_to), _value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
if (balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = safeSub(balanceOf(msg.sender), _value);
balances[_to] = safeAdd(balanceOf(_to), _value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
}
// File: contracts\ERC223\TokenMintERC223Token.sol
/**
* @title Standard ERC223 token
* @author TokenMint.io
*
* @dev Implementation of the basic standard token. For full specification see:
* https://github.com/Dexaran/ERC223-token-standard
*/
contract TokenMintERC223Token is ERC223Token {
constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply, address feeReceiver, address tokenOwnerAccount) public payable {
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _totalSupply;
// set sender as owner of all tokens
balances[tokenOwnerAccount] = totalSupply;
emit Transfer(address(0), tokenOwnerAccount, totalSupply, "");
// pay for service fee for contract deployment
feeReceiver.transfer(msg.value);
}
} | * @title Standard ERC223 token @author TokenMint.io @dev Implementation of the basic standard token. For full specification see:/ | contract TokenMintERC223Token is ERC223Token {
constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply, address feeReceiver, address tokenOwnerAccount) public payable {
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _totalSupply;
balances[tokenOwnerAccount] = totalSupply;
emit Transfer(address(0), tokenOwnerAccount, totalSupply, "");
feeReceiver.transfer(msg.value);
}
} | 6,761,853 | [
1,
8336,
4232,
39,
3787,
23,
1147,
225,
3155,
49,
474,
18,
1594,
225,
25379,
434,
326,
5337,
4529,
1147,
18,
2457,
1983,
7490,
2621,
27824,
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
]
| [
1,
1,
1,
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
]
| [
1,
16351,
3155,
49,
474,
654,
39,
3787,
23,
1345,
353,
4232,
39,
3787,
23,
1345,
288,
203,
203,
203,
225,
3885,
12,
1080,
389,
529,
16,
533,
389,
7175,
16,
2254,
28,
389,
31734,
16,
2254,
5034,
389,
4963,
3088,
1283,
16,
1758,
14036,
12952,
16,
1758,
1147,
5541,
3032,
13,
1071,
8843,
429,
288,
203,
565,
508,
273,
389,
529,
31,
203,
565,
3273,
273,
389,
7175,
31,
203,
565,
15105,
273,
389,
31734,
31,
203,
565,
2078,
3088,
1283,
273,
389,
4963,
3088,
1283,
31,
203,
203,
565,
324,
26488,
63,
2316,
5541,
3032,
65,
273,
2078,
3088,
1283,
31,
203,
565,
3626,
12279,
12,
2867,
12,
20,
3631,
1147,
5541,
3032,
16,
2078,
3088,
1283,
16,
1408,
1769,
203,
203,
565,
14036,
12952,
18,
13866,
12,
3576,
18,
1132,
1769,
203,
225,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/44787/0x76Eb2820207313AFf098478A64996ca38C6052ff/sources/contracts/CarbonPathAdmin.sol | @notice helper function to calculate cpFee @param amount base amount @param cpFeePercentage fee percentage @return cpFee fee based on the cpFeePercentage | function _calculateCPFee(uint256 amount, uint256 cpFeePercentage) private pure returns (uint256) {
return (amount * cpFeePercentage) / BASE_PERCENTAGE;
}
| 16,956,775 | [
1,
4759,
445,
358,
4604,
3283,
14667,
225,
3844,
1026,
3844,
225,
3283,
14667,
16397,
14036,
11622,
327,
3283,
14667,
14036,
2511,
603,
326,
3283,
14667,
16397,
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,
389,
11162,
4258,
14667,
12,
11890,
5034,
3844,
16,
2254,
5034,
3283,
14667,
16397,
13,
3238,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
261,
8949,
380,
3283,
14667,
16397,
13,
342,
10250,
67,
3194,
19666,
2833,
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
]
|
./full_match/43114/0x8229Ed6519456845304E343dEB5f9AEEfc5f1418/sources/project_/contracts/libraries/IterMap.sol | * @title IterMap Library @author ehrab @notice Modified version of the IterMap.sol from Solidity documentation @dev Additions made: modify structs, modify func args, add struct/ | library IterableMapping {
function insert(itmap storage self, bytes32 key, Collection memory value) internal returns (bool replaced) {
uint keyIndex = self.data[key].keyIndex;
self.data[key].value = value;
if (keyIndex > 0)
return true;
else {
keyIndex = self.keys.length;
self.keys.push();
self.data[key].keyIndex = keyIndex + 1;
self.keys[keyIndex].key = key;
self.size++;
return false;
}
}
function insert(itmap storage self, bytes32 key, Collection memory value) internal returns (bool replaced) {
uint keyIndex = self.data[key].keyIndex;
self.data[key].value = value;
if (keyIndex > 0)
return true;
else {
keyIndex = self.keys.length;
self.keys.push();
self.data[key].keyIndex = keyIndex + 1;
self.keys[keyIndex].key = key;
self.size++;
return false;
}
}
function remove(itmap storage self, bytes32 key) internal returns (bool success) {
uint keyIndex = self.data[key].keyIndex;
if (keyIndex == 0)
return false;
delete self.data[key];
self.keys[keyIndex - 1].deleted = true;
self.size --;
}
function contains(itmap storage self, bytes32 key) internal view returns (bool) {
return self.data[key].keyIndex > 0;
}
function iterateStart(itmap storage self) internal view returns (Iterator) {
return iteratorSkipDeleted(self, 0);
}
function iterateValid(itmap storage self, Iterator iterator) internal view returns (bool) {
return Iterator.unwrap(iterator) < self.keys.length;
}
function iterateNext(itmap storage self, Iterator iterator) internal view returns (Iterator) {
return iteratorSkipDeleted(self, Iterator.unwrap(iterator) + 1);
}
function iterateGet(itmap storage self, Iterator iterator) internal view returns (bytes32 key, IndexNValue memory data) {
uint keyIndex = Iterator.unwrap(iterator);
key = self.keys[keyIndex].key;
data = self.data[key];
}
function iteratorSkipDeleted(itmap storage self, uint keyIndex) private view returns (Iterator) {
while (keyIndex < self.keys.length && self.keys[keyIndex].deleted)
keyIndex++;
return Iterator.wrap(keyIndex);
}
} | 4,582,363 | [
1,
2360,
863,
18694,
225,
20124,
20727,
225,
21154,
1177,
434,
326,
3016,
863,
18,
18281,
628,
348,
7953,
560,
7323,
225,
1436,
5029,
7165,
30,
5612,
8179,
16,
5612,
1326,
833,
16,
527,
1958,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
12083,
6725,
3233,
288,
203,
202,
202,
915,
2243,
12,
305,
1458,
2502,
365,
16,
1731,
1578,
498,
16,
2200,
3778,
460,
13,
2713,
1135,
261,
6430,
8089,
13,
288,
203,
9506,
202,
11890,
498,
1016,
273,
365,
18,
892,
63,
856,
8009,
856,
1016,
31,
203,
9506,
202,
2890,
18,
892,
63,
856,
8009,
1132,
273,
460,
31,
203,
9506,
202,
430,
261,
856,
1016,
405,
374,
13,
203,
25083,
202,
2463,
638,
31,
203,
9506,
202,
12107,
288,
203,
25083,
202,
856,
1016,
273,
365,
18,
2452,
18,
2469,
31,
203,
25083,
202,
2890,
18,
2452,
18,
6206,
5621,
203,
25083,
202,
2890,
18,
892,
63,
856,
8009,
856,
1016,
273,
498,
1016,
397,
404,
31,
203,
25083,
202,
2890,
18,
2452,
63,
856,
1016,
8009,
856,
273,
498,
31,
203,
25083,
202,
2890,
18,
1467,
9904,
31,
203,
25083,
202,
2463,
629,
31,
203,
9506,
202,
97,
203,
202,
202,
97,
203,
203,
202,
202,
915,
2243,
12,
305,
1458,
2502,
365,
16,
1731,
1578,
498,
16,
2200,
3778,
460,
13,
2713,
1135,
261,
6430,
8089,
13,
288,
203,
9506,
202,
11890,
498,
1016,
273,
365,
18,
892,
63,
856,
8009,
856,
1016,
31,
203,
9506,
202,
2890,
18,
892,
63,
856,
8009,
1132,
273,
460,
31,
203,
9506,
202,
430,
261,
856,
1016,
405,
374,
13,
203,
25083,
202,
2463,
638,
31,
203,
9506,
202,
12107,
288,
203,
25083,
202,
856,
1016,
273,
365,
18,
2452,
18,
2469,
31,
203,
25083,
202,
2890,
18,
2452,
18,
6206,
5621,
203,
25083,
2
]
|
pragma solidity ^0.4.25;
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 transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function withdrawAllEther() public onlyOwner { //to be executed on contract close
_owner.transfer(this.balance);
}
/**
* @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;
}
}
contract blackJack is Ownable {
mapping (uint => uint) cardsPower;
constructor() {
cardsPower[0] = 11; // aces
cardsPower[1] = 2;
cardsPower[2] = 3;
cardsPower[3] = 4;
cardsPower[4] = 5;
cardsPower[5] = 6;
cardsPower[6] = 7;
cardsPower[7] = 8;
cardsPower[8] = 9;
cardsPower[9] = 10;
cardsPower[10] = 10; // j
cardsPower[11] = 10; // q
cardsPower[12] = 10; // k
}
uint minBet = 0.01 ether;
uint maxBet = 0.1 ether;
uint requiredHouseBankroll = 3 ether; //use math of maxBet * 300
uint autoWithdrawBuffer = 1 ether; // only automatically withdraw if requiredHouseBankroll is exceeded by this amount
mapping (address => bool) public isActive;
mapping (address => bool) public isPlayerActive;
mapping (address => uint) public betAmount;
mapping (address => uint) public gamestatus; //1 = Player Turn, 2 = Player Blackjack!, 3 = Dealer Blackjack!, 4 = Push, 5 = Game Finished. Bets resolved.
mapping (address => uint) public payoutAmount;
mapping (address => uint) dealTime;
mapping (address => uint) blackJackHouseProhibited;
mapping (address => uint[]) playerCards;
mapping (address => uint[]) houseCards;
mapping (address => bool) playerExists; //check whether the player has played before, if so, he must have a playerHand
function card2PowerConverter(uint[] cards) internal view returns (uint) { //converts an array of cards to their actual power. 1 is 1 or 11 (Ace)
uint powerMax = 0;
uint aces = 0; //count number of aces
uint power;
for (uint i = 0; i < cards.length; i++) {
power = cardsPower[(cards[i] + 13) % 13];
powerMax += power;
if (power == 11) {
aces += 1;
}
}
if (powerMax > 21) { //remove 10 for each ace until under 21, if possible.
for (uint i2=0; i2<aces; i2++) {
powerMax-=10;
if (powerMax <= 21) {
break;
}
}
}
return uint(powerMax);
}
//PRNG / RANDOM NUMBER GENERATION. REPLACE THIS AS NEEDED WITH MORE EFFICIENT RNG
uint randNonce = 0;
function randgenNewHand() internal returns(uint,uint,uint) { //returns 3 numbers from 0-51.
//If new hand, generate 3 cards. If not, generate just 1.
randNonce++;
uint a = uint(keccak256(abi.encodePacked(now, msg.sender, randNonce))) % 52;
randNonce++;
uint b = uint(keccak256(abi.encodePacked(now, msg.sender, randNonce))) % 52;
randNonce++;
uint c = uint(keccak256(abi.encodePacked(now, msg.sender, randNonce))) % 52;
return (a,b,c);
}
function randgen() internal returns(uint) { //returns number from 0-51.
//If new hand, generate 3 cards. If not, generate just 1.
randNonce++;
return uint(keccak256(abi.encodePacked(now, msg.sender, randNonce))) % 52; //range: 0-51
}
modifier requireHandActive(bool truth) {
require(isActive[msg.sender] == truth);
_;
}
modifier requirePlayerActive(bool truth) {
require(isPlayerActive[msg.sender] == truth);
_;
}
function _play() public payable { //TEMP: Care, public.. ensure this is the public point of entry to play. Only allow 1 point of entry.
//check whether or not player has played before
if (playerExists[msg.sender]) {
require(isActive[msg.sender] == false);
}
else {
playerExists[msg.sender] = true;
}
require(msg.value >= minBet); //now check player has sent ether within betting requirements
require(msg.value <= maxBet); //TODO Do unit testing to ensure ETH is not deducted if previous conditional fails
//Now all checks have passed, the betting can proceed
uint a; //generate 3 cards, 2 for player, 1 for the house
uint b;
uint c;
(a,b,c) = randgenNewHand();
gamestatus[msg.sender] = 1;
payoutAmount[msg.sender] = 0;
isActive[msg.sender] = true;
isPlayerActive[msg.sender] = true;
betAmount[msg.sender] = msg.value;
dealTime[msg.sender] = now;
playerCards[msg.sender] = new uint[](0);
playerCards[msg.sender].push(a);
playerCards[msg.sender].push(b);
houseCards[msg.sender] = new uint[](0);
houseCards[msg.sender].push(c);
isBlackjack();
withdrawToOwnerCheck();
//TODO UPDATE playerHand correctly and also commence play utilizing game logic
//PLACEHOLDER FOR THE GAMBLING, DELEGATE TO OTHER FUNCTIONS SOME OF THE GAME LOGIC HERE
//END PLACEHOLDER, REMOVE THESE COMMENTS
}
function _Hit() public requireHandActive(true) requirePlayerActive(true) { //both the hand and player turn must be active in order to hit
uint a=randgen(); //generate a new card
playerCards[msg.sender].push(a);
checkGameState();
}
function _Stand() public requireHandActive(true) requirePlayerActive(true) { //both the hand and player turn must be active in order to stand
isPlayerActive[msg.sender] = false; //Player ends their turn, now dealer's turn
checkGameState();
}
function checkGameState() internal requireHandActive(true) { //checks game state, processing it as needed. Should be called after any card is dealt or action is made (eg: stand).
//IMPORTANT: Make sure this function is NOT called in the event of a blackjack. Blackjack should calculate things separately
if (isPlayerActive[msg.sender] == true) {
uint handPower = card2PowerConverter(playerCards[msg.sender]);
if (handPower > 21) { //player busted
processHandEnd(false);
}
else if (handPower == 21) { //autostand. Ensure same logic in stand is used
isPlayerActive[msg.sender] = false;
dealerHit();
}
else if (handPower <21) {
//do nothing, player is allowed another action
}
}
else if (isPlayerActive[msg.sender] == false) {
dealerHit();
}
}
function dealerHit() internal requireHandActive(true) requirePlayerActive(false) { //dealer hits after player ends turn legally. Nounces can be incrimented with hits until turn finished.
uint[] storage houseCardstemp = houseCards[msg.sender];
uint[] storage playerCardstemp = playerCards[msg.sender];
uint tempCard;
while (card2PowerConverter(houseCardstemp) < 17) { //keep hitting on the same block for everything under 17. Same block is fine for dealer due to Nounce increase
//The house cannot cheat here since the player is forcing the NEXT BLOCK to be the source of randomness for all hits, and this contract cannot voluntarily skip blocks.
tempCard = randgen();
if (blackJackHouseProhibited[msg.sender] != 0) {
while (cardsPower[(tempCard + 13) % 13] == blackJackHouseProhibited[msg.sender]) { //don't deal the first card as prohibited card
tempCard = randgen();
}
blackJackHouseProhibited[msg.sender] = 0;
}
houseCardstemp.push(tempCard);
}
//First, check if the dealer busted for an auto player win
if (card2PowerConverter(houseCardstemp) > 21 ) {
processHandEnd(true);
}
//If not, we do win logic here, since this is the natural place to do it (after dealer hitting). 3 Scenarios are possible... =>
if (card2PowerConverter(playerCardstemp) == card2PowerConverter(houseCardstemp)) {
//push, return bet
msg.sender.transfer(betAmount[msg.sender]);
payoutAmount[msg.sender]=betAmount[msg.sender];
gamestatus[msg.sender] = 4;
isActive[msg.sender] = false; //let's declare this manually only here, since processHandEnd is not called. Not needed for other scenarios.
}
else if (card2PowerConverter(playerCardstemp) > card2PowerConverter(houseCardstemp)) {
//player hand has more strength
processHandEnd(true);
}
else {
//only one possible scenario remains.. dealer hand has more strength
processHandEnd(false);
}
}
function processHandEnd(bool _win) internal { //hand is over and win is either true or false, now process it
if (_win == false) {
//do nothing, as player simply lost
}
else if (_win == true) {
uint winAmount = betAmount[msg.sender] * 2;
msg.sender.transfer(winAmount);
payoutAmount[msg.sender]=winAmount;
}
gamestatus[msg.sender] = 5;
isActive[msg.sender] = false;
}
//TODO: Log an event after hand, showing outcome
function isBlackjack() internal { //fill this function later to check both player and dealer for a blackjack after _play is called, then process
//4 possibilities: dealer blackjack, player blackjack (paying 3:2), both blackjack (push), no blackjack
//copy processHandEnd for remainder
blackJackHouseProhibited[msg.sender]=0; //set to 0 incase it already has a value
bool houseIsBlackjack = false;
bool playerIsBlackjack = false;
//First thing: For dealer check, ensure if dealer doesn't get blackjack they are prohibited from their first hit resulting in a blackjack
uint housePower = card2PowerConverter(houseCards[msg.sender]); //read the 1 and only house card, if it's 11 or 10, then deal temporary new card for bj check
if (housePower == 10 || housePower == 11) {
uint _card = randgen();
if (housePower == 10) {
if (cardsPower[_card] == 11) {
//dealer has blackjack, process
houseCards[msg.sender].push(_card); //push card as record, since game is now over
houseIsBlackjack = true;
}
else {
blackJackHouseProhibited[msg.sender]=uint(11); //ensure dealerHit doesn't draw this powerMax
}
}
else if (housePower == 11) {
if (cardsPower[_card] == 10) { //all 10s
//dealer has blackjack, process
houseCards[msg.sender].push(_card); //push card as record, since game is now over
houseIsBlackjack = true;
}
else{
blackJackHouseProhibited[msg.sender]=uint(10); //ensure dealerHit doesn't draw this powerMax
}
}
}
//Second thing: Check if player has blackjack
uint playerPower = card2PowerConverter(playerCards[msg.sender]);
if (playerPower == 21) {
playerIsBlackjack = true;
}
//Third thing: Return all four possible outcomes: Win 1.5x, Push, Loss, or Nothing (no blackjack, continue game)
if (playerIsBlackjack == false && houseIsBlackjack == false) {
//do nothing. Call this first since it's the most likely outcome
}
else if (playerIsBlackjack == true && houseIsBlackjack == false) {
//Player has blackjack, dealer doesn't, reward 1.5x bet (plus bet return)
uint winAmount = betAmount[msg.sender] * 5/2;
msg.sender.transfer(winAmount);
payoutAmount[msg.sender] = betAmount[msg.sender] * 5/2;
gamestatus[msg.sender] = 2;
isActive[msg.sender] = false;
}
else if (playerIsBlackjack == true && houseIsBlackjack == true) {
//Both player and dealer have blackjack. Push - return bet only
uint winAmountPush = betAmount[msg.sender];
msg.sender.transfer(winAmountPush);
payoutAmount[msg.sender] = winAmountPush;
gamestatus[msg.sender] = 4;
isActive[msg.sender] = false;
}
else if (playerIsBlackjack == false && houseIsBlackjack == true) {
//Only dealer has blackjack, player loses
gamestatus[msg.sender] = 3;
isActive[msg.sender] = false;
}
}
function readCards() external view returns(uint[],uint[]) { //returns the cards in play, as an array of playercards, then houseCards
return (playerCards[msg.sender],houseCards[msg.sender]);
}
function readPower() external view returns(uint, uint) { //returns current card power of player and house
return (card2PowerConverter(playerCards[msg.sender]),card2PowerConverter(houseCards[msg.sender]));
}
function donateEther() public payable {
//do nothing
}
function withdrawToOwnerCheck() internal { //auto call this
//Contract profit withdrawal to the current contract owner is disabled unless contract balance exceeds requiredHouseBankroll
//If this condition is met, requiredHouseBankroll must still always remain in the contract and cannot be withdrawn.
uint houseBalance = address(this).balance;
if (houseBalance > requiredHouseBankroll + autoWithdrawBuffer) { //see comments at top of contract
uint permittedWithdraw = houseBalance - requiredHouseBankroll; //leave the required bankroll behind, withdraw the rest
address _owner = owner();
_owner.transfer(permittedWithdraw);
}
}
} | If not, we do win logic here, since this is the natural place to do it (after dealer hitting). 3 Scenarios are possible... =>push, return bet | if (card2PowerConverter(playerCardstemp) == card2PowerConverter(houseCardstemp)) {
msg.sender.transfer(betAmount[msg.sender]);
payoutAmount[msg.sender]=betAmount[msg.sender];
gamestatus[msg.sender] = 4;
}
| 13,126,682 | [
1,
2047,
486,
16,
732,
741,
5657,
4058,
2674,
16,
3241,
333,
353,
326,
15145,
3166,
358,
741,
518,
261,
5205,
15448,
6800,
1787,
2934,
890,
2850,
18087,
854,
3323,
2777,
516,
6206,
16,
327,
2701,
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,
3639,
309,
261,
3327,
22,
13788,
5072,
12,
14872,
6415,
19781,
84,
13,
422,
5270,
22,
13788,
5072,
12,
13028,
6415,
19781,
84,
3719,
288,
203,
5411,
1234,
18,
15330,
18,
13866,
12,
70,
278,
6275,
63,
3576,
18,
15330,
19226,
203,
5411,
293,
2012,
6275,
63,
3576,
18,
15330,
65,
33,
70,
278,
6275,
63,
3576,
18,
15330,
15533,
203,
5411,
23411,
395,
996,
63,
3576,
18,
15330,
65,
273,
1059,
31,
203,
3639,
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
]
|
./partial_match/56/0xF3AEdBF38426ecE22031a6D0b48e75cd0066d438/sources/TimeLockJULD.sol | Wednesday, February 17, 2021 10:00:00 AM UTC
| stakeEndDate= 1613556000; | 11,278,792 | [
1,
59,
329,
23712,
2881,
16,
5782,
2848,
24335,
8043,
16,
26599,
21,
1728,
30,
713,
30,
713,
20653,
9951,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
384,
911,
24640,
33,
2872,
3437,
2539,
26,
3784,
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
]
|
./full_match/1/0xb58665D962327909b94538720249b1DDDc1E3644/sources/contracts/NewBridge.sol | Send funds to multisig account, and emit a SwapToken event for emission to the Secret Network @param _recipient: The intended recipient's Secret Network address. @param _amount: The amount of ENG tokens to be itemized. @param _tokenAddress: The address of the token being swapped @param _toSCRT: Amount of SCRT to be minted - will be deducted from the amount swapped/ if (ercToken.allowance(investorContract, address(this)) < _amount) { require(token.approve(address(recipient), uint(-1)), "Approve has failed"); } | function swapToken(bytes memory _recipient, uint256 _amount, address _tokenAddress, uint256 _toSCRT)
public
notPaused()
tokenWhitelisted(_tokenAddress)
isSecretAddress(_recipient)
isNotGoingAboveLimit(_tokenAddress, _amount)
{
IERC20 ercToken = IERC20(_tokenAddress);
IInvestor investor = IInvestor(investorContract);
require(_amount >= tokenWhitelist[_tokenAddress], "Require transfer greater than minimum");
tokenBalances[_tokenAddress] = tokenBalances[_tokenAddress] + _amount;
if (ercToken.allowance(address(this), investorContract) < _amount) {
ercToken.safeApprove(investorContract, uint256(-1));
}
ercToken.safeTransferFrom(msg.sender, address(this), _amount);
investor.investToken(_tokenAddress, _amount);
emit SwapToken(
msg.sender,
_recipient,
_amount,
_tokenAddress,
_toSCRT
);
}
| 8,357,763 | [
1,
3826,
284,
19156,
358,
22945,
360,
2236,
16,
471,
3626,
279,
12738,
1345,
871,
364,
801,
19710,
358,
326,
7875,
5128,
225,
389,
20367,
30,
1021,
12613,
8027,
1807,
7875,
5128,
1758,
18,
225,
389,
8949,
30,
1021,
3844,
434,
17979,
2430,
358,
506,
761,
1235,
18,
225,
389,
2316,
1887,
30,
1021,
1758,
434,
326,
1147,
3832,
7720,
1845,
225,
389,
869,
2312,
12185,
30,
16811,
434,
348,
5093,
56,
358,
506,
312,
474,
329,
300,
903,
506,
11140,
853,
329,
628,
326,
3844,
7720,
1845,
19,
309,
261,
12610,
1345,
18,
5965,
1359,
12,
5768,
395,
280,
8924,
16,
1758,
12,
2211,
3719,
411,
389,
8949,
13,
288,
377,
2583,
12,
2316,
18,
12908,
537,
12,
2867,
12,
20367,
3631,
2254,
19236,
21,
13,
3631,
315,
12053,
537,
711,
2535,
8863,
289,
2,
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,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7720,
1345,
12,
3890,
3778,
389,
20367,
16,
2254,
5034,
389,
8949,
16,
1758,
389,
2316,
1887,
16,
2254,
5034,
389,
869,
2312,
12185,
13,
203,
565,
1071,
203,
565,
486,
28590,
1435,
203,
565,
1147,
18927,
329,
24899,
2316,
1887,
13,
203,
565,
353,
5207,
1887,
24899,
20367,
13,
203,
565,
8827,
5741,
310,
25477,
3039,
24899,
2316,
1887,
16,
389,
8949,
13,
203,
565,
288,
203,
3639,
467,
654,
39,
3462,
6445,
71,
1345,
273,
467,
654,
39,
3462,
24899,
2316,
1887,
1769,
203,
3639,
467,
3605,
395,
280,
2198,
395,
280,
273,
467,
3605,
395,
280,
12,
5768,
395,
280,
8924,
1769,
203,
203,
3639,
2583,
24899,
8949,
1545,
1147,
18927,
63,
67,
2316,
1887,
6487,
315,
8115,
7412,
6802,
2353,
5224,
8863,
203,
203,
3639,
1147,
38,
26488,
63,
67,
2316,
1887,
65,
273,
1147,
38,
26488,
63,
67,
2316,
1887,
65,
397,
389,
8949,
31,
203,
203,
203,
3639,
309,
261,
12610,
1345,
18,
5965,
1359,
12,
2867,
12,
2211,
3631,
2198,
395,
280,
8924,
13,
411,
389,
8949,
13,
288,
203,
5411,
6445,
71,
1345,
18,
4626,
12053,
537,
12,
5768,
395,
280,
8924,
16,
2254,
5034,
19236,
21,
10019,
203,
3639,
289,
203,
203,
3639,
6445,
71,
1345,
18,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
8949,
1769,
203,
203,
3639,
2198,
395,
280,
18,
5768,
395,
1345,
24899,
2316,
1887,
16,
389,
8949,
1769,
203,
203,
3639,
3626,
12738,
1345,
12,
203,
5411,
1234,
18,
15330,
16,
203,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/introspection/IERC165.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
interface IAddressRegistry {
function xyz() external view returns (address);
function bundleMarketplace() external view returns (address);
function factory() external view returns (address);
function privateFactory() external view returns (address);
function artFactory() external view returns (address);
function privateArtFactory() external view returns (address);
function tokenRegistry() external view returns (address);
function priceFeed() external view returns (address);
}
interface IBundleMarketplace {
function validateItemSold(
address,
uint256,
uint256
) external;
}
interface INFTFactory {
function exists(address) external view returns (bool);
}
interface ITokenRegistry {
function enabled(address) external view returns (bool);
}
interface IPriceFeed {
function wFTM() external view returns (address);
function getPrice(address) external view returns (int256, uint8);
}
contract Marketplace is OwnableUpgradeable, ReentrancyGuardUpgradeable {
using SafeMath for uint256;
using AddressUpgradeable for address payable;
using SafeERC20 for IERC20;
/// @notice Events for the contract
event ItemListed(
address indexed owner,
address indexed nft,
uint256 tokenId,
uint256 quantity,
address payToken,
uint256 pricePerItem,
uint256 startingTime
);
event ItemSold(
address indexed seller,
address indexed buyer,
address indexed nft,
uint256 tokenId,
uint256 quantity,
address payToken,
int256 unitPrice,
uint256 pricePerItem
);
event ItemUpdated(
address indexed owner,
address indexed nft,
uint256 tokenId,
address payToken,
uint256 newPrice
);
event ItemCanceled(
address indexed owner,
address indexed nft,
uint256 tokenId
);
event OfferCreated(
address indexed creator,
address indexed nft,
uint256 tokenId,
uint256 quantity,
address payToken,
uint256 pricePerItem,
uint256 deadline
);
event OfferCanceled(
address indexed creator,
address indexed nft,
uint256 tokenId
);
event UpdatePlatformFee(uint16 platformFee);
event UpdatePlatformFeeRecipient(address payable platformFeeRecipient);
/// @notice Structure for listed items
struct Listing {
uint256 quantity;
address payToken;
uint256 pricePerItem;
uint256 startingTime;
}
/// @notice Structure for offer
struct Offer {
IERC20 payToken;
uint256 quantity;
uint256 pricePerItem;
uint256 deadline;
}
struct CollectionRoyalty {
uint16 royalty;
address creator;
address feeRecipient;
}
bytes4 private constant INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 private constant INTERFACE_ID_ERC1155 = 0xd9b67a26;
/// @notice NftAddress -> Token ID -> Minter
mapping(address => mapping(uint256 => address)) public minters;
/// @notice NftAddress -> Token ID -> Royalty
mapping(address => mapping(uint256 => uint16)) public royalties;
/// @notice NftAddress -> Token ID -> Owner -> Listing item
mapping(address => mapping(uint256 => mapping(address => Listing)))
public listings;
/// @notice NftAddress -> Token ID -> Offerer -> Offer
mapping(address => mapping(uint256 => mapping(address => Offer)))
public offers;
/// @notice Platform fee
uint16 public platformFee;
/// @notice Platform fee receipient
address payable public feeReceipient;
/// @notice NftAddress -> Royalty
mapping(address => CollectionRoyalty) public collectionRoyalties;
/// @notice Address registry
IAddressRegistry public addressRegistry;
modifier onlyMarketplace() {
require(
address(addressRegistry.bundleMarketplace()) == _msgSender(),
"sender must be bundle marketplace"
);
_;
}
modifier isListed(
address _nftAddress,
uint256 _tokenId,
address _owner
) {
Listing memory listing = listings[_nftAddress][_tokenId][_owner];
require(listing.quantity > 0, "not listed item");
_;
}
modifier notListed(
address _nftAddress,
uint256 _tokenId,
address _owner
) {
Listing memory listing = listings[_nftAddress][_tokenId][_owner];
require(listing.quantity == 0, "already listed");
_;
}
modifier validListing(
address _nftAddress,
uint256 _tokenId,
address _owner
) {
Listing memory listedItem = listings[_nftAddress][_tokenId][_owner];
if (IERC165(_nftAddress).supportsInterface(INTERFACE_ID_ERC721)) {
IERC721 nft = IERC721(_nftAddress);
require(nft.ownerOf(_tokenId) == _owner, "not owning item");
} else if (
IERC165(_nftAddress).supportsInterface(INTERFACE_ID_ERC1155)
) {
IERC1155 nft = IERC1155(_nftAddress);
require(
nft.balanceOf(_owner, _tokenId) >= listedItem.quantity,
"not owning item"
);
} else {
revert("invalid nft address");
}
require(_getNow() >= listedItem.startingTime, "item not buyable");
_;
}
modifier offerExists(
address _nftAddress,
uint256 _tokenId,
address _creator
) {
Offer memory offer = offers[_nftAddress][_tokenId][_creator];
require(
offer.quantity > 0 && offer.deadline > _getNow(),
"offer not exists or expired"
);
_;
}
modifier offerNotExists(
address _nftAddress,
uint256 _tokenId,
address _creator
) {
Offer memory offer = offers[_nftAddress][_tokenId][_creator];
require(
offer.quantity == 0 || offer.deadline <= _getNow(),
"offer already created"
);
_;
}
/// @notice Contract initializer
function initialize(address payable _feeRecipient, uint16 _platformFee)
public
initializer
{
platformFee = _platformFee;
feeReceipient = _feeRecipient;
__Ownable_init();
__ReentrancyGuard_init();
}
/// @notice Method for listing NFT
/// @param _nftAddress Address of NFT contract
/// @param _tokenId Token ID of NFT
/// @param _quantity token amount to list (needed for ERC-1155 NFTs, set as 1 for ERC-721)
/// @param _payToken Paying token
/// @param _pricePerItem sale price for each iteam
/// @param _startingTime scheduling for a future sale
function listItem(
address _nftAddress,
uint256 _tokenId,
uint256 _quantity,
address _payToken,
uint256 _pricePerItem,
uint256 _startingTime
) external notListed(_nftAddress, _tokenId, _msgSender()) {
if (IERC165(_nftAddress).supportsInterface(INTERFACE_ID_ERC721)) {
IERC721 nft = IERC721(_nftAddress);
require(nft.ownerOf(_tokenId) == _msgSender(), "not owning item");
require(
nft.isApprovedForAll(_msgSender(), address(this)),
"item not approved"
);
} else if (
IERC165(_nftAddress).supportsInterface(INTERFACE_ID_ERC1155)
) {
IERC1155 nft = IERC1155(_nftAddress);
require(
nft.balanceOf(_msgSender(), _tokenId) >= _quantity,
"must hold enough nfts"
);
require(
nft.isApprovedForAll(_msgSender(), address(this)),
"item not approved"
);
} else {
revert("invalid nft address");
}
require(
_payToken == address(0) ||
(addressRegistry.tokenRegistry() != address(0) &&
ITokenRegistry(addressRegistry.tokenRegistry())
.enabled(_payToken)),
"invalid pay token"
);
listings[_nftAddress][_tokenId][_msgSender()] = Listing(
_quantity,
_payToken,
_pricePerItem,
_startingTime
);
emit ItemListed(
_msgSender(),
_nftAddress,
_tokenId,
_quantity,
_payToken,
_pricePerItem,
_startingTime
);
}
/// @notice Method for canceling listed NFT
function cancelListing(address _nftAddress, uint256 _tokenId)
external
nonReentrant
isListed(_nftAddress, _tokenId, _msgSender())
{
_cancelListing(_nftAddress, _tokenId, _msgSender());
}
/// @notice Method for updating listed NFT
/// @param _nftAddress Address of NFT contract
/// @param _tokenId Token ID of NFT
/// @param _payToken payment token
/// @param _newPrice New sale price for each iteam
function updateListing(
address _nftAddress,
uint256 _tokenId,
address _payToken,
uint256 _newPrice
) external nonReentrant isListed(_nftAddress, _tokenId, _msgSender()) {
Listing storage listedItem = listings[_nftAddress][_tokenId][
_msgSender()
];
if (IERC165(_nftAddress).supportsInterface(INTERFACE_ID_ERC721)) {
IERC721 nft = IERC721(_nftAddress);
require(nft.ownerOf(_tokenId) == _msgSender(), "not owning item");
} else if (
IERC165(_nftAddress).supportsInterface(INTERFACE_ID_ERC1155)
) {
IERC1155 nft = IERC1155(_nftAddress);
require(
nft.balanceOf(_msgSender(), _tokenId) >= listedItem.quantity,
"not owning item"
);
} else {
revert("invalid nft address");
}
require(
_payToken == address(0) ||
(addressRegistry.tokenRegistry() != address(0) &&
ITokenRegistry(addressRegistry.tokenRegistry())
.enabled(_payToken)),
"invalid pay token"
);
listedItem.payToken = _payToken;
listedItem.pricePerItem = _newPrice;
emit ItemUpdated(
_msgSender(),
_nftAddress,
_tokenId,
_payToken,
_newPrice
);
}
/// @notice Method for buying listed NFT
/// @param _nftAddress NFT contract address
/// @param _tokenId TokenId
function buyItem(
address _nftAddress,
uint256 _tokenId,
address payable _owner
)
external
payable
nonReentrant
isListed(_nftAddress, _tokenId, _owner)
validListing(_nftAddress, _tokenId, _owner)
{
Listing memory listedItem = listings[_nftAddress][_tokenId][_owner];
require(listedItem.payToken == address(0), "invalid pay token");
require(
msg.value >= listedItem.pricePerItem.mul(listedItem.quantity),
"insufficient balance to buy"
);
_buyItem(_nftAddress, _tokenId, address(0), _owner);
}
/// @notice Method for buying listed NFT
/// @param _nftAddress NFT contract address
/// @param _tokenId TokenId
function buyItem(
address _nftAddress,
uint256 _tokenId,
address _payToken,
address _owner
)
external
nonReentrant
isListed(_nftAddress, _tokenId, _owner)
validListing(_nftAddress, _tokenId, _owner)
{
Listing memory listedItem = listings[_nftAddress][_tokenId][_owner];
require(listedItem.payToken == _payToken, "invalid pay token");
_buyItem(_nftAddress, _tokenId, _payToken, _owner);
}
function _buyItem(
address _nftAddress,
uint256 _tokenId,
address _payToken,
address _owner
) private {
Listing memory listedItem = listings[_nftAddress][_tokenId][_owner];
uint256 price = listedItem.pricePerItem.mul(listedItem.quantity);
uint256 feeAmount = price.mul(platformFee).div(1e3);
if (_payToken == address(0)) {
(bool feeTransferSuccess, ) = feeReceipient.call{value: feeAmount}(
""
);
require(feeTransferSuccess, "fee transfer failed");
} else {
IERC20(_payToken).safeTransferFrom(
_msgSender(),
feeReceipient,
feeAmount
);
}
address minter = minters[_nftAddress][_tokenId];
uint16 royalty = royalties[_nftAddress][_tokenId];
if (minter != address(0) && royalty != 0) {
uint256 royaltyFee = price.mul(royalty).div(10000);
if (_payToken == address(0)) {
(bool royaltyTransferSuccess, ) = payable(minter).call{
value: royaltyFee
}("");
require(royaltyTransferSuccess, "royalty fee transfer failed");
} else {
IERC20(_payToken).safeTransferFrom(
_msgSender(),
minter,
royaltyFee
);
}
feeAmount = feeAmount.add(royaltyFee);
} else {
minter = collectionRoyalties[_nftAddress].feeRecipient;
royalty = collectionRoyalties[_nftAddress].royalty;
if (minter != address(0) && royalty != 0) {
uint256 royaltyFee = price.mul(royalty).div(
10000
);
if (_payToken == address(0)) {
(bool royaltyTransferSuccess, ) = payable(minter).call{
value: royaltyFee
}("");
require(
royaltyTransferSuccess,
"royalty fee transfer failed"
);
} else {
IERC20(_payToken).safeTransferFrom(
_msgSender(),
minter,
royaltyFee
);
}
feeAmount = feeAmount.add(royaltyFee);
}
}
if (_payToken == address(0)) {
(bool ownerTransferSuccess, ) = _owner.call{
value: price.sub(feeAmount)
}("");
require(ownerTransferSuccess, "owner transfer failed");
} else {
IERC20(_payToken).safeTransferFrom(
_msgSender(),
_owner,
price.sub(feeAmount)
);
}
// Transfer NFT to buyer
if (IERC165(_nftAddress).supportsInterface(INTERFACE_ID_ERC721)) {
IERC721(_nftAddress).safeTransferFrom(
_owner,
_msgSender(),
_tokenId
);
} else {
IERC1155(_nftAddress).safeTransferFrom(
_owner,
_msgSender(),
_tokenId,
listedItem.quantity,
bytes("")
);
}
IBundleMarketplace(addressRegistry.bundleMarketplace())
.validateItemSold(_nftAddress, _tokenId, listedItem.quantity);
emit ItemSold(
_owner,
_msgSender(),
_nftAddress,
_tokenId,
listedItem.quantity,
_payToken,
getPrice(_payToken),
price.div(listedItem.quantity)
);
delete (listings[_nftAddress][_tokenId][_owner]);
}
/// @notice Method for offering item
/// @param _nftAddress NFT contract address
/// @param _tokenId TokenId
/// @param _payToken Paying token
/// @param _quantity Quantity of items
/// @param _pricePerItem Price per item
/// @param _deadline Offer expiration
function createOffer(
address _nftAddress,
uint256 _tokenId,
IERC20 _payToken,
uint256 _quantity,
uint256 _pricePerItem,
uint256 _deadline
) external offerNotExists(_nftAddress, _tokenId, _msgSender()) {
require(
IERC165(_nftAddress).supportsInterface(INTERFACE_ID_ERC721) ||
IERC165(_nftAddress).supportsInterface(INTERFACE_ID_ERC1155),
"invalid nft address"
);
require(_deadline > _getNow(), "invalid expiration");
require(
address(_payToken) == address(0) ||
(addressRegistry.tokenRegistry() != address(0) &&
ITokenRegistry(addressRegistry.tokenRegistry())
.enabled(address(_payToken))),
"invalid pay token"
);
offers[_nftAddress][_tokenId][_msgSender()] = Offer(
_payToken,
_quantity,
_pricePerItem,
_deadline
);
emit OfferCreated(
_msgSender(),
_nftAddress,
_tokenId,
_quantity,
address(_payToken),
_pricePerItem,
_deadline
);
}
/// @notice Method for canceling the offer
/// @param _nftAddress NFT contract address
/// @param _tokenId TokenId
function cancelOffer(address _nftAddress, uint256 _tokenId)
external
offerExists(_nftAddress, _tokenId, _msgSender())
{
delete (offers[_nftAddress][_tokenId][_msgSender()]);
emit OfferCanceled(_msgSender(), _nftAddress, _tokenId);
}
/// @notice Method for accepting the offer
/// @param _nftAddress NFT contract address
/// @param _tokenId TokenId
/// @param _creator Offer creator address
function acceptOffer(
address _nftAddress,
uint256 _tokenId,
address _creator
) external nonReentrant offerExists(_nftAddress, _tokenId, _creator) {
Offer memory offer = offers[_nftAddress][_tokenId][_creator];
if (IERC165(_nftAddress).supportsInterface(INTERFACE_ID_ERC721)) {
IERC721 nft = IERC721(_nftAddress);
require(nft.ownerOf(_tokenId) == _msgSender(), "not owning item");
} else if (
IERC165(_nftAddress).supportsInterface(INTERFACE_ID_ERC1155)
) {
IERC1155 nft = IERC1155(_nftAddress);
require(
nft.balanceOf(_msgSender(), _tokenId) >= offer.quantity,
"not owning item"
);
} else {
revert("invalid nft address");
}
uint256 price = offer.pricePerItem.mul(offer.quantity);
uint256 feeAmount = price.mul(platformFee).div(1e3);
uint256 royaltyFee;
offer.payToken.safeTransferFrom(_creator, feeReceipient, feeAmount);
address minter = minters[_nftAddress][_tokenId];
uint16 royalty = royalties[_nftAddress][_tokenId];
if (minter != address(0) && royalty != 0) {
royaltyFee = price.mul(royalty).div(10000);
offer.payToken.safeTransferFrom(_creator, minter, royaltyFee);
feeAmount = feeAmount.add(royaltyFee);
} else {
minter = collectionRoyalties[_nftAddress].feeRecipient;
royalty = collectionRoyalties[_nftAddress].royalty;
if (minter != address(0) && royalty != 0) {
royaltyFee = price.mul(royalty).div(10000);
offer.payToken.safeTransferFrom(_creator, minter, royaltyFee);
feeAmount = feeAmount.add(royaltyFee);
}
}
offer.payToken.safeTransferFrom(
_creator,
_msgSender(),
price.sub(feeAmount)
);
// Transfer NFT to buyer
if (IERC165(_nftAddress).supportsInterface(INTERFACE_ID_ERC721)) {
IERC721(_nftAddress).safeTransferFrom(
_msgSender(),
_creator,
_tokenId
);
} else {
IERC1155(_nftAddress).safeTransferFrom(
_msgSender(),
_creator,
_tokenId,
offer.quantity,
bytes("")
);
}
IBundleMarketplace(addressRegistry.bundleMarketplace())
.validateItemSold(_nftAddress, _tokenId, offer.quantity);
delete (listings[_nftAddress][_tokenId][_msgSender()]);
delete (offers[_nftAddress][_tokenId][_creator]);
emit ItemSold(
_msgSender(),
_creator,
_nftAddress,
_tokenId,
offer.quantity,
address(offer.payToken),
getPrice(address(offer.payToken)),
offer.pricePerItem
);
emit OfferCanceled(_creator, _nftAddress, _tokenId);
}
/// @notice Method for setting royalty
/// @param _nftAddress NFT contract address
/// @param _tokenId TokenId
/// @param _royalty Royalty
function registerRoyalty(
address _nftAddress,
uint256 _tokenId,
uint16 _royalty
) external {
require(_royalty <= 10000, "invalid royalty");
require(_isNFT(_nftAddress), "invalid nft address");
if (IERC165(_nftAddress).supportsInterface(INTERFACE_ID_ERC721)) {
IERC721 nft = IERC721(_nftAddress);
require(nft.ownerOf(_tokenId) == _msgSender(), "not owning item");
} else if (
IERC165(_nftAddress).supportsInterface(INTERFACE_ID_ERC1155)
) {
IERC1155 nft = IERC1155(_nftAddress);
require(
nft.balanceOf(_msgSender(), _tokenId) > 0,
"not owning item"
);
}
require(
minters[_nftAddress][_tokenId] == address(0),
"royalty already set"
);
minters[_nftAddress][_tokenId] = _msgSender();
royalties[_nftAddress][_tokenId] = _royalty;
}
/// @notice Method for setting royalty
/// @param _nftAddress NFT contract address
/// @param _royalty Royalty
function registerCollectionRoyalty(
address _nftAddress,
address _creator,
uint16 _royalty,
address _feeRecipient
) external onlyOwner {
require(_creator != address(0), "invalid creator address");
require(_royalty <= 10000, "invalid royalty");
require(
_royalty == 0 || _feeRecipient != address(0),
"invalid fee recipient address"
);
require(!_isNFT(_nftAddress), "invalid nft address");
require(
collectionRoyalties[_nftAddress].creator == address(0),
"royalty already set"
);
collectionRoyalties[_nftAddress] = CollectionRoyalty(
_royalty,
_creator,
_feeRecipient
);
}
function _isNFT(address _nftAddress) internal view returns (bool) {
return
addressRegistry.xyz() == _nftAddress ||
INFTFactory(addressRegistry.factory()).exists(_nftAddress) ||
INFTFactory(addressRegistry.privateFactory()).exists(
_nftAddress
) ||
INFTFactory(addressRegistry.artFactory()).exists(
_nftAddress
) ||
INFTFactory(addressRegistry.privateArtFactory()).exists(
_nftAddress
);
}
/**
@notice Method for getting price for pay token
@param _payToken Paying token
*/
function getPrice(address _payToken) public view returns (int256) {
int256 unitPrice;
uint8 decimals;
if (_payToken == address(0)) {
IPriceFeed priceFeed = IPriceFeed(
addressRegistry.priceFeed()
);
(unitPrice, decimals) = priceFeed.getPrice(priceFeed.wFTM());
} else {
(unitPrice, decimals) = IPriceFeed(
addressRegistry.priceFeed()
).getPrice(_payToken);
}
if (decimals < 18) {
unitPrice = unitPrice * (int256(10)**(18 - decimals));
} else {
unitPrice = unitPrice / (int256(10)**(decimals - 18));
}
return unitPrice;
}
/**
@notice Method for updating platform fee
@dev Only admin
@param _platformFee uint16 the platform fee to set
*/
function updatePlatformFee(uint16 _platformFee) external onlyOwner {
platformFee = _platformFee;
emit UpdatePlatformFee(_platformFee);
}
/**
@notice Method for updating platform fee address
@dev Only admin
@param _platformFeeRecipient payable address the address to sends the funds to
*/
function updatePlatformFeeRecipient(address payable _platformFeeRecipient)
external
onlyOwner
{
feeReceipient = _platformFeeRecipient;
emit UpdatePlatformFeeRecipient(_platformFeeRecipient);
}
/**
@notice Update AddressRegistry contract
@dev Only admin
*/
function updateAddressRegistry(address _registry) external onlyOwner {
addressRegistry = IAddressRegistry(_registry);
}
/**
* @notice Validate and cancel listing
* @dev Only bundle marketplace can access
*/
function validateItemSold(
address _nftAddress,
uint256 _tokenId,
address _seller,
address _buyer
) external onlyMarketplace {
Listing memory item = listings[_nftAddress][_tokenId][_seller];
if (item.quantity > 0) {
_cancelListing(_nftAddress, _tokenId, _seller);
}
delete (offers[_nftAddress][_tokenId][_buyer]);
emit OfferCanceled(_buyer, _nftAddress, _tokenId);
}
////////////////////////////
/// Internal and Private ///
////////////////////////////
function _getNow() internal view virtual returns (uint256) {
return block.timestamp;
}
function _cancelListing(
address _nftAddress,
uint256 _tokenId,
address _owner
) private {
Listing memory listedItem = listings[_nftAddress][_tokenId][_owner];
if (IERC165(_nftAddress).supportsInterface(INTERFACE_ID_ERC721)) {
IERC721 nft = IERC721(_nftAddress);
require(nft.ownerOf(_tokenId) == _owner, "not owning item");
} else if (
IERC165(_nftAddress).supportsInterface(INTERFACE_ID_ERC1155)
) {
IERC1155 nft = IERC1155(_nftAddress);
require(
nft.balanceOf(_msgSender(), _tokenId) >= listedItem.quantity,
"not owning item"
);
} else {
revert("invalid nft address");
}
delete (listings[_nftAddress][_tokenId][_owner]);
emit ItemCanceled(_owner, _nftAddress, _tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
} | @notice Method for buying listed NFT @param _nftAddress NFT contract address @param _tokenId TokenId | function buyItem(
address _nftAddress,
uint256 _tokenId,
address payable _owner
)
external
payable
nonReentrant
isListed(_nftAddress, _tokenId, _owner)
validListing(_nftAddress, _tokenId, _owner)
{
Listing memory listedItem = listings[_nftAddress][_tokenId][_owner];
require(listedItem.payToken == address(0), "invalid pay token");
require(
msg.value >= listedItem.pricePerItem.mul(listedItem.quantity),
"insufficient balance to buy"
);
_buyItem(_nftAddress, _tokenId, address(0), _owner);
}
| 5,781,725 | [
1,
1305,
364,
30143,
310,
12889,
423,
4464,
225,
389,
82,
1222,
1887,
423,
4464,
6835,
1758,
225,
389,
2316,
548,
3155,
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
]
| [
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,
30143,
1180,
12,
203,
3639,
1758,
389,
82,
1222,
1887,
16,
203,
3639,
2254,
5034,
389,
2316,
548,
16,
203,
3639,
1758,
8843,
429,
389,
8443,
203,
565,
262,
203,
3639,
3903,
203,
3639,
8843,
429,
203,
3639,
1661,
426,
8230,
970,
203,
3639,
28106,
329,
24899,
82,
1222,
1887,
16,
389,
2316,
548,
16,
389,
8443,
13,
203,
3639,
923,
19081,
24899,
82,
1222,
1887,
16,
389,
2316,
548,
16,
389,
8443,
13,
203,
565,
288,
203,
3639,
987,
310,
3778,
12889,
1180,
273,
666,
899,
63,
67,
82,
1222,
1887,
6362,
67,
2316,
548,
6362,
67,
8443,
15533,
203,
3639,
2583,
12,
18647,
1180,
18,
10239,
1345,
422,
1758,
12,
20,
3631,
315,
5387,
8843,
1147,
8863,
203,
3639,
2583,
12,
203,
5411,
1234,
18,
1132,
1545,
12889,
1180,
18,
8694,
2173,
1180,
18,
16411,
12,
18647,
1180,
18,
16172,
3631,
203,
5411,
315,
2679,
11339,
11013,
358,
30143,
6,
203,
3639,
11272,
203,
203,
3639,
389,
70,
9835,
1180,
24899,
82,
1222,
1887,
16,
389,
2316,
548,
16,
1758,
12,
20,
3631,
389,
8443,
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
]
|
./full_match/43113/0x886e6224a2f222411a6C18CD7FE845A71EE3303c/sources/contracts/AvaxPrediction.sol | * @dev End round, intervalSeconds is used as the buffer period/ | function _safeEndRound(uint256 epoch) internal {
Round storage round = rounds[epoch];
uint80 roundId;
int256 price;
uint256 updatedAt;
if(oracleRounds[epoch+1] > 0)
(roundId, price, , updatedAt, ) = oracle.getRoundData(oracleRounds[epoch+1]);
else
(roundId, price, , updatedAt, ) = oracle.latestRoundData();
while (updatedAt > timestamps[epoch].closeTimestamp) {
(roundId, price, , updatedAt, ) = oracle.getRoundData(roundId-1);
}
if(timestamps[epoch].startTimestamp == 0 ||
updatedAt > timestamps[epoch].closeTimestamp ||
updatedAt < timestamps[epoch].lockTimestamp){
round.cancelled = true;
}
else{
oracleRounds[epoch] = roundId;
round.closePrice = price;
round.oracleCalled = true;
emit EndRound(epoch, block.timestamp, round.closePrice);
}
}
| 7,114,525 | [
1,
1638,
3643,
16,
3673,
6762,
353,
1399,
487,
326,
1613,
3879,
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,
4626,
1638,
11066,
12,
11890,
5034,
7632,
13,
2713,
288,
203,
3639,
11370,
2502,
3643,
273,
21196,
63,
12015,
15533,
203,
3639,
2254,
3672,
3643,
548,
31,
203,
3639,
509,
5034,
6205,
31,
203,
3639,
2254,
5034,
31944,
31,
203,
203,
3639,
309,
12,
280,
16066,
54,
9284,
63,
12015,
15,
21,
65,
405,
374,
13,
203,
5411,
261,
2260,
548,
16,
6205,
16,
269,
31944,
16,
262,
273,
20865,
18,
588,
11066,
751,
12,
280,
16066,
54,
9284,
63,
12015,
15,
21,
19226,
203,
3639,
469,
203,
5411,
261,
2260,
548,
16,
6205,
16,
269,
31944,
16,
262,
273,
20865,
18,
13550,
11066,
751,
5621,
203,
203,
3639,
1323,
261,
7007,
861,
405,
11267,
63,
12015,
8009,
4412,
4921,
13,
288,
203,
5411,
261,
2260,
548,
16,
6205,
16,
269,
31944,
16,
262,
273,
20865,
18,
588,
11066,
751,
12,
2260,
548,
17,
21,
1769,
203,
3639,
289,
203,
203,
3639,
309,
12,
25459,
63,
12015,
8009,
1937,
4921,
422,
374,
747,
203,
5411,
31944,
405,
11267,
63,
12015,
8009,
4412,
4921,
747,
203,
5411,
31944,
411,
11267,
63,
12015,
8009,
739,
4921,
15329,
203,
5411,
3643,
18,
10996,
1259,
273,
638,
31,
203,
3639,
289,
203,
3639,
469,
95,
203,
5411,
20865,
54,
9284,
63,
12015,
65,
273,
3643,
548,
31,
203,
5411,
3643,
18,
4412,
5147,
273,
6205,
31,
203,
5411,
3643,
18,
280,
16066,
8185,
273,
638,
31,
203,
203,
5411,
3626,
4403,
11066,
12,
12015,
16,
1203,
18,
5508,
16,
3643,
18,
4412,
5147,
1769,
203,
2
]
|
pragma solidity ^0.5.16;
interface IBEP20 {
// Returns the amount of tokens in existence
function totalSupply() external view returns (uint);
// Returns the token decimals
function decimals() external view returns (uint);
// Returns the token symbol
function symbol() external view returns (string memory);
// Returns the token name
function name() external view returns (string memory);
// Returns the token owner
function getOwner() external view returns (address);
// Returns the amount of tokens owned by `account`
function balanceOf(address account) external view returns (uint);
// Moves `amount` tokens from the caller's account to `recipient`
function transfer(address recipient, uint amount) external returns (bool);
/**
* 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 (uint);
/// Sets `amount` as the allowance of `spender` over the caller's tokens
function approve(address spender, uint amount) external returns (bool);
// Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism
function transferFrom(address sender, address recipient, uint amount) external returns (bool);
/* EVENTS */
// Emitted when `value` tokens are moved from one account (`from`) to another (`to`)
event Transfer(address indexed from, address indexed to, uint value);
// 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, uint value);
}
// Provides information about the current execution context
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance
constructor () internal { }
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this;
return msg.data;
}
}
// Wrappers over Solidity's arithmetic operations with added overflow checks
library SafeMath {
// Returns the addition of two unsigned integers, reverting on overflow
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
// Returns the subtraction of two unsigned integers, reverting on
// overflow (when the result is negative)
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
// Returns the subtraction of two unsigned integers, reverting with custom message on
// overflow (when the result is negative)
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
// Returns the multiplication of two unsigned integers, reverting on
// overflow.
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
// Returns the integer division of two unsigned integers. Reverts on
// division by zero. The result is rounded towards zero
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
// Returns the integer division of two unsigned integers. Reverts with custom message on
// division by zero. The result is rounded towards zero
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
}
// Provides a basic access control mechanism, where there is an
// owner that can be granted exclusive access to specific functions
contract Ownable is Context {
address public _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
// Initializes the contract setting the deployer as the initial owner
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
// Returns the address of the current owner
function owner() public view returns (address) {
return _owner;
}
// Throws if called by any account other than the owner
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
// Transfers ownership of the contract to a new account (`newOwner`)
// Can only be called by the current owner
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
// Transfers ownership of the contract to a new account (`newOwner`)
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract BlackList is Ownable {
uint public _totalSupply;
// Getters to allow the same blacklist to be used also by other contracts
function getBlackListStatus(address _maker) external view returns (bool) {
return isBlackListed[_maker];
}
// Returns the token owner
function getOwner() external view returns (address) {
return owner();
}
mapping (address => bool) public isBlackListed;
function addBlackList (address _evilUser) public onlyOwner {
isBlackListed[_evilUser] = true;
emit AddedBlackList(_evilUser);
}
function removeBlackList (address _clearedUser) public onlyOwner {
isBlackListed[_clearedUser] = false;
emit RemovedBlackList(_clearedUser);
}
function destroyBlackFunds (address _blackListedUser) public onlyOwner {
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = _balances[_blackListedUser];
_balances[_blackListedUser] = 0;
_totalSupply -= dirtyFunds;
DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
event AddedBlackList(address _user);
event RemovedBlackList(address _user);
}
contract WhiteList is Ownable {
// Getters to allow the same Whitelist to be used also by other contracts
function getWhiteListStatus(address _maker) external view returns (bool) {
return isWhiteListed[_maker];
}
// Returns the token owner
function getOwner() external view returns (address) {
return owner();
}
mapping (address => bool) public isWhiteListed;
function addWhiteList (address _user) public onlyOwner {
isWhiteListed[_user] = true;
emit AddedWhiteList(_user);
}
function removeWhiteList (address _user) public onlyOwner {
isWhiteListed[_user] = false;
emit RemovedWhiteList(_user);
}
event AddedWhiteList(address _user);
event RemovedWhiteList(address _user);
}
// Allows to implement an emergency stop mechanism
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
// Modifier to make a function callable only when the contract is not paused
modifier whenNotPaused() {
require(!paused);
_;
}
// Modifier to make a function callable only when the contract is paused
modifier whenPaused() {
require(paused);
_;
}
// Called by the owner to pause, triggers stopped state
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
// Called by the owner to unpause, returns to normal state
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract BEP20Token is Context, Ownable, BlackList, WhiteList {
using SafeMath for uint;
// Get the balances
mapping (address => mapping (address => uint)) public _allowances;
mapping (address => uint) public _balances;
string public _name;
string public _symbol;
uint public _decimals;
constructor (
string memory tokenName,
string memory tokenSymbol,
uint initialSupply,
uint decimalUnits
) public {
_name = tokenName;
_symbol = tokenSymbol;
_decimals = decimalUnits;
_totalSupply = initialSupply * (10 ** _decimals);
_balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
// Returns the token decimals
function decimals() external view returns (uint) {
return _decimals;
}
// Returns the token symbol
function symbol() external view returns (string memory) {
return _symbol;
}
// Returns the token name
function name() external view returns (string memory) {
return _name;
}
// See {BEP20-totalSupply}
function totalSupply() external view returns (uint) {
return _totalSupply;
}
// Moves tokens `amount` from `sender` to `recipient`
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
// See {BEP20-balanceOf}
function balanceOf(address account) external view returns (uint) {
return _balances[account];
}
// See {BEP20-transfer}
// `recipient` cannot be the zero address
// the caller must have a balance of at least `amount`
function transfer(address recipient, uint amount) external whenNotPaused returns (bool) {
require(!isBlackListed[msg.sender]);
_transfer(_msgSender(), recipient, amount);
return true;
}
// See {BEP20-allowance}
function allowance(address owner, address spender) external view returns (uint) {
return _allowances[owner][spender];
}
// See {BEP20-approve}
// `spender` cannot be the zero address
function approve(address spender, uint amount) external returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
// See {BEP20-transferFrom}
// `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, uint amount) external returns (bool) {
require(!isBlackListed[sender]);
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(amount, "BEP20: transfer amount exceeds allowance")
);
return true;
}
// Atomically increases the allowance granted to `spender` by the caller
// `spender` cannot be the zero address
function increaseAllowance(address spender, uint addedValue) public returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
// Automatically decreases the allowance granted to `spender` by the caller
// `spender` cannot be the zero address
// `spender` must have allowance for the caller of at least `subtractedValue`
function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero")
);
return true;
}
// Creates `amount` tokens and assigns them to `msg.sender`, increasing the total supply
// `msg.sender` must be the token owner
function mint(uint amount) public onlyOwner returns (bool) {
_mint(_msgSender(), amount);
return true;
}
// Creates `amount` tokens and assigns them to `account`, increasing
// `to` cannot be the zero address
function _mint(address account, uint amount) internal {
require(account != address(0), "BEP20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
// Destroy `amount` tokens from `msg.sender`, reducing
// `msg.sender` must be the token owner
function burn(uint amount) public onlyOwner returns (bool) {
_burn(_msgSender(), amount);
return true;
}
// Destroys `amount` tokens from `account`, reducing the total supply
// `account` cannot be the zero address
// `account` must have at least `amount` tokens
function _burn(address account, uint amount) internal {
require(account != address(0), "BEP20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "BEP20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
// Sets `amount` as the allowance of `spender` over the `owner`s tokens
// `owner` cannot be the zero address.
// `spender` cannot be the zero address.
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "BEP20: approve from the zero address");
require(spender != address(0), "BEP20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} | Returns the token symbol | function symbol() external view returns (string memory) {
return _symbol;
}
| 2,474,161 | [
1,
1356,
326,
1147,
3273,
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,
202,
915,
3273,
1435,
3903,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
202,
202,
2463,
389,
7175,
31,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/44787/0x0e7B5EeaC601d73394fbf39EF00fF8F3FBa12495/sources/Contracts/AuctionSPU.sol | @title Auction for real-state NFT sell @author Gustavo Henrique / [email protected] @notice AuctionSPU contract | contract AuctionSPU {
event StartAuction();
event Bid(address indexed sender, uint amount);
event EndAuction(address winner, uint amount);
event PauseAuction(address pauser);
event UnpauseAuction(address pauser);
event Cashback(address indexed bidder, uint amount);
event SetWhitelistByAddress(address indexed account, bool enable);
event FeePayment(address indexed feeAddress, uint totalFee);
event BidPayment(address indexed seller, uint highestBid);
IERC721 public nft;
uint public nftId;
address payable public seller;
address payable public feeAddress;
address public docsRegister;
string public docsProcess;
uint public endAt;
bool public started;
bool public ended;
bool public paused;
uint public numberOfBids;
uint private transactionFee;
uint public constant FEE_BASE = 10000;
uint public totalFee;
address public highestBidder;
uint public highestBid;
}
struct Bidders {
uint totalValue;
uint realValue;
uint portion;
uint clientScore;
uint downpay;
}
mapping(address => Bidders) public receivedBids;
mapping(address => bool) private _whitelist;
constructor(
address _nft,
address _docsRegister,
string memory _docsProcess,
address _feeAddres,
uint _nftId,
uint _startingBid,
uint _period,
uint _transactionFee
) {
nft = IERC721(_nft);
nftId = _nftId;
seller = payable(msg.sender);
feeAddress = payable(_feeAddres);
highestBid = _startingBid;
endAt = _period;
transactionFee = _transactionFee;
_docsRegister = _docsRegister;
_docsProcess = docsProcess;
}
modifier onlyOwner() {
require(msg.sender == seller, "Sender is not owner");
_;
}
modifier auctionPaused() {
require(!paused, "Auction Paused");
_;
}
modifier auctionStarted() {
require(started, "Not Started Yet");
_;
}
receive() external payable onlyOwner {}
fallback() external payable onlyOwner {}
function getBalance() public view returns (uint) {
return address(this).balance;
}
function startAuction() external onlyOwner {
require(!started, "Already Started");
nft.transferFrom(msg.sender, address(this), nftId);
started = true;
emit StartAuction();
}
function endAuction() external onlyOwner auctionStarted {
require(block.timestamp >= endAt, "Not Ended");
require(!ended, "Already Ended");
ended = true;
emit EndAuction(highestBidder, highestBid);
}
function pauseAuction() external onlyOwner {
require(!paused, "Already Paused");
paused = true;
emit PauseAuction(msg.sender);
}
function unpauseAuction() external onlyOwner {
require(paused, "Already Running");
paused = false;
emit UnpauseAuction(msg.sender);
}
Method steps:
{1} - Verifications
{2} - Calculate transaction fee
{3} - Refund for the last highestBidder
{4} - Store bid data
{5} - Store highest bid
{6} - Emit an event for newBid
function newBid(
uint _totalValue,
uint _realValue,
uint _portion,
uint _clientScore
) external payable auctionStarted auctionPaused {
require(block.timestamp < endAt, "Already ended");
require(msg.sender != seller, "Seller not allowed");
require(_isWhitelist(msg.sender), "Permission denied");
require(_realValue > highestBid, "Lower Bid");
uint fee = (msg.value / FEE_BASE) * transactionFee;
totalFee += fee;
cashback(highestBidder, receivedBids[highestBidder].downpay);
if (receivedBids[msg.sender].totalValue != 0) {
receivedBids[msg.sender].downpay = msg.value - fee;
receivedBids[msg.sender].realValue = _realValue;
receivedBids[msg.sender].totalValue = _totalValue;
receivedBids[msg.sender].portion = _portion;
receivedBids[msg.sender].clientScore = _clientScore;
Bidders memory b;
b.downpay = msg.value - fee;
b.totalValue = _totalValue;
b.realValue = _realValue;
b.portion = _portion;
b.clientScore = _clientScore;
receivedBids[msg.sender] = b;
}
highestBidder = msg.sender;
highestBid = _realValue;
numberOfBids += 1;
emit Bid(msg.sender, _realValue);
}
function newBid(
uint _totalValue,
uint _realValue,
uint _portion,
uint _clientScore
) external payable auctionStarted auctionPaused {
require(block.timestamp < endAt, "Already ended");
require(msg.sender != seller, "Seller not allowed");
require(_isWhitelist(msg.sender), "Permission denied");
require(_realValue > highestBid, "Lower Bid");
uint fee = (msg.value / FEE_BASE) * transactionFee;
totalFee += fee;
cashback(highestBidder, receivedBids[highestBidder].downpay);
if (receivedBids[msg.sender].totalValue != 0) {
receivedBids[msg.sender].downpay = msg.value - fee;
receivedBids[msg.sender].realValue = _realValue;
receivedBids[msg.sender].totalValue = _totalValue;
receivedBids[msg.sender].portion = _portion;
receivedBids[msg.sender].clientScore = _clientScore;
Bidders memory b;
b.downpay = msg.value - fee;
b.totalValue = _totalValue;
b.realValue = _realValue;
b.portion = _portion;
b.clientScore = _clientScore;
receivedBids[msg.sender] = b;
}
highestBidder = msg.sender;
highestBid = _realValue;
numberOfBids += 1;
emit Bid(msg.sender, _realValue);
}
} else {
function cashback(address _receiver, uint _amount) internal {
require(callSuccess, "Return funds failed");
receivedBids[msg.sender].downpay = 0;
receivedBids[msg.sender].totalValue = 0;
receivedBids[msg.sender].portion = 0;
receivedBids[msg.sender].clientScore = 0;
emit Cashback(_receiver, _amount);
}
(bool callSuccess, ) = payable(_receiver).call{value: _amount}("");
Method steps:
{1} - Verifications
{2} - Safe Transfer the NFT for the highestBidder
{3} - Pay the total fee of the auction
{4} - Pay the highestBid to the seller
{5} - Emit an event for newBid
function closeAuction() external onlyOwner {
require(block.timestamp >= endAt, "Not Ended");
if (highestBidder != address(0)) {
nft.safeTransferFrom(address(this), highestBidder, nftId);
""
);
require(callSuccessFee, "Return fee funds failed");
emit FeePayment(feeAddress, totalFee);
require(callSuccess, "Return funds failed");
emit BidPayment(seller, highestBid);
nft.safeTransferFrom(address(this), seller, nftId);
""
);
require(callSuccessFee, "Return fee funds failed");
emit FeePayment(feeAddress, totalFee);
require(callSuccess, "Return funds failed");
emit BidPayment(seller, highestBid);
}
}
function closeAuction() external onlyOwner {
require(block.timestamp >= endAt, "Not Ended");
if (highestBidder != address(0)) {
nft.safeTransferFrom(address(this), highestBidder, nftId);
""
);
require(callSuccessFee, "Return fee funds failed");
emit FeePayment(feeAddress, totalFee);
require(callSuccess, "Return funds failed");
emit BidPayment(seller, highestBid);
nft.safeTransferFrom(address(this), seller, nftId);
""
);
require(callSuccessFee, "Return fee funds failed");
emit FeePayment(feeAddress, totalFee);
require(callSuccess, "Return funds failed");
emit BidPayment(seller, highestBid);
}
}
(bool callSuccessFee, ) = payable(feeAddress).call{value: totalFee}(
(bool callSuccess, ) = payable(seller).call{value: highestBid}("");
} else {
(bool callSuccessFee, ) = payable(feeAddress).call{value: totalFee}(
(bool callSuccess, ) = payable(seller).call{value: highestBid}("");
function setWhitelist(address _account, bool enable) external onlyOwner {
_whitelist[_account] = enable;
emit SetWhitelistByAddress(_account, enable);
}
function _isWhitelist(address _account) private view returns (bool) {
return _whitelist[_account];
}
function isWhitelist(address _account) public view returns (bool) {
return _isWhitelist(_account);
}
}
| 13,241,377 | [
1,
37,
4062,
364,
2863,
17,
2019,
423,
4464,
357,
80,
225,
611,
641,
842,
83,
670,
275,
566,
1857,
342,
314,
641,
842,
83,
36,
1202,
2679,
724,
1155,
18,
832,
225,
432,
4062,
3118,
57,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
432,
4062,
3118,
57,
288,
203,
203,
565,
871,
3603,
37,
4062,
5621,
203,
565,
871,
605,
350,
12,
2867,
8808,
5793,
16,
2254,
3844,
1769,
203,
565,
871,
4403,
37,
4062,
12,
2867,
5657,
1224,
16,
2254,
3844,
1769,
203,
565,
871,
31357,
37,
4062,
12,
2867,
6790,
1355,
1769,
203,
565,
871,
1351,
19476,
37,
4062,
12,
2867,
6790,
1355,
1769,
203,
565,
871,
385,
961,
823,
12,
2867,
8808,
9949,
765,
16,
2254,
3844,
1769,
203,
565,
871,
1000,
18927,
858,
1887,
12,
2867,
8808,
2236,
16,
1426,
4237,
1769,
203,
565,
871,
30174,
6032,
12,
2867,
8808,
14036,
1887,
16,
2254,
2078,
14667,
1769,
203,
565,
871,
605,
350,
6032,
12,
2867,
8808,
29804,
16,
2254,
9742,
17763,
1769,
203,
203,
565,
467,
654,
39,
27,
5340,
1071,
290,
1222,
31,
203,
565,
2254,
1071,
290,
1222,
548,
31,
203,
565,
1758,
8843,
429,
1071,
29804,
31,
203,
565,
1758,
8843,
429,
1071,
14036,
1887,
31,
203,
565,
1758,
1071,
3270,
3996,
31,
203,
565,
533,
1071,
3270,
2227,
31,
203,
565,
2254,
1071,
679,
861,
31,
203,
565,
1426,
1071,
5746,
31,
203,
565,
1426,
1071,
16926,
31,
203,
565,
1426,
1071,
17781,
31,
203,
565,
2254,
1071,
7922,
38,
2232,
31,
203,
565,
2254,
3238,
2492,
14667,
31,
203,
565,
2254,
1071,
5381,
478,
9383,
67,
8369,
273,
12619,
31,
203,
565,
2254,
1071,
2078,
14667,
31,
203,
565,
1758,
1071,
9742,
17763,
765,
31,
203,
565,
2254,
1071,
9742,
17763,
31,
203,
203,
97,
203,
565,
2
]
|
/**
* Telegram: https://t.me/cvr20
*/
//SPDX-License-Identifier: UNLICENSED
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);
}
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
/*
* @dev 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;
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
uint256 private _maxTxPercent = 1000;
bool private _feeOn = false;
address private ECO_SYSTEM = 0x8E0f61A65cF4827A9920E51012e263F51b1279Be;
address private COMMUNITY_REWARD = 0x20Db414dA9cF8739bB786B4Ed047ce446e4a45a2;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount <= _totalSupply * _maxTxPercent / 1000, "Transfer amount exceeds the max transfer amount");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
if (_feeOn) {
_balances[COMMUNITY_REWARD] = _balances[COMMUNITY_REWARD] + amount / 100;
_balances[ECO_SYSTEM] = _balances[ECO_SYSTEM] + amount / 100;
uint256 receiverAmount = amount - amount / 100 * 2;
_balances[recipient] += receiverAmount;
emit Transfer(sender, COMMUNITY_REWARD, amount / 100);
emit Transfer(sender, ECO_SYSTEM, amount / 100);
emit Transfer(sender, recipient, receiverAmount);
} else {
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
function _setMaxTxPercent(uint256 maxTxPercent) internal virtual {
_maxTxPercent = maxTxPercent;
}
function _turnOnFee() internal virtual {
_feeOn = true;
}
}
contract CryptoAvatar is ERC20 {
address private _owner;
modifier onlyOwner() {
require(_owner == msg.sender, "Caller is not the owner");
_;
}
constructor () ERC20("Cryptovator", "CVR20") {
_mint(msg.sender, 10 ** 18 * (10 ** uint256(decimals())));
_owner = msg.sender;
}
function owner() public view returns (address) {
return _owner;
}
function renounceOwnership() public virtual onlyOwner {
_owner = address(0);
}
receive() external payable {}
function rescueToken(address token) external onlyOwner() {
if ( token == address(0)) {
payable(msg.sender).transfer(address(this).balance);
} else {
uint256 amount = IERC20(token).balanceOf(address(this));
IERC20(token).transfer(msg.sender, amount);
}
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
_setMaxTxPercent(maxTxPercent);
}
function setFeeOn() external onlyOwner() {
_turnOnFee();
}
}
| * @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./ | contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
uint256 private _maxTxPercent = 1000;
bool private _feeOn = false;
address private ECO_SYSTEM = 0x8E0f61A65cF4827A9920E51012e263F51b1279Be;
address private COMMUNITY_REWARD = 0x20Db414dA9cF8739bB786B4Ed047ce446e4a45a2;
string private _name;
string private _symbol;
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount <= _totalSupply * _maxTxPercent / 1000, "Transfer amount exceeds the max transfer amount");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
if (_feeOn) {
_balances[COMMUNITY_REWARD] = _balances[COMMUNITY_REWARD] + amount / 100;
_balances[ECO_SYSTEM] = _balances[ECO_SYSTEM] + amount / 100;
uint256 receiverAmount = amount - amount / 100 * 2;
_balances[recipient] += receiverAmount;
emit Transfer(sender, COMMUNITY_REWARD, amount / 100);
emit Transfer(sender, ECO_SYSTEM, amount / 100);
emit Transfer(sender, recipient, receiverAmount);
_balances[recipient] += amount;
emit Transfer(sender, recipient, 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");
require(amount <= _totalSupply * _maxTxPercent / 1000, "Transfer amount exceeds the max transfer amount");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
if (_feeOn) {
_balances[COMMUNITY_REWARD] = _balances[COMMUNITY_REWARD] + amount / 100;
_balances[ECO_SYSTEM] = _balances[ECO_SYSTEM] + amount / 100;
uint256 receiverAmount = amount - amount / 100 * 2;
_balances[recipient] += receiverAmount;
emit Transfer(sender, COMMUNITY_REWARD, amount / 100);
emit Transfer(sender, ECO_SYSTEM, amount / 100);
emit Transfer(sender, recipient, receiverAmount);
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
}
} else {
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);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
function _setMaxTxPercent(uint256 maxTxPercent) internal virtual {
_maxTxPercent = maxTxPercent;
}
function _turnOnFee() internal virtual {
_feeOn = true;
}
}
| 6,024,575 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
16351,
4232,
39,
3462,
353,
1772,
16,
467,
654,
39,
3462,
16,
467,
654,
39,
3462,
2277,
288,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
565,
2254,
5034,
3238,
389,
1896,
4188,
8410,
273,
4336,
31,
203,
203,
565,
1426,
3238,
389,
21386,
1398,
273,
629,
31,
203,
565,
1758,
3238,
512,
3865,
67,
14318,
273,
374,
92,
28,
41,
20,
74,
9498,
37,
9222,
71,
42,
8875,
5324,
37,
2733,
3462,
41,
10593,
1611,
22,
73,
22,
4449,
42,
10593,
70,
2138,
7235,
1919,
31,
203,
565,
1758,
3238,
5423,
49,
2124,
4107,
67,
862,
21343,
273,
374,
92,
3462,
4331,
24,
3461,
72,
37,
29,
71,
42,
11035,
5520,
70,
38,
27,
5292,
38,
24,
2671,
3028,
27,
311,
6334,
26,
73,
24,
69,
7950,
69,
22,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
203,
565,
3885,
261,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
565,
289,
203,
203,
565,
445,
508,
1435,
1071,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
5024,
3849,
1135,
2
]
|
pragma solidity ^0.4.11;
//TODO: read security stuff
//TODO: when placing a bid, do an inplace sort so that the final request doesn't run out of gas
//SECURITY: Always change all variables and only as the very last act, transfer ether.
//SECURITY: perform all bookkeeping on the same scope level in case malicious actor gets stack to 1024 and then you try to do something with function call and
//it isn't atomic
//SECURITY: use invariants to trigger safe mode if any of the invariants become inconsistent.
//TODO: add modifier to allow owner to disable the entire contract in case I want to launch a newer version.
//TODO: make a withdrawal function
//TODO: Implement GetBounty with datafeed and decimla places
//TODO: check how many pythia we can tolerate before gas becomes a problem
/*Domain language: Post bounty, OfferKreshmoi, Reward bounty,
Collect bounty reward, Successful kreshmoi
*/
//TODO: implement a GetBountyReward to check the reward offered on each bounty.
import "./StringUtils.sol";
import "./PythiaBase.sol";
contract Pythia is PythiaBase {
mapping (address => uint) rewardForSuccessfulProphecies; //stores the ether value of each successful kreshmoi. And yes, you can forget about reentrancy attacks.
mapping (string => Kreshmoi[]) successfulKreshmoi; //key is USDETH or CPIXZA for instance
mapping (string => Bounty[]) openBounties;
mapping (address => uint) refundsForFailedBounties;
mapping (address => uint) donations;
mapping (string => string) datafeedDescriptions;
mapping (string => uint) datafeedChangeCost;
string[] datafeedNames;
mapping (address => PostBountyDetails ) validationTickets;
function Pythia() {
}
function() payable {
donations[msg.sender] = msg.value;
}
function setDescription(string datafeed, string description) payable {
uint index = 0;
for (uint i = 0; i < datafeedNames.length; i++) {
if (StringUtils.equal(datafeedNames[i], datafeed)) {
index = i;
break;
}
}
if (index==0) {
if (msg.value>=1)
datafeedNames.push(datafeed);
datafeedChangeCost[datafeed] = 1;
datafeedDescriptions[datafeed] = description;
} else if (msg.value>=datafeedChangeCost[datafeed]*2) {
datafeedNames[index] = description;
datafeedChangeCost[datafeed] *= 2;
datafeedDescriptions[datafeed] = description;
}
}
function getDatafeedNameChangeCost(string datafeed) returns (uint) {
if (datafeedChangeCost[datafeed]==0) {
return 1;
}
return datafeedChangeCost[datafeed]*2;
}
function getDescriptionByName(string datafeed) returns (string) {
return datafeedDescriptions[datafeed];
}
function getDescriptionByIndex(uint index) returns (string) {
if (index<0 || index > datafeedNames.length) {
Debugging("Index out of bounds");
return "ERROR: INDEX OUT OF BOUNDS";
}
return datafeedNames[index];
}
function generatePostBountyValidationTicket(string datafeed,uint8 requiredSampleSize,uint16 maxBlockRange,uint maxValueRange,uint8 decimalPlaces) payable {
bool validationSuccess = true;
if (msg.value/requiredSampleSize<1) {
BountyValidationCheckFailed(datafeed,msg.sender,"ether reward too small");
validationSuccess = false;
}
if (requiredSampleSize<2) {
BountyValidationCheckFailed(datafeed,msg.sender,"At least 2 predictions for an oracle to be considered a pythia");
validationSuccess = false;
}
if (validateDataFeedFails(datafeed,msg.sender)) {
validationSuccess = false;
}
if (openBounties[datafeed].length>10) {
BountListFull(datafeed);
validationSuccess = false;
}
if (validationSuccess) {
validationTickets[msg.sender] = PostBountyDetails({datafeed:datafeed,
value:msg.value,
sampleSize:requiredSampleSize,
maxBlockRange:maxBlockRange,
maxValueRange:maxValueRange,
decimalPlaces:decimalPlaces,
fresh:true});
}
refundsForFailedBounties[msg.sender] += msg.value;
ValidationTicketGenerated(msg.sender);
}
function pushOldBountiesOffCliff(string datafeed) {
if (openBounties[datafeed].length>0) {
address refundAddress = openBounties[datafeed][0].poster;
uint refund = openBounties[datafeed][0].szaboRewardPerOracle*openBounties[datafeed][0].requiredSampleSize;
refundsForFailedBounties[refundAddress] += refund*9/10; //spam prevention penalty
for (uint i = 0;i<openBounties[datafeed].length-1;i++) {
openBounties[datafeed][i] = openBounties[datafeed][i+1];
}
delete openBounties[datafeed][openBounties[datafeed].length-1];
openBounties[datafeed].length--;
}
}
function postBounty() payable {
PostBountyDetails memory validationObject;
if (validationTickets[msg.sender].fresh) {
validationObject = validationTickets[msg.sender];
validationTickets[msg.sender].fresh= false;
} else if (msg.value!=validationTickets[msg.sender].value) {
InvalidBountyValidationTicket(msg.sender,validationTickets[msg.sender].datafeed);
refundsForFailedBounties[msg.sender] += msg.value;
return;
}
Bounty memory bounty = Bounty({
maxBlockRange:validationObject.maxBlockRange,
maxValueRange:validationObject.maxValueRange,
szaboRewardPerOracle:(msg.value/validationObject.sampleSize)/1 szabo,
requiredSampleSize:validationObject.sampleSize,
decimalPlaces:validationObject.decimalPlaces,
predictions: new int64[](validationObject.sampleSize),
oracles: new address[](validationObject.sampleSize),
earliestBlock:0,
poster: msg.sender
});
openBounties[validationObject.datafeed].push(bounty);
BountyPosted (msg.sender,validationObject.datafeed,bounty.szaboRewardPerOracle);
}
function getOracleReward() returns (uint) {
return rewardForSuccessfulProphecies[msg.sender]*1 szabo;
}
function collectOracleReward() {
uint reward = getOracleReward();
rewardForSuccessfulProphecies[msg.sender] = 0;
msg.sender.transfer(reward);
}
function claimRefundsDue() {
uint refund = refundsForFailedBounties[msg.sender];
refundsForFailedBounties[msg.sender] = 0;
RefundProcessed(msg.sender);
msg.sender.transfer(refund);
}
function getBounties(string datafeed) returns (uint8[] sampleSize,uint8[] decimalPlaces,uint[] rewardPerOracle) {
for (uint i = 0; i<openBounties[datafeed].length;i++) {
sampleSize[i] = openBounties[datafeed][i].requiredSampleSize;
decimalPlaces[i] = openBounties[datafeed][i].decimalPlaces;
rewardPerOracle[i] = openBounties[datafeed][i].szaboRewardPerOracle;
}
}
function offerKreshmoi(string datafeed, uint8 index, int64 predictionValue) {//TODO: limiting factor on number of open bounties to participate in
Bounty memory bounty = openBounties[datafeed][index];
if (bounty.earliestBlock==0 || block.number - uint(bounty.earliestBlock)>uint(bounty.maxBlockRange)) {
clearBounty(datafeed,index,"Max block registers exceeded. All previous bounty hunters have been erased. Bounty reset at current block.");
}
int128[] memory registers = new int128[](4);//0 = smallest,1 = largest,2 = average value,3 = order of magnitude
if (bounty.predictions.length>0) {
registers[0] = bounty.predictions[0];
registers[1] = bounty.predictions[0];
} else {
registers[0] = 0;
registers[1] = 0;
}
for (uint j = 1;j<bounty.predictions.length;j++) {
registers[2] += bounty.predictions[j];
if (registers[1] < bounty.predictions[j])
registers[1] = bounty.predictions[j];
if (registers[0] > bounty.predictions[j])
registers[0] = bounty.predictions[j];
}
if (predictionValue > registers[1])
registers[1] = predictionValue;
if (uint(registers[1]-registers[0])>bounty.maxValueRange) {
clearBounty(datafeed,index,"The kreshmoi offered exceeded the maximum allowable registers for this bounty. All previous bounty hunters have been erased. Bounty reset at current block.");
}
for (j = 0;j < openBounties[datafeed][index].oracles.length;j++) {
if (openBounties[datafeed][index].oracles[j]==msg.sender) {
KreshmoiOfferFailed (msg.sender, datafeed, "oracle cannot post 2 predictions for same bounty");
return;
}
}
openBounties[datafeed][index].predictions.push(predictionValue);
openBounties[datafeed][index].oracles.push(msg.sender);
if (openBounties[datafeed][index].predictions.length == bounty.requiredSampleSize) {
registers[2] += predictionValue;
registers[3] = 1;
for (j = 0;j < openBounties[datafeed][index].decimalPlaces;j++) {
registers[3]*=10;
}
registers[2] *= registers[3];
registers[2] /= openBounties[datafeed][index].requiredSampleSize;
successfulKreshmoi[datafeed].push(Kreshmoi({
blockRange: uint16(block.number - openBounties[datafeed][index].earliestBlock),
decimalPlaces:openBounties[datafeed][index].decimalPlaces,
value: int64(registers[2]),
sampleSize:openBounties[datafeed][index].requiredSampleSize,
valueRange:uint(registers[1]-registers[0]),
bountyPoster:openBounties[datafeed][index].poster
}));
address[] memory oracles = bounty.oracles;
uint reward = bounty.szaboRewardPerOracle;
for (j = 0;j<oracles.length;j++) {
rewardForSuccessfulProphecies[oracles[j]] += reward;
}
delete openBounties[datafeed][index];
for (j = index;j<openBounties[datafeed].length-1;j++) {
openBounties[datafeed][j] = openBounties[datafeed][j+1];
}
KreshmoiOffered(msg.sender,datafeed);
ProphecyDelivered(datafeed);
return;
}
KreshmoiOffered(msg.sender,datafeed);
}
function getKreshmoi(string datafeed) returns (int64[],uint8[]) {
int64[] memory values = new int64[](successfulKreshmoi[datafeed].length);
uint8[] memory decimalPlaces = new uint8[](successfulKreshmoi[datafeed].length);
for (uint i =0;i<successfulKreshmoi[datafeed].length;i++) {
values[i] = successfulKreshmoi[datafeed][i].value;
decimalPlaces[i] = successfulKreshmoi[datafeed][i].decimalPlaces;
}
return (values, decimalPlaces);
}
function clearBounty(string datafeed, uint index, string reason) internal {
openBounties[datafeed][index].earliestBlock = block.number;
delete openBounties[datafeed][index].predictions;
delete openBounties[datafeed][index].oracles;
BountyCleared(datafeed,index,reason);
}
function validateDataFeedFails(string datafeed, address sender) internal returns(bool) {
bytes memory chararray = bytes(datafeed);
if (chararray.length>10) {
BountyValidationCheckFailed(datafeed, sender, "datafeed name must contain at most 10 characters");
return true;
}
if (chararray.length<3) {
BountyValidationCheckFailed(datafeed, sender, "datafeed name must contain at least 3 characters");
return true;
}
string memory validString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
bytes memory validCharacterSet = bytes(validString);
Debugging(datafeed);
for (uint i = 0;i<chararray.length;i++) {
bool existsInValidSet = false;
for (uint j =0;j<36;j++) {
if (chararray[i]==validCharacterSet[j])
existsInValidSet= true;
}
if (!existsInValidSet) {
BountyValidationCheckFailed(datafeed, sender,"Characters must be uppercase alphanumeric.");
return true;
}
}
return false;
}
event Debugging(string message);
event DebuggingUINT(string message,uint additional);
event BountyValidationCheckFailed(string datafeed, address from, string reason);
event InvalidBountyValidationTicket(address sender, string datafeed);
event BountListFull(string datafeed);
event BountyCleared(string datafeed, uint index, string reason);
event BountyPosted (address from, string datafeed, uint rewardPerOracle);
event KreshmoiOffered (address from, string datafeed);
event KreshmoiOfferFailed (address from, string datafeed, string reason);
event ProphecyDelivered (string datafeed);
event RefundProcessed(address collector);
event ValidationTicketGenerated(address bountyPost);
} | spam prevention penalty
| refundsForFailedBounties[refundAddress] += refund*9/10; | 929,283 | [
1,
1752,
301,
5309,
285,
23862,
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,
5411,
16255,
28388,
2925,
38,
592,
606,
63,
1734,
1074,
1887,
65,
1011,
16255,
14,
29,
19,
2163,
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
]
|
./partial_match/1/0xf750eD63528f98B7934D33D39a24D5E0D6797A13/sources/SimpleDappMakerProject.sol | When start - 1 buy in 1 block
| bool public transferDelayEnabled = true; | 3,694,494 | [
1,
9434,
787,
300,
404,
30143,
316,
404,
1203,
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,
1426,
1071,
7412,
6763,
1526,
273,
638,
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
]
|
./full_match/5/0xf738870a8063a060f59E3754C89039663bA1b027/sources/contracts/messagePassingBridge/MessagePassingBridge.sol | * @dev Function for setting the bridge fees @param fees The bridge fees to set/ | function setBridgeFees(BridgeFees memory fees) external onlyOwnerOrGuardian {
bridgeFees = fees;
}
| 1,858,639 | [
1,
2083,
364,
3637,
326,
10105,
1656,
281,
225,
1656,
281,
1021,
10105,
1656,
281,
358,
444,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
444,
13691,
2954,
281,
12,
13691,
2954,
281,
3778,
1656,
281,
13,
3903,
1338,
5541,
1162,
16709,
2779,
288,
203,
3639,
10105,
2954,
281,
273,
1656,
281,
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
]
|
/**
*Submitted for verification at Etherscan.io on 2021-07-08
*/
// Sources flattened with hardhat v2.4.0 https://hardhat.org
// File contracts/auxiliary/interfaces/v0.8.4/IERC20Aux.sol
pragma solidity 0.8.4;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Aux {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File contracts/auxiliary/interfaces/v0.8.4/IApi3Token.sol
pragma solidity 0.8.4;
interface IApi3Token is IERC20Aux {
event MinterStatusUpdated(
address indexed minterAddress,
bool minterStatus
);
event BurnerStatusUpdated(
address indexed burnerAddress,
bool burnerStatus
);
function updateMinterStatus(
address minterAddress,
bool minterStatus
)
external;
function updateBurnerStatus(bool burnerStatus)
external;
function mint(
address account,
uint256 amount
)
external;
function burn(uint256 amount)
external;
function getMinterStatus(address minterAddress)
external
view
returns (bool minterStatus);
function getBurnerStatus(address burnerAddress)
external
view
returns (bool burnerStatus);
}
// File contracts/interfaces/IStateUtils.sol
pragma solidity 0.8.4;
interface IStateUtils {
event SetDaoApps(
address agentAppPrimary,
address agentAppSecondary,
address votingAppPrimary,
address votingAppSecondary
);
event SetClaimsManagerStatus(
address indexed claimsManager,
bool indexed status
);
event SetStakeTarget(uint256 stakeTarget);
event SetMaxApr(uint256 maxApr);
event SetMinApr(uint256 minApr);
event SetUnstakeWaitPeriod(uint256 unstakeWaitPeriod);
event SetAprUpdateStep(uint256 aprUpdateStep);
event SetProposalVotingPowerThreshold(uint256 proposalVotingPowerThreshold);
event UpdatedLastProposalTimestamp(
address indexed user,
uint256 lastProposalTimestamp,
address votingApp
);
function setDaoApps(
address _agentAppPrimary,
address _agentAppSecondary,
address _votingAppPrimary,
address _votingAppSecondary
)
external;
function setClaimsManagerStatus(
address claimsManager,
bool status
)
external;
function setStakeTarget(uint256 _stakeTarget)
external;
function setMaxApr(uint256 _maxApr)
external;
function setMinApr(uint256 _minApr)
external;
function setUnstakeWaitPeriod(uint256 _unstakeWaitPeriod)
external;
function setAprUpdateStep(uint256 _aprUpdateStep)
external;
function setProposalVotingPowerThreshold(uint256 _proposalVotingPowerThreshold)
external;
function updateLastProposalTimestamp(address userAddress)
external;
function isGenesisEpoch()
external
view
returns (bool);
}
// File contracts/StateUtils.sol
pragma solidity 0.8.4;
/// @title Contract that keeps state variables
contract StateUtils is IStateUtils {
struct Checkpoint {
uint32 fromBlock;
uint224 value;
}
struct AddressCheckpoint {
uint32 fromBlock;
address _address;
}
struct Reward {
uint32 atBlock;
uint224 amount;
uint256 totalSharesThen;
uint256 totalStakeThen;
}
struct User {
Checkpoint[] shares;
Checkpoint[] delegatedTo;
AddressCheckpoint[] delegates;
uint256 unstaked;
uint256 vesting;
uint256 unstakeAmount;
uint256 unstakeShares;
uint256 unstakeScheduledFor;
uint256 lastDelegationUpdateTimestamp;
uint256 lastProposalTimestamp;
}
struct LockedCalculation {
uint256 initialIndEpoch;
uint256 nextIndEpoch;
uint256 locked;
}
/// @notice Length of the epoch in which the staking reward is paid out
/// once. It is hardcoded as 7 days.
/// @dev In addition to regulating reward payments, this variable is used
/// for two additional things:
/// (1) After a user makes a proposal, they cannot make a second one
/// before `EPOCH_LENGTH` has passed
/// (2) After a user updates their delegation status, they have to wait
/// `EPOCH_LENGTH` before updating it again
uint256 public constant EPOCH_LENGTH = 1 weeks;
/// @notice Number of epochs before the staking rewards get unlocked.
/// Hardcoded as 52 epochs, which approximately corresponds to a year with
/// an `EPOCH_LENGTH` of 1 week.
uint256 public constant REWARD_VESTING_PERIOD = 52;
// All percentage values are represented as 1e18 = 100%
uint256 internal constant ONE_PERCENT = 1e18 / 100;
uint256 internal constant HUNDRED_PERCENT = 1e18;
// To assert that typecasts do not overflow
uint256 internal constant MAX_UINT32 = 2**32 - 1;
uint256 internal constant MAX_UINT224 = 2**224 - 1;
/// @notice Epochs are indexed as `block.timestamp / EPOCH_LENGTH`.
/// `genesisEpoch` is the index of the epoch in which the pool is deployed.
/// @dev No reward gets paid and proposals are not allowed in the genesis
/// epoch
uint256 public immutable genesisEpoch;
/// @notice API3 token contract
IApi3Token public immutable api3Token;
/// @notice TimelockManager contract
address public immutable timelockManager;
/// @notice Address of the primary Agent app of the API3 DAO
/// @dev Primary Agent can be operated through the primary Api3Voting app.
/// The primary Api3Voting app requires a higher quorum by default, and the
/// primary Agent is more privileged.
address public agentAppPrimary;
/// @notice Address of the secondary Agent app of the API3 DAO
/// @dev Secondary Agent can be operated through the secondary Api3Voting
/// app. The secondary Api3Voting app requires a lower quorum by default,
/// and the primary Agent is less privileged.
address public agentAppSecondary;
/// @notice Address of the primary Api3Voting app of the API3 DAO
/// @dev Used to operate the primary Agent
address public votingAppPrimary;
/// @notice Address of the secondary Api3Voting app of the API3 DAO
/// @dev Used to operate the secondary Agent
address public votingAppSecondary;
/// @notice Mapping that keeps the claims manager statuses of addresses
/// @dev A claims manager is a contract that is authorized to pay out
/// claims from the staking pool, effectively slashing the stakers. The
/// statuses are kept as a mapping to support multiple claims managers.
mapping(address => bool) public claimsManagerStatus;
/// @notice Records of rewards paid in each epoch
/// @dev `.atBlock` of a past epoch's reward record being `0` means no
/// reward was paid for that epoch
mapping(uint256 => Reward) public epochIndexToReward;
/// @notice Epoch index of the most recent reward
uint256 public epochIndexOfLastReward;
/// @notice Total number of tokens staked at the pool
uint256 public totalStake;
/// @notice Stake target the pool will aim to meet in percentages of the
/// total token supply. The staking rewards increase if the total staked
/// amount is below this, and vice versa.
/// @dev Default value is 50% of the total API3 token supply. This
/// parameter is governable by the DAO.
uint256 public stakeTarget = ONE_PERCENT * 50;
/// @notice Minimum APR (annual percentage rate) the pool will pay as
/// staking rewards in percentages
/// @dev Default value is 2.5%. This parameter is governable by the DAO.
uint256 public minApr = ONE_PERCENT * 25 / 10;
/// @notice Maximum APR (annual percentage rate) the pool will pay as
/// staking rewards in percentages
/// @dev Default value is 75%. This parameter is governable by the DAO.
uint256 public maxApr = ONE_PERCENT * 75;
/// @notice Steps in which APR will be updated in percentages
/// @dev Default value is 1%. This parameter is governable by the DAO.
uint256 public aprUpdateStep = ONE_PERCENT;
/// @notice Users need to schedule an unstake and wait for
/// `unstakeWaitPeriod` before being able to unstake. This is to prevent
/// the stakers from frontrunning insurance claims by unstaking to evade
/// them, or repeatedly unstake/stake to work around the proposal spam
/// protection. The tokens awaiting to be unstaked during this period do
/// not grant voting power or rewards.
/// @dev This parameter is governable by the DAO, and the DAO is expected
/// to set this to a value that is large enough to allow insurance claims
/// to be resolved.
uint256 public unstakeWaitPeriod = EPOCH_LENGTH;
/// @notice Minimum voting power the users must have to be able to make
/// proposals (in percentages)
/// @dev Delegations count towards voting power.
/// Default value is 0.1%. This parameter is governable by the DAO.
uint256 public proposalVotingPowerThreshold = ONE_PERCENT / 10;
/// @notice APR that will be paid next epoch
/// @dev This value will reach an equilibrium based on the stake target.
/// Every epoch (week), APR/52 of the total staked tokens will be added to
/// the pool, effectively distributing them to the stakers.
uint256 public apr = (maxApr + minApr) / 2;
/// @notice User records
mapping(address => User) public users;
// Keeps the total number of shares of the pool
Checkpoint[] public poolShares;
// Keeps user states used in `withdrawPrecalculated()` calls
mapping(address => LockedCalculation) public userToLockedCalculation;
// Kept to prevent third parties from frontrunning the initialization
// `setDaoApps()` call and grief the deployment
address private deployer;
/// @dev Reverts if the caller is not an API3 DAO Agent
modifier onlyAgentApp() {
require(
msg.sender == agentAppPrimary || msg.sender == agentAppSecondary,
"Pool: Caller not agent"
);
_;
}
/// @dev Reverts if the caller is not the primary API3 DAO Agent
modifier onlyAgentAppPrimary() {
require(
msg.sender == agentAppPrimary,
"Pool: Caller not primary agent"
);
_;
}
/// @dev Reverts if the caller is not an API3 DAO Api3Voting app
modifier onlyVotingApp() {
require(
msg.sender == votingAppPrimary || msg.sender == votingAppSecondary,
"Pool: Caller not voting app"
);
_;
}
/// @param api3TokenAddress API3 token contract address
/// @param timelockManagerAddress Timelock manager contract address
constructor(
address api3TokenAddress,
address timelockManagerAddress
)
{
require(
api3TokenAddress != address(0),
"Pool: Invalid Api3Token"
);
require(
timelockManagerAddress != address(0),
"Pool: Invalid TimelockManager"
);
deployer = msg.sender;
api3Token = IApi3Token(api3TokenAddress);
timelockManager = timelockManagerAddress;
// Initialize the share price at 1
updateCheckpointArray(poolShares, 1);
totalStake = 1;
// Set the current epoch as the genesis epoch and skip its reward
// payment
uint256 currentEpoch = block.timestamp / EPOCH_LENGTH;
genesisEpoch = currentEpoch;
epochIndexOfLastReward = currentEpoch;
}
/// @notice Called after deployment to set the addresses of the DAO apps
/// @dev This can also be called later on by the primary Agent to update
/// all app addresses as a means of an upgrade
/// @param _agentAppPrimary Address of the primary Agent
/// @param _agentAppSecondary Address of the secondary Agent
/// @param _votingAppPrimary Address of the primary Api3Voting app
/// @param _votingAppSecondary Address of the secondary Api3Voting app
function setDaoApps(
address _agentAppPrimary,
address _agentAppSecondary,
address _votingAppPrimary,
address _votingAppSecondary
)
external
override
{
// solhint-disable-next-line reason-string
require(
msg.sender == agentAppPrimary
|| (agentAppPrimary == address(0) && msg.sender == deployer),
"Pool: Caller not primary agent or deployer initializing values"
);
require(
_agentAppPrimary != address(0)
&& _agentAppSecondary != address(0)
&& _votingAppPrimary != address(0)
&& _votingAppSecondary != address(0),
"Pool: Invalid DAO apps"
);
agentAppPrimary = _agentAppPrimary;
agentAppSecondary = _agentAppSecondary;
votingAppPrimary = _votingAppPrimary;
votingAppSecondary = _votingAppSecondary;
emit SetDaoApps(
agentAppPrimary,
agentAppSecondary,
votingAppPrimary,
votingAppSecondary
);
}
/// @notice Called by the primary DAO Agent to set the authorization status
/// of a claims manager contract
/// @dev The claims manager is a trusted contract that is allowed to
/// withdraw as many tokens as it wants from the pool to pay out insurance
/// claims.
/// Only the primary Agent can do this because it is a critical operation.
/// WARNING: A compromised contract being given claims manager status may
/// result in loss of staked funds. If a proposal has been made to call
/// this method to set a contract as a claims manager, you are recommended
/// to review the contract yourself and/or refer to the audit reports to
/// understand the implications.
/// @param claimsManager Claims manager contract address
/// @param status Authorization status
function setClaimsManagerStatus(
address claimsManager,
bool status
)
external
override
onlyAgentAppPrimary()
{
claimsManagerStatus[claimsManager] = status;
emit SetClaimsManagerStatus(
claimsManager,
status
);
}
/// @notice Called by the DAO Agent to set the stake target
/// @param _stakeTarget Stake target
function setStakeTarget(uint256 _stakeTarget)
external
override
onlyAgentApp()
{
require(
_stakeTarget <= HUNDRED_PERCENT,
"Pool: Invalid percentage value"
);
stakeTarget = _stakeTarget;
emit SetStakeTarget(_stakeTarget);
}
/// @notice Called by the DAO Agent to set the maximum APR
/// @param _maxApr Maximum APR
function setMaxApr(uint256 _maxApr)
external
override
onlyAgentApp()
{
require(
_maxApr >= minApr,
"Pool: Max APR smaller than min"
);
maxApr = _maxApr;
emit SetMaxApr(_maxApr);
}
/// @notice Called by the DAO Agent to set the minimum APR
/// @param _minApr Minimum APR
function setMinApr(uint256 _minApr)
external
override
onlyAgentApp()
{
require(
_minApr <= maxApr,
"Pool: Min APR larger than max"
);
minApr = _minApr;
emit SetMinApr(_minApr);
}
/// @notice Called by the primary DAO Agent to set the unstake waiting
/// period
/// @dev This may want to be increased to provide more time for insurance
/// claims to be resolved.
/// Even when the insurance functionality is not implemented, the minimum
/// valid value is `EPOCH_LENGTH` to prevent users from unstaking,
/// withdrawing and staking with another address to work around the
/// proposal spam protection.
/// Only the primary Agent can do this because it is a critical operation.
/// @param _unstakeWaitPeriod Unstake waiting period
function setUnstakeWaitPeriod(uint256 _unstakeWaitPeriod)
external
override
onlyAgentAppPrimary()
{
require(
_unstakeWaitPeriod >= EPOCH_LENGTH,
"Pool: Period shorter than epoch"
);
unstakeWaitPeriod = _unstakeWaitPeriod;
emit SetUnstakeWaitPeriod(_unstakeWaitPeriod);
}
/// @notice Called by the primary DAO Agent to set the APR update steps
/// @dev aprUpdateStep can be 0% or 100%+.
/// Only the primary Agent can do this because it is a critical operation.
/// @param _aprUpdateStep APR update steps
function setAprUpdateStep(uint256 _aprUpdateStep)
external
override
onlyAgentAppPrimary()
{
aprUpdateStep = _aprUpdateStep;
emit SetAprUpdateStep(_aprUpdateStep);
}
/// @notice Called by the primary DAO Agent to set the voting power
/// threshold for proposals
/// @dev Only the primary Agent can do this because it is a critical
/// operation.
/// @param _proposalVotingPowerThreshold Voting power threshold for
/// proposals
function setProposalVotingPowerThreshold(uint256 _proposalVotingPowerThreshold)
external
override
onlyAgentAppPrimary()
{
require(
_proposalVotingPowerThreshold >= ONE_PERCENT / 10
&& _proposalVotingPowerThreshold <= ONE_PERCENT * 10,
"Pool: Threshold outside limits");
proposalVotingPowerThreshold = _proposalVotingPowerThreshold;
emit SetProposalVotingPowerThreshold(_proposalVotingPowerThreshold);
}
/// @notice Called by a DAO Api3Voting app at proposal creation-time to
/// update the timestamp of the user's last proposal
/// @param userAddress User address
function updateLastProposalTimestamp(address userAddress)
external
override
onlyVotingApp()
{
users[userAddress].lastProposalTimestamp = block.timestamp;
emit UpdatedLastProposalTimestamp(
userAddress,
block.timestamp,
msg.sender
);
}
/// @notice Called to check if we are in the genesis epoch
/// @dev Voting apps use this to prevent proposals from being made in the
/// genesis epoch
/// @return If the current epoch is the genesis epoch
function isGenesisEpoch()
external
view
override
returns (bool)
{
return block.timestamp / EPOCH_LENGTH == genesisEpoch;
}
/// @notice Called internally to update a checkpoint array by pushing a new
/// checkpoint
/// @dev We assume `block.number` will always fit in a uint32 and `value`
/// will always fit in a uint224. `value` will either be a raw token amount
/// or a raw pool share amount so this assumption will be correct in
/// practice with a token with 18 decimals, 1e8 initial total supply and no
/// hyperinflation.
/// @param checkpointArray Checkpoint array
/// @param value Value to be used to create the new checkpoint
function updateCheckpointArray(
Checkpoint[] storage checkpointArray,
uint256 value
)
internal
{
assert(block.number <= MAX_UINT32);
assert(value <= MAX_UINT224);
checkpointArray.push(Checkpoint({
fromBlock: uint32(block.number),
value: uint224(value)
}));
}
/// @notice Called internally to update an address-checkpoint array by
/// pushing a new checkpoint
/// @dev We assume `block.number` will always fit in a uint32
/// @param addressCheckpointArray Address-checkpoint array
/// @param _address Address to be used to create the new checkpoint
function updateAddressCheckpointArray(
AddressCheckpoint[] storage addressCheckpointArray,
address _address
)
internal
{
assert(block.number <= MAX_UINT32);
addressCheckpointArray.push(AddressCheckpoint({
fromBlock: uint32(block.number),
_address: _address
}));
}
}
// File contracts/interfaces/IGetterUtils.sol
pragma solidity 0.8.4;
interface IGetterUtils is IStateUtils {
function userVotingPowerAt(
address userAddress,
uint256 _block
)
external
view
returns (uint256);
function userVotingPower(address userAddress)
external
view
returns (uint256);
function totalSharesAt(uint256 _block)
external
view
returns (uint256);
function totalShares()
external
view
returns (uint256);
function userSharesAt(
address userAddress,
uint256 _block
)
external
view
returns (uint256);
function userShares(address userAddress)
external
view
returns (uint256);
function userStake(address userAddress)
external
view
returns (uint256);
function delegatedToUserAt(
address userAddress,
uint256 _block
)
external
view
returns (uint256);
function delegatedToUser(address userAddress)
external
view
returns (uint256);
function userDelegateAt(
address userAddress,
uint256 _block
)
external
view
returns (address);
function userDelegate(address userAddress)
external
view
returns (address);
function userLocked(address userAddress)
external
view
returns (uint256);
function getUser(address userAddress)
external
view
returns (
uint256 unstaked,
uint256 vesting,
uint256 unstakeShares,
uint256 unstakeAmount,
uint256 unstakeScheduledFor,
uint256 lastDelegationUpdateTimestamp,
uint256 lastProposalTimestamp
);
}
// File contracts/GetterUtils.sol
pragma solidity 0.8.4;
/// @title Contract that implements getters
abstract contract GetterUtils is StateUtils, IGetterUtils {
/// @notice Called to get the voting power of a user at a specific block
/// @param userAddress User address
/// @param _block Block number for which the query is being made for
/// @return Voting power of the user at the block
function userVotingPowerAt(
address userAddress,
uint256 _block
)
public
view
override
returns (uint256)
{
// Users that have a delegate have no voting power
if (userDelegateAt(userAddress, _block) != address(0))
{
return 0;
}
return userSharesAt(userAddress, _block)
+ delegatedToUserAt(userAddress, _block);
}
/// @notice Called to get the current voting power of a user
/// @param userAddress User address
/// @return Current voting power of the user
function userVotingPower(address userAddress)
external
view
override
returns (uint256)
{
return userVotingPowerAt(userAddress, block.number);
}
/// @notice Called to get the total pool shares at a specific block
/// @dev Total pool shares also corresponds to total voting power
/// @param _block Block number for which the query is being made for
/// @return Total pool shares at the block
function totalSharesAt(uint256 _block)
public
view
override
returns (uint256)
{
return getValueAt(poolShares, _block);
}
/// @notice Called to get the current total pool shares
/// @dev Total pool shares also corresponds to total voting power
/// @return Current total pool shares
function totalShares()
public
view
override
returns (uint256)
{
return totalSharesAt(block.number);
}
/// @notice Called to get the pool shares of a user at a specific block
/// @param userAddress User address
/// @param _block Block number for which the query is being made for
/// @return Pool shares of the user at the block
function userSharesAt(
address userAddress,
uint256 _block
)
public
view
override
returns (uint256)
{
return getValueAt(users[userAddress].shares, _block);
}
/// @notice Called to get the current pool shares of a user
/// @param userAddress User address
/// @return Current pool shares of the user
function userShares(address userAddress)
public
view
override
returns (uint256)
{
return userSharesAt(userAddress, block.number);
}
/// @notice Called to get the current staked tokens of the user
/// @param userAddress User address
/// @return Current staked tokens of the user
function userStake(address userAddress)
public
view
override
returns (uint256)
{
return userShares(userAddress) * totalStake / totalShares();
}
/// @notice Called to get the voting power delegated to a user at a
/// specific block
/// @param userAddress User address
/// @param _block Block number for which the query is being made for
/// @return Voting power delegated to the user at the block
function delegatedToUserAt(
address userAddress,
uint256 _block
)
public
view
override
returns (uint256)
{
return getValueAt(users[userAddress].delegatedTo, _block);
}
/// @notice Called to get the current voting power delegated to a user
/// @param userAddress User address
/// @return Current voting power delegated to the user
function delegatedToUser(address userAddress)
public
view
override
returns (uint256)
{
return delegatedToUserAt(userAddress, block.number);
}
/// @notice Called to get the delegate of the user at a specific block
/// @param userAddress User address
/// @param _block Block number
/// @return Delegate of the user at the specific block
function userDelegateAt(
address userAddress,
uint256 _block
)
public
view
override
returns (address)
{
return getAddressAt(users[userAddress].delegates, _block);
}
/// @notice Called to get the current delegate of the user
/// @param userAddress User address
/// @return Current delegate of the user
function userDelegate(address userAddress)
public
view
override
returns (address)
{
return userDelegateAt(userAddress, block.number);
}
/// @notice Called to get the current locked tokens of the user
/// @param userAddress User address
/// @return locked Current locked tokens of the user
function userLocked(address userAddress)
public
view
override
returns (uint256 locked)
{
Checkpoint[] storage _userShares = users[userAddress].shares;
uint256 currentEpoch = block.timestamp / EPOCH_LENGTH;
uint256 oldestLockedEpoch = getOldestLockedEpoch();
uint256 indUserShares = _userShares.length;
for (
uint256 indEpoch = currentEpoch;
indEpoch >= oldestLockedEpoch;
indEpoch--
)
{
// The user has never staked at this point, we can exit early
if (indUserShares == 0)
{
break;
}
Reward storage lockedReward = epochIndexToReward[indEpoch];
if (lockedReward.atBlock != 0)
{
for (; indUserShares > 0; indUserShares--)
{
Checkpoint storage userShare = _userShares[indUserShares - 1];
if (userShare.fromBlock <= lockedReward.atBlock)
{
locked += lockedReward.amount * userShare.value / lockedReward.totalSharesThen;
break;
}
}
}
}
}
/// @notice Called to get the details of a user
/// @param userAddress User address
/// @return unstaked Amount of unstaked API3 tokens
/// @return vesting Amount of API3 tokens locked by vesting
/// @return unstakeAmount Amount scheduled to unstake
/// @return unstakeShares Shares revoked to unstake
/// @return unstakeScheduledFor Time unstaking is scheduled for
/// @return lastDelegationUpdateTimestamp Time of last delegation update
/// @return lastProposalTimestamp Time when the user made their most
/// recent proposal
function getUser(address userAddress)
external
view
override
returns (
uint256 unstaked,
uint256 vesting,
uint256 unstakeAmount,
uint256 unstakeShares,
uint256 unstakeScheduledFor,
uint256 lastDelegationUpdateTimestamp,
uint256 lastProposalTimestamp
)
{
User storage user = users[userAddress];
unstaked = user.unstaked;
vesting = user.vesting;
unstakeAmount = user.unstakeAmount;
unstakeShares = user.unstakeShares;
unstakeScheduledFor = user.unstakeScheduledFor;
lastDelegationUpdateTimestamp = user.lastDelegationUpdateTimestamp;
lastProposalTimestamp = user.lastProposalTimestamp;
}
/// @notice Called to get the value of a checkpoint array at a specific
/// block using binary search
/// @dev Adapted from
/// https://github.com/aragon/minime/blob/1d5251fc88eee5024ff318d95bc9f4c5de130430/contracts/MiniMeToken.sol#L431
/// @param checkpoints Checkpoints array
/// @param _block Block number for which the query is being made
/// @return Value of the checkpoint array at the block
function getValueAt(
Checkpoint[] storage checkpoints,
uint256 _block
)
internal
view
returns (uint256)
{
if (checkpoints.length == 0)
return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length -1].fromBlock)
return checkpoints[checkpoints.length - 1].value;
if (_block < checkpoints[0].fromBlock)
return 0;
// Limit the search to the last 1024 elements if the value being
// searched falls within that window
uint min = 0;
if (
checkpoints.length > 1024
&& checkpoints[checkpoints.length - 1024].fromBlock < _block
)
{
min = checkpoints.length - 1024;
}
// Binary search of the value in the array
uint max = checkpoints.length - 1;
while (max > min) {
uint mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock <= _block) {
min = mid;
} else {
max = mid - 1;
}
}
return checkpoints[min].value;
}
/// @notice Called to get the value of an address-checkpoint array at a
/// specific block using binary search
/// @dev Adapted from
/// https://github.com/aragon/minime/blob/1d5251fc88eee5024ff318d95bc9f4c5de130430/contracts/MiniMeToken.sol#L431
/// @param checkpoints Address-checkpoint array
/// @param _block Block number for which the query is being made
/// @return Value of the address-checkpoint array at the block
function getAddressAt(
AddressCheckpoint[] storage checkpoints,
uint256 _block
)
private
view
returns (address)
{
if (checkpoints.length == 0)
return address(0);
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length -1].fromBlock)
return checkpoints[checkpoints.length - 1]._address;
if (_block < checkpoints[0].fromBlock)
return address(0);
// Limit the search to the last 1024 elements if the value being
// searched falls within that window
uint min = 0;
if (
checkpoints.length > 1024
&& checkpoints[checkpoints.length - 1024].fromBlock < _block
)
{
min = checkpoints.length - 1024;
}
// Binary search of the value in the array
uint max = checkpoints.length - 1;
while (max > min) {
uint mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock <= _block) {
min = mid;
} else {
max = mid - 1;
}
}
return checkpoints[min]._address;
}
/// @notice Called internally to get the index of the oldest epoch whose
/// reward should be locked in the current epoch
/// @return oldestLockedEpoch Index of the oldest epoch with locked rewards
function getOldestLockedEpoch()
internal
view
returns (uint256 oldestLockedEpoch)
{
uint256 currentEpoch = block.timestamp / EPOCH_LENGTH;
oldestLockedEpoch = currentEpoch - REWARD_VESTING_PERIOD + 1;
if (oldestLockedEpoch < genesisEpoch + 1)
{
oldestLockedEpoch = genesisEpoch + 1;
}
}
}
// File contracts/interfaces/IRewardUtils.sol
pragma solidity 0.8.4;
interface IRewardUtils is IGetterUtils {
event MintedReward(
uint256 indexed epochIndex,
uint256 amount,
uint256 newApr,
uint256 totalStake
);
function mintReward()
external;
}
// File contracts/RewardUtils.sol
pragma solidity 0.8.4;
/// @title Contract that implements reward payments
abstract contract RewardUtils is GetterUtils, IRewardUtils {
/// @notice Called to mint the staking reward
/// @dev Skips past epochs for which rewards have not been paid for.
/// Skips the reward payment if the pool is not authorized to mint tokens.
/// Neither of these conditions will occur in practice.
function mintReward()
public
override
{
uint256 currentEpoch = block.timestamp / EPOCH_LENGTH;
// This will be skipped in most cases because someone else will have
// triggered the payment for this epoch
if (epochIndexOfLastReward < currentEpoch)
{
if (api3Token.getMinterStatus(address(this)))
{
uint256 rewardAmount = totalStake * apr * EPOCH_LENGTH / 365 days / HUNDRED_PERCENT;
assert(block.number <= MAX_UINT32);
assert(rewardAmount <= MAX_UINT224);
epochIndexToReward[currentEpoch] = Reward({
atBlock: uint32(block.number),
amount: uint224(rewardAmount),
totalSharesThen: totalShares(),
totalStakeThen: totalStake
});
api3Token.mint(address(this), rewardAmount);
totalStake += rewardAmount;
updateCurrentApr();
emit MintedReward(
currentEpoch,
rewardAmount,
apr,
totalStake
);
}
epochIndexOfLastReward = currentEpoch;
}
}
/// @notice Updates the current APR
/// @dev Called internally after paying out the reward
function updateCurrentApr()
internal
{
uint256 totalStakePercentage = totalStake
* HUNDRED_PERCENT
/ api3Token.totalSupply();
if (totalStakePercentage > stakeTarget)
{
apr = apr > aprUpdateStep ? apr - aprUpdateStep : 0;
}
else
{
apr += aprUpdateStep;
}
if (apr > maxApr) {
apr = maxApr;
}
else if (apr < minApr) {
apr = minApr;
}
}
}
// File contracts/interfaces/IDelegationUtils.sol
pragma solidity 0.8.4;
interface IDelegationUtils is IRewardUtils {
event Delegated(
address indexed user,
address indexed delegate,
uint256 shares,
uint256 totalDelegatedTo
);
event Undelegated(
address indexed user,
address indexed delegate,
uint256 shares,
uint256 totalDelegatedTo
);
event UpdatedDelegation(
address indexed user,
address indexed delegate,
bool delta,
uint256 shares,
uint256 totalDelegatedTo
);
function delegateVotingPower(address delegate)
external;
function undelegateVotingPower()
external;
}
// File contracts/DelegationUtils.sol
pragma solidity 0.8.4;
/// @title Contract that implements voting power delegation
abstract contract DelegationUtils is RewardUtils, IDelegationUtils {
/// @notice Called by the user to delegate voting power
/// @param delegate User address the voting power will be delegated to
function delegateVotingPower(address delegate)
external
override
{
mintReward();
require(
delegate != address(0) && delegate != msg.sender,
"Pool: Invalid delegate"
);
// Delegating users cannot use their voting power, so we are
// verifying that the delegate is not currently delegating. However,
// the delegate may delegate after they have been delegated to.
require(
userDelegate(delegate) == address(0),
"Pool: Delegate is delegating"
);
User storage user = users[msg.sender];
// Do not allow frequent delegation updates as that can be used to spam
// proposals
require(
user.lastDelegationUpdateTimestamp + EPOCH_LENGTH < block.timestamp,
"Pool: Updated delegate recently"
);
user.lastDelegationUpdateTimestamp = block.timestamp;
uint256 userShares = userShares(msg.sender);
require(
userShares != 0,
"Pool: Have no shares to delegate"
);
address previousDelegate = userDelegate(msg.sender);
require(
previousDelegate != delegate,
"Pool: Already delegated"
);
if (previousDelegate != address(0)) {
// Need to revoke previous delegation
updateCheckpointArray(
users[previousDelegate].delegatedTo,
delegatedToUser(previousDelegate) - userShares
);
}
// Assign the new delegation
uint256 delegatedToUpdate = delegatedToUser(delegate) + userShares;
updateCheckpointArray(
users[delegate].delegatedTo,
delegatedToUpdate
);
// Record the new delegate for the user
updateAddressCheckpointArray(
user.delegates,
delegate
);
emit Delegated(
msg.sender,
delegate,
userShares,
delegatedToUpdate
);
}
/// @notice Called by the user to undelegate voting power
function undelegateVotingPower()
external
override
{
mintReward();
User storage user = users[msg.sender];
address previousDelegate = userDelegate(msg.sender);
require(
previousDelegate != address(0),
"Pool: Not delegated"
);
require(
user.lastDelegationUpdateTimestamp + EPOCH_LENGTH < block.timestamp,
"Pool: Updated delegate recently"
);
user.lastDelegationUpdateTimestamp = block.timestamp;
uint256 userShares = userShares(msg.sender);
uint256 delegatedToUpdate = delegatedToUser(previousDelegate) - userShares;
updateCheckpointArray(
users[previousDelegate].delegatedTo,
delegatedToUpdate
);
updateAddressCheckpointArray(
user.delegates,
address(0)
);
emit Undelegated(
msg.sender,
previousDelegate,
userShares,
delegatedToUpdate
);
}
/// @notice Called internally when the user shares are updated to update
/// the delegated voting power
/// @dev User shares only get updated while staking or scheduling unstaking
/// @param shares Amount of shares that will be added/removed
/// @param delta Whether the shares will be added/removed (add for `true`,
/// and vice versa)
function updateDelegatedVotingPower(
uint256 shares,
bool delta
)
internal
{
address delegate = userDelegate(msg.sender);
if (delegate == address(0))
{
return;
}
uint256 currentDelegatedTo = delegatedToUser(delegate);
uint256 delegatedToUpdate = delta
? currentDelegatedTo + shares
: currentDelegatedTo - shares;
updateCheckpointArray(
users[delegate].delegatedTo,
delegatedToUpdate
);
emit UpdatedDelegation(
msg.sender,
delegate,
delta,
shares,
delegatedToUpdate
);
}
}
// File contracts/interfaces/ITransferUtils.sol
pragma solidity 0.8.4;
interface ITransferUtils is IDelegationUtils{
event Deposited(
address indexed user,
uint256 amount,
uint256 userUnstaked
);
event Withdrawn(
address indexed user,
uint256 amount,
uint256 userUnstaked
);
event CalculatingUserLocked(
address indexed user,
uint256 nextIndEpoch,
uint256 oldestLockedEpoch
);
event CalculatedUserLocked(
address indexed user,
uint256 amount
);
function depositRegular(uint256 amount)
external;
function withdrawRegular(uint256 amount)
external;
function precalculateUserLocked(
address userAddress,
uint256 noEpochsPerIteration
)
external
returns (bool finished);
function withdrawPrecalculated(uint256 amount)
external;
}
// File contracts/TransferUtils.sol
pragma solidity 0.8.4;
/// @title Contract that implements token transfer functionality
abstract contract TransferUtils is DelegationUtils, ITransferUtils {
/// @notice Called by the user to deposit tokens
/// @dev The user should approve the pool to spend at least `amount` tokens
/// before calling this.
/// The method is named `depositRegular()` to prevent potential confusion.
/// See `deposit()` for more context.
/// @param amount Amount to be deposited
function depositRegular(uint256 amount)
public
override
{
mintReward();
uint256 unstakedUpdate = users[msg.sender].unstaked + amount;
users[msg.sender].unstaked = unstakedUpdate;
// Should never return false because the API3 token uses the
// OpenZeppelin implementation
assert(api3Token.transferFrom(msg.sender, address(this), amount));
emit Deposited(
msg.sender,
amount,
unstakedUpdate
);
}
/// @notice Called by the user to withdraw tokens to their wallet
/// @dev The user should call `userLocked()` beforehand to ensure that
/// they have at least `amount` unlocked tokens to withdraw.
/// The method is named `withdrawRegular()` to be consistent with the name
/// `depositRegular()`. See `depositRegular()` for more context.
/// @param amount Amount to be withdrawn
function withdrawRegular(uint256 amount)
public
override
{
mintReward();
withdraw(amount, userLocked(msg.sender));
}
/// @notice Called to calculate the locked tokens of a user by making
/// multiple transactions
/// @dev If the user updates their `user.shares` by staking/unstaking too
/// frequently (50+/week) in the last `REWARD_VESTING_PERIOD`, the
/// `userLocked()` call gas cost may exceed the block gas limit. In that
/// case, the user may call this method multiple times to have their locked
/// tokens calculated and use `withdrawPrecalculated()` to withdraw.
/// @param userAddress User address
/// @param noEpochsPerIteration Number of epochs per iteration
/// @return finished Calculation has finished in this call
function precalculateUserLocked(
address userAddress,
uint256 noEpochsPerIteration
)
external
override
returns (bool finished)
{
mintReward();
require(
noEpochsPerIteration > 0,
"Pool: Zero iteration window"
);
uint256 currentEpoch = block.timestamp / EPOCH_LENGTH;
LockedCalculation storage lockedCalculation = userToLockedCalculation[userAddress];
// Reset the state if there was no calculation made in this epoch
if (lockedCalculation.initialIndEpoch != currentEpoch)
{
lockedCalculation.initialIndEpoch = currentEpoch;
lockedCalculation.nextIndEpoch = currentEpoch;
lockedCalculation.locked = 0;
}
uint256 indEpoch = lockedCalculation.nextIndEpoch;
uint256 locked = lockedCalculation.locked;
uint256 oldestLockedEpoch = getOldestLockedEpoch();
for (; indEpoch >= oldestLockedEpoch; indEpoch--)
{
if (lockedCalculation.nextIndEpoch >= indEpoch + noEpochsPerIteration)
{
lockedCalculation.nextIndEpoch = indEpoch;
lockedCalculation.locked = locked;
emit CalculatingUserLocked(
userAddress,
indEpoch,
oldestLockedEpoch
);
return false;
}
Reward storage lockedReward = epochIndexToReward[indEpoch];
if (lockedReward.atBlock != 0)
{
uint256 userSharesThen = userSharesAt(userAddress, lockedReward.atBlock);
locked += lockedReward.amount * userSharesThen / lockedReward.totalSharesThen;
}
}
lockedCalculation.nextIndEpoch = indEpoch;
lockedCalculation.locked = locked;
emit CalculatedUserLocked(userAddress, locked);
return true;
}
/// @notice Called by the user to withdraw after their locked token amount
/// is calculated with repeated calls to `precalculateUserLocked()`
/// @dev Only use `precalculateUserLocked()` and this method if
/// `withdrawRegular()` hits the block gas limit
/// @param amount Amount to be withdrawn
function withdrawPrecalculated(uint256 amount)
external
override
{
mintReward();
uint256 currentEpoch = block.timestamp / EPOCH_LENGTH;
LockedCalculation storage lockedCalculation = userToLockedCalculation[msg.sender];
require(
lockedCalculation.initialIndEpoch == currentEpoch,
"Pool: Calculation not up to date"
);
require(
lockedCalculation.nextIndEpoch < getOldestLockedEpoch(),
"Pool: Calculation not complete"
);
withdraw(amount, lockedCalculation.locked);
}
/// @notice Called internally after the amount of locked tokens of the user
/// is determined
/// @param amount Amount to be withdrawn
/// @param userLocked Amount of locked tokens of the user
function withdraw(
uint256 amount,
uint256 userLocked
)
private
{
User storage user = users[msg.sender];
// Check if the user has `amount` unlocked tokens to withdraw
uint256 lockedAndVesting = userLocked + user.vesting;
uint256 userTotalFunds = user.unstaked + userStake(msg.sender);
require(
userTotalFunds >= lockedAndVesting + amount,
"Pool: Not enough unlocked funds"
);
require(
user.unstaked >= amount,
"Pool: Not enough unstaked funds"
);
// Carry on with the withdrawal
uint256 unstakedUpdate = user.unstaked - amount;
user.unstaked = unstakedUpdate;
// Should never return false because the API3 token uses the
// OpenZeppelin implementation
assert(api3Token.transfer(msg.sender, amount));
emit Withdrawn(
msg.sender,
amount,
unstakedUpdate
);
}
}
// File contracts/interfaces/IStakeUtils.sol
pragma solidity 0.8.4;
interface IStakeUtils is ITransferUtils{
event Staked(
address indexed user,
uint256 amount,
uint256 mintedShares,
uint256 userUnstaked,
uint256 userShares,
uint256 totalShares,
uint256 totalStake
);
event ScheduledUnstake(
address indexed user,
uint256 amount,
uint256 shares,
uint256 scheduledFor,
uint256 userShares
);
event Unstaked(
address indexed user,
uint256 amount,
uint256 userUnstaked,
uint256 totalShares,
uint256 totalStake
);
function stake(uint256 amount)
external;
function depositAndStake(uint256 amount)
external;
function scheduleUnstake(uint256 amount)
external;
function unstake(address userAddress)
external
returns (uint256);
function unstakeAndWithdraw()
external;
}
// File contracts/StakeUtils.sol
pragma solidity 0.8.4;
/// @title Contract that implements staking functionality
abstract contract StakeUtils is TransferUtils, IStakeUtils {
/// @notice Called to stake tokens to receive pools in the share
/// @param amount Amount of tokens to stake
function stake(uint256 amount)
public
override
{
mintReward();
User storage user = users[msg.sender];
require(
user.unstaked >= amount,
"Pool: Amount exceeds unstaked"
);
uint256 userUnstakedUpdate = user.unstaked - amount;
user.unstaked = userUnstakedUpdate;
uint256 totalSharesNow = totalShares();
uint256 sharesToMint = amount * totalSharesNow / totalStake;
uint256 userSharesUpdate = userShares(msg.sender) + sharesToMint;
updateCheckpointArray(
user.shares,
userSharesUpdate
);
uint256 totalSharesUpdate = totalSharesNow + sharesToMint;
updateCheckpointArray(
poolShares,
totalSharesUpdate
);
totalStake += amount;
updateDelegatedVotingPower(sharesToMint, true);
emit Staked(
msg.sender,
amount,
sharesToMint,
userUnstakedUpdate,
userSharesUpdate,
totalSharesUpdate,
totalStake
);
}
/// @notice Convenience method to deposit and stake in a single transaction
/// @param amount Amount to be deposited and staked
function depositAndStake(uint256 amount)
external
override
{
depositRegular(amount);
stake(amount);
}
/// @notice Called by the user to schedule unstaking of their tokens
/// @dev While scheduling an unstake, `shares` get deducted from the user,
/// meaning that they will not receive rewards or voting power for them any
/// longer.
/// At unstaking-time, the user unstakes either the amount of tokens
/// scheduled to unstake, or the amount of tokens `shares` corresponds to
/// at unstaking-time, whichever is smaller. This corresponds to tokens
/// being scheduled to be unstaked not receiving any rewards, but being
/// subject to claim payouts.
/// In the instance that a claim has been paid out before an unstaking is
/// executed, the user may potentially receive rewards during
/// `unstakeWaitPeriod` (but not if there has not been a claim payout) but
/// the amount of tokens that they can unstake will not be able to exceed
/// the amount they scheduled the unstaking for.
/// @param amount Amount of tokens scheduled to unstake
function scheduleUnstake(uint256 amount)
external
override
{
mintReward();
uint256 userSharesNow = userShares(msg.sender);
uint256 totalSharesNow = totalShares();
uint256 userStaked = userSharesNow * totalStake / totalSharesNow;
require(
userStaked >= amount,
"Pool: Amount exceeds staked"
);
User storage user = users[msg.sender];
require(
user.unstakeScheduledFor == 0,
"Pool: Unexecuted unstake exists"
);
uint256 sharesToUnstake = amount * totalSharesNow / totalStake;
// This will only happen if the user wants to schedule an unstake for a
// few Wei
require(sharesToUnstake > 0, "Pool: Unstake amount too small");
uint256 unstakeScheduledFor = block.timestamp + unstakeWaitPeriod;
user.unstakeScheduledFor = unstakeScheduledFor;
user.unstakeAmount = amount;
user.unstakeShares = sharesToUnstake;
uint256 userSharesUpdate = userSharesNow - sharesToUnstake;
updateCheckpointArray(
user.shares,
userSharesUpdate
);
updateDelegatedVotingPower(sharesToUnstake, false);
emit ScheduledUnstake(
msg.sender,
amount,
sharesToUnstake,
unstakeScheduledFor,
userSharesUpdate
);
}
/// @notice Called to execute a pre-scheduled unstake
/// @dev Anyone can execute a matured unstake. This is to allow the user to
/// use bots, etc. to execute their unstaking as soon as possible.
/// @param userAddress User address
/// @return Amount of tokens that are unstaked
function unstake(address userAddress)
public
override
returns (uint256)
{
mintReward();
User storage user = users[userAddress];
require(
user.unstakeScheduledFor != 0,
"Pool: No unstake scheduled"
);
require(
user.unstakeScheduledFor < block.timestamp,
"Pool: Unstake not mature yet"
);
uint256 totalShares = totalShares();
uint256 unstakeAmount = user.unstakeAmount;
uint256 unstakeAmountByShares = user.unstakeShares * totalStake / totalShares;
// If there was a claim payout in between the scheduling and the actual
// unstake then the amount might be lower than expected at scheduling
// time
if (unstakeAmount > unstakeAmountByShares)
{
unstakeAmount = unstakeAmountByShares;
}
uint256 userUnstakedUpdate = user.unstaked + unstakeAmount;
user.unstaked = userUnstakedUpdate;
uint256 totalSharesUpdate = totalShares - user.unstakeShares;
updateCheckpointArray(
poolShares,
totalSharesUpdate
);
totalStake -= unstakeAmount;
user.unstakeAmount = 0;
user.unstakeShares = 0;
user.unstakeScheduledFor = 0;
emit Unstaked(
userAddress,
unstakeAmount,
userUnstakedUpdate,
totalSharesUpdate,
totalStake
);
return unstakeAmount;
}
/// @notice Convenience method to execute an unstake and withdraw to the
/// user's wallet in a single transaction
/// @dev The withdrawal will revert if the user has less than
/// `unstakeAmount` tokens that are withdrawable
function unstakeAndWithdraw()
external
override
{
withdrawRegular(unstake(msg.sender));
}
}
// File contracts/interfaces/IClaimUtils.sol
pragma solidity 0.8.4;
interface IClaimUtils is IStakeUtils {
event PaidOutClaim(
address indexed recipient,
uint256 amount,
uint256 totalStake
);
function payOutClaim(
address recipient,
uint256 amount
)
external;
}
// File contracts/ClaimUtils.sol
pragma solidity 0.8.4;
/// @title Contract that implements the insurance claim payout functionality
abstract contract ClaimUtils is StakeUtils, IClaimUtils {
/// @dev Reverts if the caller is not a claims manager
modifier onlyClaimsManager() {
require(
claimsManagerStatus[msg.sender],
"Pool: Caller not claims manager"
);
_;
}
/// @notice Called by a claims manager to pay out an insurance claim
/// @dev The claims manager is a trusted contract that is allowed to
/// withdraw as many tokens as it wants from the pool to pay out insurance
/// claims. Any kind of limiting logic (e.g., maximum amount of tokens that
/// can be withdrawn) is implemented at its end and is out of the scope of
/// this contract.
/// This will revert if the pool does not have enough staked funds.
/// @param recipient Recipient of the claim
/// @param amount Amount of tokens that will be paid out
function payOutClaim(
address recipient,
uint256 amount
)
external
override
onlyClaimsManager()
{
mintReward();
// totalStake should not go lower than 1
require(
totalStake > amount,
"Pool: Amount exceeds total stake"
);
totalStake -= amount;
// Should never return false because the API3 token uses the
// OpenZeppelin implementation
assert(api3Token.transfer(recipient, amount));
emit PaidOutClaim(
recipient,
amount,
totalStake
);
}
}
// File contracts/interfaces/ITimelockUtils.sol
pragma solidity 0.8.4;
interface ITimelockUtils is IClaimUtils {
event DepositedByTimelockManager(
address indexed user,
uint256 amount,
uint256 userUnstaked
);
event DepositedVesting(
address indexed user,
uint256 amount,
uint256 start,
uint256 end,
uint256 userUnstaked,
uint256 userVesting
);
event VestedTimelock(
address indexed user,
uint256 amount,
uint256 userVesting
);
function deposit(
address source,
uint256 amount,
address userAddress
)
external;
function depositWithVesting(
address source,
uint256 amount,
address userAddress,
uint256 releaseStart,
uint256 releaseEnd
)
external;
function updateTimelockStatus(address userAddress)
external;
}
// File contracts/TimelockUtils.sol
pragma solidity 0.8.4;
/// @title Contract that implements vesting functionality
/// @dev The TimelockManager contract interfaces with this contract to transfer
/// API3 tokens that are locked under a vesting schedule.
/// This contract keeps its own type definitions, event declarations and state
/// variables for them to be easier to remove for a subDAO where they will
/// likely not be used.
abstract contract TimelockUtils is ClaimUtils, ITimelockUtils {
struct Timelock {
uint256 totalAmount;
uint256 remainingAmount;
uint256 releaseStart;
uint256 releaseEnd;
}
/// @notice Maps user addresses to timelocks
/// @dev This implies that a user cannot have multiple timelocks
/// transferred from the TimelockManager contract. This is acceptable
/// because TimelockManager is implemented in a way to not allow multiple
/// timelocks per user.
mapping(address => Timelock) public userToTimelock;
/// @notice Called by the TimelockManager contract to deposit tokens on
/// behalf of a user
/// @dev This method is only usable by `TimelockManager.sol`.
/// It is named as `deposit()` and not `depositAsTimelockManager()` for
/// example, because the TimelockManager is already deployed and expects
/// the `deposit(address,uint256,address)` interface.
/// @param source Token transfer source
/// @param amount Amount to be deposited
/// @param userAddress User that the tokens will be deposited for
function deposit(
address source,
uint256 amount,
address userAddress
)
external
override
{
require(
msg.sender == timelockManager,
"Pool: Caller not TimelockManager"
);
uint256 unstakedUpdate = users[userAddress].unstaked + amount;
users[userAddress].unstaked = unstakedUpdate;
// Should never return false because the API3 token uses the
// OpenZeppelin implementation
assert(api3Token.transferFrom(source, address(this), amount));
emit DepositedByTimelockManager(
userAddress,
amount,
unstakedUpdate
);
}
/// @notice Called by the TimelockManager contract to deposit tokens on
/// behalf of a user on a linear vesting schedule
/// @dev Refer to `TimelockManager.sol` to see how this is used
/// @param source Token source
/// @param amount Token amount
/// @param userAddress Address of the user who will receive the tokens
/// @param releaseStart Vesting schedule starting time
/// @param releaseEnd Vesting schedule ending time
function depositWithVesting(
address source,
uint256 amount,
address userAddress,
uint256 releaseStart,
uint256 releaseEnd
)
external
override
{
require(
msg.sender == timelockManager,
"Pool: Caller not TimelockManager"
);
require(
userToTimelock[userAddress].remainingAmount == 0,
"Pool: User has active timelock"
);
require(
releaseEnd > releaseStart,
"Pool: Timelock start after end"
);
require(
amount != 0,
"Pool: Timelock amount zero"
);
uint256 unstakedUpdate = users[userAddress].unstaked + amount;
users[userAddress].unstaked = unstakedUpdate;
uint256 vestingUpdate = users[userAddress].vesting + amount;
users[userAddress].vesting = vestingUpdate;
userToTimelock[userAddress] = Timelock({
totalAmount: amount,
remainingAmount: amount,
releaseStart: releaseStart,
releaseEnd: releaseEnd
});
// Should never return false because the API3 token uses the
// OpenZeppelin implementation
assert(api3Token.transferFrom(source, address(this), amount));
emit DepositedVesting(
userAddress,
amount,
releaseStart,
releaseEnd,
unstakedUpdate,
vestingUpdate
);
}
/// @notice Called to release tokens vested by the timelock
/// @param userAddress Address of the user whose timelock status will be
/// updated
function updateTimelockStatus(address userAddress)
external
override
{
Timelock storage timelock = userToTimelock[userAddress];
require(
block.timestamp > timelock.releaseStart,
"Pool: Release not started yet"
);
require(
timelock.remainingAmount > 0,
"Pool: Timelock already released"
);
uint256 totalUnlocked;
if (block.timestamp >= timelock.releaseEnd)
{
totalUnlocked = timelock.totalAmount;
}
else
{
uint256 passedTime = block.timestamp - timelock.releaseStart;
uint256 totalTime = timelock.releaseEnd - timelock.releaseStart;
totalUnlocked = timelock.totalAmount * passedTime / totalTime;
}
uint256 previouslyUnlocked = timelock.totalAmount - timelock.remainingAmount;
uint256 newlyUnlocked = totalUnlocked - previouslyUnlocked;
User storage user = users[userAddress];
uint256 vestingUpdate = user.vesting - newlyUnlocked;
user.vesting = vestingUpdate;
timelock.remainingAmount -= newlyUnlocked;
emit VestedTimelock(
userAddress,
newlyUnlocked,
vestingUpdate
);
}
}
// File contracts/interfaces/IApi3Pool.sol
pragma solidity 0.8.4;
interface IApi3Pool is ITimelockUtils {
}
// File contracts/Api3Pool.sol
pragma solidity 0.8.4;
/// @title API3 pool contract
/// @notice Users can stake API3 tokens at the pool contract to be granted
/// shares. These shares are exposed to the Aragon-based DAO, giving the user
/// voting power at the DAO. Staking pays out weekly rewards that get unlocked
/// after a year, and staked funds are used to collateralize an insurance
/// product that is outside the scope of this contract.
/// @dev Functionalities of the contract are distributed to files that form a
/// chain of inheritance:
/// (1) Api3Pool.sol
/// (2) TimelockUtils.sol
/// (3) ClaimUtils.sol
/// (4) StakeUtils.sol
/// (5) TransferUtils.sol
/// (6) DelegationUtils.sol
/// (7) RewardUtils.sol
/// (8) GetterUtils.sol
/// (9) StateUtils.sol
contract Api3Pool is TimelockUtils, IApi3Pool {
/// @param api3TokenAddress API3 token contract address
/// @param timelockManagerAddress Timelock manager contract address
constructor(
address api3TokenAddress,
address timelockManagerAddress
)
StateUtils(
api3TokenAddress,
timelockManagerAddress
)
{}
} | @notice Called internally to get the index of the oldest epoch whose reward should be locked in the current epoch @return oldestLockedEpoch Index of the oldest epoch with locked rewards | function getOldestLockedEpoch()
internal
view
returns (uint256 oldestLockedEpoch)
{
uint256 currentEpoch = block.timestamp / EPOCH_LENGTH;
oldestLockedEpoch = currentEpoch - REWARD_VESTING_PERIOD + 1;
if (oldestLockedEpoch < genesisEpoch + 1)
{
oldestLockedEpoch = genesisEpoch + 1;
}
}
| 2,456,805 | [
1,
8185,
12963,
358,
336,
326,
770,
434,
326,
17067,
7632,
8272,
19890,
1410,
506,
8586,
316,
326,
783,
7632,
327,
17067,
8966,
14638,
3340,
434,
326,
17067,
7632,
598,
8586,
283,
6397,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
336,
7617,
395,
8966,
14638,
1435,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
17067,
8966,
14638,
13,
203,
565,
288,
203,
3639,
2254,
5034,
783,
14638,
273,
1203,
18,
5508,
342,
512,
30375,
67,
7096,
31,
203,
3639,
17067,
8966,
14638,
273,
783,
14638,
300,
2438,
21343,
67,
3412,
882,
1360,
67,
28437,
397,
404,
31,
203,
3639,
309,
261,
1673,
395,
8966,
14638,
411,
21906,
14638,
397,
404,
13,
203,
3639,
288,
203,
5411,
17067,
8966,
14638,
273,
21906,
14638,
397,
404,
31,
203,
3639,
289,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol";
import "@openzeppelin/contracts/token/ERC777/ERC777.sol";
import "@openzeppelin/contracts/token/ERC777/ERC777.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./Administration.sol";
import "./ERC777ReceiveSend.sol";
import "./xStarterInterfaces.sol";
import "./xStarterDeployers.sol";
//import "./UniswapInterface.sol";
// https://ropsten.etherscan.io/tx/0xd0fd6a146eca2faff282a10e7604fa1c0c334d6a8a6361e4694a743154b2798f
// must first approve amount
// https://ropsten.etherscan.io/tx/0x2f39644b43bb8f1407e4bb8bf9c1f6ceb116633be8be7c8fa2980235fa088c51
// transaction showing how to add liquidity for ETH to token pair
// xStarterPoolPairB: project tokens are swapped after total funding is raised. As Long as a Minimum funding amount is reached.
interface IERC20Custom {
function totalSupply() external view returns (uint256);
// function owner() external view returns (address);
function allowance(address owner_, address spender) external view returns (uint256);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function transfer(address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function balanceOf(address) external view returns (uint256);
function decimals() external view returns (uint8);
}
interface IERC20Uni {
function approve(address spender, uint256 amount) external returns (bool);
function transfer(address to, uint value) external returns (bool);
}
interface IUniswapRouter {
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);
// add liquidity, this will automatically create a pair for WETH
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
// get the WETH address
function WETH() external pure returns (address);
}
interface IUniswapFactory {
function getPair(address tokenA, address tokenB) external view returns (address pair);
}
struct Info {
uint8 _percentOfTokensForILO;
uint8 _percentTokensForTeam;
uint24 _dexDeadlineLength;
uint48 _contribTimeLock;
// length of lock for Liquidity tokens Minimum 365.25 days or 31557600 seconds
uint48 _liqPairLockLen;
uint _minPerSwap;
uint _minPerAddr;
uint _maxPerAddr;
uint _softcap;
uint _hardcap;
address _fundingToken;
address _addressOfDex;
address _addressOfDexFactory;
}
contract ProjectBaseToken is Context, ERC777, ERC777NoReceiveRecipient, ERC777NoSendSender {
using SafeMath for uint256;
using Address for address;
constructor(
string memory name_,
string memory symbol_,
uint totalSupply_,
address creatorAddr,
address[] memory defaultOperators_
) ERC777(name_, symbol_, defaultOperators_) {
// this will mint total supply
_mint(creatorAddr, totalSupply_, "", "");
// _mint(_msgSender(), totalSupply_, "", "");
}
}
contract ProjectBaseTokenERC20 is Context, ERC20{
using SafeMath for uint256;
using Address for address;
constructor(
string memory name_,
string memory symbol_,
uint totalSupply_,
address creatorAddr
) ERC20(name_, symbol_) {
// _setupDecimals(decimals_);
// this will mint total supply
_mint(creatorAddr, totalSupply_);
// _mint(_msgSender(), totalSupply_, "", "");
}
}
contract xStarterERCDeployer is BaseDeployer {
function deployToken(
string memory name_,
string memory symbol_,
uint totalTokenSupply_,
address[] memory defaultOperators_
) external onlyAllowedCaller returns(address ercToken){
//ProjectBaseToken newToken = new ProjectBaseToken(name_,symbol_, totalTokenSupply_, address(this), defaultOperators_);
ercToken = address(new ProjectBaseTokenERC20(name_,symbol_, totalTokenSupply_, msg.sender));
}
}
interface IXStarterERCDeployer {
function setAllowedCaller(address allowedCaller_) external returns(bool);
function deployToken(
string memory name_,
string memory symbol_,
uint totalTokenSupply_,
address[] memory defaultOperators_
) external returns(address ercToken);
}
contract xStarterPoolPairB is Administration, IERC777Recipient, IERC777Sender {
using SafeMath for uint256;
using Address for address;
// this is for xDai chain it's 5 seconds, goerli is 15 seconds. if deploying to other chains check the length of block creation, some are faster
uint MINE_LEN;
struct FunderInfo {
uint fundingTokenAmount;
uint projectTokenAmount;
}
struct SwapInfo {
uint24 fundTokenReceive;
uint24 projectTokenGive;
}
modifier onlySetup() {
require(_isSetup, "ILO has not been set up");
_;
}
modifier onlyOpen() {
require(isEventOpen(), "ILO event not open");
_;
}
modifier notCurrentlyFunding() {
require(!_currentlyFunding[_msgSender()], "Locked From Funding, A transaction you initiated has not been completed");
_;
}
modifier allowedToWithdraw() {
require(!_currentlyWithdrawing[_msgSender()], "Locked From Withdrawing, A transaction you initiated has not been completed");
_;
}
event TokenCreatedByXStarterPoolPair(address indexed TokenAddr_, address indexed PoolPairAddr_, address indexed Admin_, uint timestamp_);
event TokenSwapped(address indexed funder_, uint indexed tokensDesired, uint indexed tokensReceived_, uint tokensForLiq_);
Info private i;
// address private _addressOfDex;
// address private _addressOfDexFactory;
uint _decimals = 18;
// stores address of the project's token
address private _projectToken;
uint8 private _projectTokenDecimals;
// uint keeping track of total project's token supply.
//for record. this is used to make sure total token is the same as voted for by the community
uint private _totalTokensSupply;
// added to when token is transferred from admin address to contract.
// subtracted from when token is transfered to dex
// subtracted from when token can be withdrawn by participants and admin
uint private _tokensHeld;
// this is set up by the launchpad, it enforces what the project told the community
// if the project said 70% of tokens will be offered in the ILO. This will be set in the constructor.
// address _fundingToken; // if 0 then use nativeTokenSwap
// uint8 _fundingTokenDecimals;
// address of dex liquidity token pair, this is the pair that issues liquidity tokens from uniswap or deriivatives
address _liquidityPairAddress;
address _proposalAddr;
address _xStarterERCDeployer;
address _xStarterToken;
// Minimum xstarter token required to participate during private sale
uint _minXSTN;
address _xStarterLP;
// Minimum xstarter LP tokens required
uint _minXSTNLP;
uint _totalLPTokens; // amount of liquidity
uint _availLPTokens; // amount of liquidity
// timestamp when contributors can start withdrawing their their Liquidity pool tokens
uint _liqPairTimeLock;
uint _liqPairBlockLock;
uint8 private _percentOfTotalTokensForILO;
uint8 private _percentOfILOTokensForLiquidity = 50;
// timestamp of when contributors tokens will be free to withdraw
uint private _contribTimeStampLock;
// time stamp until project owner tokens are free usually double the length of contributor time
uint private _projTimeLock;
// block lock, use both timesamp and block number to add time lock
uint private _projBlockLock;
// the length in seconds of between block timestamp till timestamp when contributors can receive their tokens
//Minimum is 14 days equivalent or 1,209,600 seconds
// also project owners tokens are timelocked for either double the timelock of contributors or an additional 2 months
uint private _contribBlockLock;
// uint private _softcap;
// uint private _hardcap;
// uint private _minPerAddr = 1000000000000 wei;
// uint private _maxPerAddr;
// Minimum is 1 gwei, this is a really small amount and should only be overriden by a larger amount
SwapInfo private _swapRatio;
// uint amount of tokens aside for ILO.
uint private _totalTokensILO;
// tokens remaining for ILO
uint private _availTokensILO;
// tokens for liquidity
uint private _tokensForLiquidity;
// stores value of tokens for liquidity and is used to calculate contributors share
uint private _amountForProjTokenCalc;
// total funding tokens
uint _fundingTokenTotal;
// total funding tokens available. For non capital raising will be the same as i._fundingTokenTotal until liquidity pool is created
uint _fundingTokenAvail;
uint _fundingTokenForTeam;
// utc timestamp
uint48 private _startTime;
// uint timestamp
uint48 private _endTime;
// utc timestamp
uint48 private _pubStartTime;
// bool if xStarterPoolPair is set up
bool _isSetup;
//
bool _ILOValidated;
bool _ILOSuccess;
bool _approvedForLP;
bool _liquidityPairCreated;
uint private _adminBalance;
mapping(address => FunderInfo) private _funders;
mapping(address => bool) private _liqTokensWithdrawn;
mapping(address => bool) private _projTokensWithdrawn;
mapping(address => bool) private _currentlyFunding;
mapping(address => bool) private _currentlyWithdrawing;
// step 1
// todo: remove some of the unused parameters on the constructor
constructor(
address adminAddress,
address proposalAddr_,
address addressOfDex_,
address addressOfDexFactory_,
address xStarterToken_,
address xstarterLP_,
address xStarterERCDeployer_,
uint minXSTN_,
uint minXSTNLP_,
uint blockTime_
) Administration(adminAddress) {
// require(percentOfTokensForILO_ > 0 && percentOfTokensForILO_ <= 100, "percent of tokens must be between 1 and 100");
// require(projectTokenGive_ > 0 && fundTokenReceive_ > 0, "swap ratio is zero ");
// require(softcap_ > 0, "No softcap set");
(ILOProposal memory i_, ILOAdditionalInfo memory a_) = iXstarterProposal(proposalAddr_).getILOInfo();
MINE_LEN = blockTime_;
_proposalAddr = proposalAddr_;
_xStarterToken = xStarterToken_;
_xStarterLP = xstarterLP_;
_xStarterERCDeployer = xStarterERCDeployer_;
_minXSTN = minXSTN_;
_minXSTNLP = minXSTNLP_;
i._minPerSwap = a_.minPerSwap;
i._minPerAddr = a_.minPerAddr;
_percentOfTotalTokensForILO = i_.percentOfTokensForILO;
i._fundingToken = i_.fundingToken;
i._dexDeadlineLength = 1800;
// todo; in final production contract should be not less than 1209600 seconds or 14 days
i._contribTimeLock = a_.contribTimeLock;
i._liqPairLockLen = a_.liqPairLockLen;
// i._addressOfDex = addressOfDex_;
i._addressOfDex = addressOfDex_;
i._addressOfDexFactory = addressOfDexFactory_;
// if provided is less than default take default
// todo require a minimum fund per address possible 1000 gwei or 1000000000000 wei
i._minPerAddr = a_.minPerAddr;
// 0 means not max set
i._maxPerAddr = a_.maxPerAddr;
i._softcap = a_.softcap;
i._hardcap = a_.hardcap;
i._percentTokensForTeam = a_.percentTokensForTeam > 20 ? 20 : a_.percentTokensForTeam;
_totalTokensSupply = i_.totalSupply;
}
function getFullInfo() external view returns(Info memory) {
return i;
}
function fundingTokenForTeam() public view returns(uint) {
return _fundingTokenForTeam;
}
function addressOfDex() public view returns(address) {
return i._addressOfDex;
}
function addressOfDexFactory() public view returns(address) {
return i._addressOfDexFactory;
}
function amountRaised() public view returns(uint) {
return _fundingTokenTotal;
}
function fundingTokenAvail() public view returns(uint) {
return _fundingTokenAvail;
}
function availLPTokens() public view returns(uint) {
return _availLPTokens;
}
function softcap() public view returns(uint) {
return i._softcap;
}
function hardcap() public view returns(uint) {
return i._hardcap;
}
function minSpend() public view returns(uint) {
return i._minPerAddr;
}
function maxSpend() public view returns(uint) {
return i._maxPerAddr;
}
function liquidityPairAddress() public view returns(address) {
return _liquidityPairAddress;
}
function tokensForLiquidity() public view returns(uint) {
return _tokensForLiquidity;
}
function amountForProjTokenCalc() public view returns(uint) {
return _amountForProjTokenCalc;
}
function fundingTokenBalanceOfFunder(address funder_) public view returns(uint) {
return _funders[funder_].fundingTokenAmount;
}
function projectTokenBalanceOfFunder(address funder_) public view returns(uint) {
require(_ILOValidated, "project balance not available till ILO validated");
return _getProjTknBal(funder_);
}
function projectLPTokenBalanceOfFunder(address funder_) public view returns(uint) {
require(_availLPTokens > 0, "LP tokens not yet set");
return _getLiqTknBal(funder_);
}
//todo: swapRatio should be called after ILO, which would allow individuals to see how much tokens they're receiving per funding token
function swapRatio() public view returns(uint24, uint24) {
return (_swapRatio.fundTokenReceive, _swapRatio.projectTokenGive);
}
function adminBalance() public view returns(uint balance_) {
return _adminBalance;
}
function isWithdrawing(address addr_) public view returns(bool) {
return _currentlyWithdrawing[addr_ ];
}
function isSetup() public view returns (bool) {
return _isSetup;
}
function isTimeLockSet() public view returns (bool) {
return _projTimeLock != 0 && _contribTimeStampLock != 0 && _liqPairTimeLock != 0;
}
// return true if ILO is complete, Validated and ILO did not reach threshold ie _ILOSuccess == false
function ILOFailed() public view returns (bool) {
return isEventDone() && _ILOValidated && !_ILOSuccess;
}
function isContribTokenLocked() public view returns (bool) {
require(isTimeLockSet(), "Time locked not set");
return block.timestamp < _contribTimeStampLock || block.number < _contribBlockLock;
}
function isProjTokenLocked() public view returns (bool) {
require(isTimeLockSet(), "Time locked not set");
return block.timestamp < _projTimeLock || block.number < _projBlockLock;
}
function isLiqTokenLocked() public view returns (bool) {
require(isTimeLockSet(), "Time locked not set");
return block.timestamp < _liqPairTimeLock || block.number < _liqPairBlockLock;
}
function getTimeLocks() public view returns (uint, uint, uint, uint, uint, uint) {
return ( _contribTimeStampLock, _contribBlockLock, _projTimeLock, _projBlockLock, _liqPairTimeLock, _liqPairBlockLock);
}
function endTime() public view returns (uint48) {
return _endTime;
}
function startTime() public view returns (uint48) {
return _startTime;
}
function pubStartTime() public view returns(uint48) {
return _pubStartTime;
}
function availTokensILO() public view returns (uint) {
return _availTokensILO;
}
function totalTokensILO() public view returns (uint) {
return _totalTokensILO;
}
function percentOfTotalTokensForILO() public view returns (uint) {
return _percentOfTotalTokensForILO;
}
function tokensHeld() public view returns (uint) {
return _tokensHeld;
}
function totalTokensSupply() public view returns (uint) {
return _totalTokensSupply;
}
function projectToken() public view returns (address) {
return _projectToken;
}
function fundingToken() public view returns (address) {
return i._fundingToken;
}
// different
function isEventOpen() public view returns (bool isOpen_) {
uint48 currentTime = uint48(block.timestamp);
if(currentTime >= startTime() && currentTime < endTime() && amountRaised() < i._hardcap && _isSetup) {
isOpen_ = true;
}
}
//different
function isEventDone() public view returns (bool isOpen_) {
uint48 currentTime = uint48(block.timestamp);
if(_isSetup && ( currentTime >= endTime() )|| ( i._hardcap > 0 && amountRaised() == i._hardcap )) {
isOpen_ = true;
}
}
// Step 2
function setUpPoolPair(
address addressOfProjectToken,
string memory tokenName_,
string memory tokenSymbol_,
uint totalTokenSupply_,
uint48 startTime_,
uint48 endTime_
) public onlyAdmin returns(bool) {
require(admin() == msg.sender, "Administration: caller is not the admin");
require(!_isSetup,"initial setup already done");
require(startTime_ > block.timestamp && endTime_ > startTime_, "ILO dates not correct");
totalTokenSupply_ = totalTokenSupply_ * 10 ** _decimals;
require(_totalTokensSupply == totalTokenSupply_, "Total token supply not equal to provided information");
// if address of project token is 0 address deploy token for it
if(address(0) == addressOfProjectToken) {
address[] memory defaultOperators_;
_deployToken(_xStarterERCDeployer,tokenName_, tokenSymbol_, totalTokenSupply_, defaultOperators_);
}
else {
IERC20Custom existingToken = IERC20Custom(addressOfProjectToken);
// address existingTokenOwner = existingToken.owner();
uint existingTokenSupply = existingToken.totalSupply();
uint8 expDecimals = existingToken.decimals();
// require(existingTokenOwner == admin(),"Admin of pool pair must be owner of token contract");
require(existingTokenSupply == totalTokenSupply_, "All tokens from contract must be transferred");
require(expDecimals == _decimals, "decimals do not match");
_projectToken = addressOfProjectToken;
// _totalTokensSupply = _totalTokensSupply.add(totalTokenSupply_);
// _tokensHeld = _tokensHeld.add(totalTokenSupply_);
}
_startTime = startTime_;
_endTime = endTime_;
uint48 privLen = (endTime_ - startTime_) / 2;
_pubStartTime = _xStarterToken == address(0) ? startTime_ : startTime_ + privLen;
// this also sets ILO status to 1
_isSetup = iXstarterProposal(_proposalAddr).setILOTimes(_startTime, _endTime, _projectToken);
// if address of project token was zero address, then poolpair launches ERC20 for the project and keeps control of supply
_isSetup = address(0) == addressOfProjectToken ? iXstarterProposal(_proposalAddr).setStatus(2) : iXstarterProposal(_proposalAddr).setStatus(1);
require(_isSetup, 'not able register on proposal');
return _isSetup;
}
// function should be called within a function that checks proper access
function _deployToken(
address ercDeployer_,
string memory name_,
string memory symbol_,
uint totalTokenSupply_,
address[] memory defaultOperators_
) internal returns(bool){
//ProjectBaseToken newToken = new ProjectBaseToken(name_,symbol_, totalTokenSupply_, address(this), defaultOperators_);
_projectToken = IXStarterERCDeployer(ercDeployer_).deployToken(name_,symbol_, totalTokenSupply_, defaultOperators_);
// _projectToken = address(newToken);
// _totalTokensSupply = totalTokenSupply_;
_tokensHeld = _tokensHeld.add(totalTokenSupply_);
//_totalTokensILO = _tokensHeld.mul(_percentOfTotalTokensForILO.div(100));
_setTokensForILO();
emit TokenCreatedByXStarterPoolPair(_projectToken, address(this), _msgSender(), block.timestamp);
return true;
}
// step 3 if PoolPair has not been funded, if token was created by poolpair contract it is automatically funded, also sets ILO tokens
function depositAllTokenSupply() public onlyAdmin onlySetup returns(bool success) {
require(_tokensHeld != _totalTokensSupply, "already deposited");
// if(_tokensHeld == _totalTokensSupply) {
// return true;
// }
IERC20Custom existingToken = IERC20Custom(_projectToken);
uint allowance = existingToken.allowance(admin(), address(this));
require(allowance == _totalTokensSupply, "You must deposit all available tokens by calling the approve function on the token contract");
// transfer approved tokens from admin to current ILO contract
success = existingToken.transferFrom(_msgSender(), address(this), _totalTokensSupply);
require(success,'could not transfer project tokens to pool pair contract');
_tokensHeld = _tokensHeld.add(_totalTokensSupply);
_setTokensForILO();
iXstarterProposal(_proposalAddr).setStatus(2);
}
// function should be called within a function that checks proper access ie onlyAdmin or onlyOwner
function _setTokensForILO() internal {
// using the percent of tokens set in constructor by launchpad set total tokens for ILO
// formular: (_percentOfTotalTokensForILO/100 ) * _tokensHeld
//uint amount = _tokensHeld.mul(_percentOfTotalTokensForILO/100);
uint amount = _tokensHeld * _percentOfTotalTokensForILO/100;
_totalTokensILO = amount;
_availTokensILO = amount;
_adminBalance = _tokensHeld.sub(amount);
}
// functions for taking part in ILO
function contributeNativeToken() payable notCurrentlyFunding onlyOpen external returns(bool){
require(i._fundingToken == address(0), "please use contributeFundingToken");
require(msg.value > i._minPerSwap, "No value Sent");
_disallowFunding();
_contribute(msg.value, _msgSender());
_allowFunding();
return true;
}
// should be called after approving amount of token
function contributeFundingToken() notCurrentlyFunding onlyOpen external returns(bool) {
require(i._fundingToken != address(0), "please use nativeTokenSwap.");
_disallowFunding();
uint amount_ = _retrieveApprovedToken();
_contribute(amount_, _msgSender());
_allowFunding();
return true;
}
function _contribute(uint fundingTokenAmount_, address funder_) internal {
// check to see if currently in private sale time, for initial xStarter ILO this will == _startTime
//for subsequent it will be half of the ILO time, for example, if the ILO time was 1000 seconds, private sale would be the first 500 seconds,
// and the public sale would be the last 500 seconds
if(_pubStartTime > 0 && block.timestamp < _pubStartTime) {
require(IERC20Custom(_xStarterToken).balanceOf(funder_) >= _minXSTN || IERC20Custom(_xStarterLP).balanceOf(funder_) >= _minXSTNLP, "must hold xStarter tokens");
}
_fundingTokenTotal = _fundingTokenTotal.add(fundingTokenAmount_);
_fundingTokenAvail = _fundingTokenAvail.add(fundingTokenAmount_);
require(_fundingTokenTotal <= i._hardcap, "exceeds hard carp");
// add to msg.sender token funder balance
FunderInfo storage funder = _funders[funder_];
funder.fundingTokenAmount = funder.fundingTokenAmount.add(fundingTokenAmount_);
// funding can be less than Minimum if max - total < minimum
uint amountLeft = i._hardcap - _fundingTokenTotal;
// funding amount should be greater or equal to Minimum OR if not then available amount should be less than Minimum and fundingTokenAmount equals to amount left
require((funder.fundingTokenAmount >= i._minPerAddr) || (amountLeft < i._minPerAddr && fundingTokenAmount_ == amountLeft ) , "Minimum amount not met");
// if max is set then make sure not contributing max
require(funder.fundingTokenAmount <= i._maxPerAddr || i._maxPerAddr == 0, "maximum exceeded");
// sets amount raised on proposal
iXstarterProposal(_proposalAddr).setAmountRaised(_fundingTokenTotal);
}
function _retrieveApprovedToken() internal returns(uint allowedAmount_) {
address ownAddress = address(this);
IERC20Custom existingToken = IERC20Custom(i._fundingToken);
allowedAmount_ = existingToken.allowance(_msgSender(), ownAddress);
require(allowedAmount_ > i._minPerSwap, "Amount must be greater than 0");
bool success = existingToken.transferFrom(_msgSender(), ownAddress, allowedAmount_);
require(success, "not able to retrieve approved tokens of funding token");
return allowedAmount_;
}
function _allowFunding() internal {
_currentlyFunding[_msgSender()] = false;
}
function _disallowFunding() internal {
_currentlyFunding[_msgSender()] = true;
}
function _allowWithdraw() internal {
_currentlyWithdrawing[_msgSender()] = false;
}
function _disallowWithdraw() internal {
_currentlyWithdrawing[_msgSender()] = true;
}
event ILOValidated(address indexed caller_, uint indexed amountRaised_, bool success_, uint indexed swappedTokens_);
// step 4 validate after ILO
// validate checks to make sure mini amount of project tokens raised
// different
function validateILO() external returns(bool) {
require(isEventDone() && !_ILOValidated, "ILO not yet done OR already validated");
// uint minNeeded = uint(_totalTokensILO * _percentRequiredTokenPurchase / 100);
_ILOSuccess = amountRaised() >= i._softcap;
_ILOValidated = true;
emit ILOValidated(_msgSender(), amountRaised(), _ILOSuccess, _totalTokensILO);
if(_ILOSuccess) {
_tokensForLiquidity = uint(_totalTokensILO * _percentOfILOTokensForLiquidity / 100);
if(i._percentTokensForTeam > 0) {
_fundingTokenForTeam = uint((_fundingTokenAvail * i._percentTokensForTeam) / 100);
_fundingTokenAvail = _fundingTokenAvail.sub(_fundingTokenForTeam);
}
}
iXstarterProposal(_proposalAddr).setStatus(3);
return true;
}
// step 5
function approveTokensForLiquidityPair() external returns(bool) {
require(_ILOValidated && !ILOFailed(), "You must first validate ILO");
require(address(0) != i._addressOfDex, "dex zero addr");
require(!_approvedForLP, "approved tokens for liquidity already called");
uint amountProjectToken = _tokensForLiquidity;
if(address(0) == i._fundingToken) {
_approvedForLP = _callApproveOnProjectToken(i._addressOfDex, amountProjectToken);
} else {
uint amountERC20 = _fundingTokenAvail;
_approvedForLP = _callApproveOnProjectToken(i._addressOfDex, amountProjectToken) && _callApproveOnFundingToken(i._addressOfDex, amountERC20);
}
// approve project token to be sent to dex. Spender is dex IUniswapRouter address (honeyswap, uniswap etc)
require(_approvedForLP, "xStarterPair: TokenApprovalFail");
iXstarterProposal(_proposalAddr).setStatus(4);
return _approvedForLP;
}
event liquidityPairCreated(address indexed lpAddress_, address dexAddress_, uint lpTokenAmount_);
// step 6
function createLiquidityPool() external returns(bool success) {
// liquidity will be i._fundingTokenAvail to _tokensForLiquidity ratio
require(_ILOValidated && !ILOFailed(), "You must first validate ILO");
require(_approvedForLP, "xStarterPair: TokenApprovalFail");
require(!_liquidityPairCreated, "Liquidity pair already created");
_liquidityPairCreated = true;
uint liquidityAmount;
// save current amount to be used later to calculate each individual contributors share of project tokens
_amountForProjTokenCalc = _tokensForLiquidity;
if(address(0) == i._fundingToken) {
liquidityAmount = _createLiquidityPairETH();
} else {
liquidityAmount = _createLiquidityPairERC20();
}
_totalLPTokens = liquidityAmount;
_availLPTokens = liquidityAmount;
_liquidityPairAddress = _getLiquidityPairAddress();
emit liquidityPairCreated(_liquidityPairAddress, addressOfDex(), liquidityAmount);
iXstarterProposal(_proposalAddr).setTokenAndLPAddr(_projectToken, _liquidityPairAddress);
iXstarterProposal(_proposalAddr).setStatus(5);
return true;
}
event ILOFinalized(address caller_);
// step 7
function finalizeILO() external returns(bool success) {
require(_liquidityPairCreated, "liquidity pair must be created first");
// set liquidity pair address
success = _setTimeLocks();
emit ILOFinalized(_msgSender());
iXstarterProposal(_proposalAddr).setStatus(6);
}
event WithdrawnProjectToken(address indexed funder_, uint indexed amount_);
function withdraw() external allowedToWithdraw returns(bool success) {
_disallowWithdraw();
require(!isContribTokenLocked(), "withdrawal locked");
require(!_projTokensWithdrawn[_msgSender()], "project tokens already withdrawn");
uint amount_ = projectTokenBalanceOfFunder(_msgSender());
_projTokensWithdrawn[_msgSender()] = true;
// FunderInfo storage funder = _funders[_msgSender()];
// require(funder.fundingTokenAmount > 0, "Did Not Contribute");
require(amount_ > 0, 'amount must be greater than 0');
//funder.projectTokenAmount = funder.projectTokenAmount.sub(amount_);
// success = IERC20Custom(_projectToken).approve(_msgSender(), amount_);
success = IERC20Custom(_projectToken).transfer(_msgSender(), amount_);
_tokensHeld = _tokensHeld.sub(amount_);
_allowWithdraw();
emit WithdrawnProjectToken(_msgSender(), amount_);
}
// todo: verify the balance is right
function _getProjTknBal(address funder_) internal view returns(uint balance) {
if(_projTokensWithdrawn[funder_] == true) {
return 0;
}
uint tokensForContributors = _totalTokensILO - _amountForProjTokenCalc;
balance = _getProportionAmt(tokensForContributors, _fundingTokenTotal, _funders[funder_].fundingTokenAmount);
// avoid solidity rounding fractions to 0
// if(tokensForContributors > i._fundingTokenTotal) {
// amtPer = tokensForContributors / i._fundingTokenTotal;
// balance = _funders[funder_].fundingTokenAmount * amtPer;
// }else {
// amtPer = i._fundingTokenTotal / tokensForContributors;
// balance = _funders[funder_].fundingTokenAmount / amtPer;
// }
// uint amtPer = i._fundingTokenTotal.div(10 ** 18);
// lpPer * fundingTokenAmount to get lp tokens to send
}
function _getLiqTknBal(address funder_) internal view returns(uint balance) {
if(_liqTokensWithdrawn[funder_] == true) {
return 0;
}
balance = _getProportionAmt(_totalLPTokens, _fundingTokenTotal, _funders[funder_].fundingTokenAmount);
// uint amtPer;
// // avoid solidity rounding fractions to 0
// if(_totalLPTokens > i._fundingTokenTotal) {
// amtPer = _totalLPTokens / i._fundingTokenTotal;
// balance = _funders[funder_].fundingTokenAmount * amtPer;
// }else {
// amtPer = i._fundingTokenTotal / _totalLPTokens;
// balance = _funders[funder_].fundingTokenAmount / amtPer;
// }
}
function _getProportionAmt(uint totalRewardTokens, uint totalFundingTokens, uint funderFundingAmount) internal pure returns (uint proportionalRewardTokens) {
// assumes each both tokens a decimals = 18, while precision is lost, reducing this blunts the loss of precision
uint reducedTotalFundingTokens = totalFundingTokens / (10 ** 12);
uint reducedFunderFundingAmount = funderFundingAmount / (10 ** 12);
uint amtPer = totalRewardTokens / reducedTotalFundingTokens;
proportionalRewardTokens = amtPer * reducedFunderFundingAmount;
}
event FundingTokenForTeamWithdrawn(address indexed admin_, uint indexed amount_, uint indexed percentTokensForTeam_, uint totalFundingTokens_ );
function withdrawFundingToken() external onlyAdmin returns(bool success) {
require(_fundingTokenForTeam > 0, 'no balance');
uint amount_ = _fundingTokenForTeam;
_fundingTokenForTeam = 0;
if(i._fundingToken == address(0)) {
// send native token to funder
(success, ) = _msgSender().call{value: amount_}('');
}else {
// or if funding token wasn't native, send ERC20 token
success = IERC20Custom(i._fundingToken).transfer(_msgSender(), amount_);
}
emit FundingTokenForTeamWithdrawn(_msgSender(), amount_, i._percentTokensForTeam, _fundingTokenTotal);
}
event WithdrawnOnFailure(address indexed funder_, address indexed TokenAddr_, uint indexed amount_, bool isAdmin);
function withdrawOnFailure() external allowedToWithdraw returns(bool success) {
require(ILOFailed(), "ILO not failed");
_disallowWithdraw();
if(_msgSender() == _admin) {
// if admin withdraw all project tokens
require(_adminBalance != 0, "already withdrawn");
_adminBalance = 0;
uint amount_ = _tokensHeld;
_tokensHeld = 0;
success = IERC20Custom(_projectToken).transfer(_msgSender(), amount_);
emit WithdrawnOnFailure(_msgSender(), _projectToken, amount_, true);
}else{
// if not admin send back funding token (nativ token like eth or ERC20 token)
FunderInfo storage funder = _funders[_msgSender()];
uint amount_ = funder.fundingTokenAmount;
require(amount_ > 0, "no balance");
// uint amount2_ = funder.projectTokenAmount;
funder.fundingTokenAmount = 0;
funder.projectTokenAmount = 0;
_fundingTokenAvail = _fundingTokenAvail.sub(amount_);
if(i._fundingToken == address(0)) {
// send native token to funder
(success, ) = _msgSender().call{value: amount_}('');
emit WithdrawnOnFailure(_msgSender(), address(0), amount_, false);
}else {
// or if funding token wasn't native, send ERC20 token
success = IERC20Custom(i._fundingToken).transfer(_msgSender(), amount_);
emit WithdrawnOnFailure(_msgSender(), i._fundingToken, amount_, false);
}
}
_allowWithdraw();
}
event WithdrawnLiquidityToken(address funder_, uint amount_);
// withraws all the liquidity token of the user
function withdrawLiquidityTokens() external allowedToWithdraw returns(bool success) {
require(!isLiqTokenLocked(), "withdrawal locked ");
_disallowWithdraw();
require(!_liqTokensWithdrawn[_msgSender()], "No tokens");
uint LPAmount_ = _getLiqTknBal(_msgSender());
_liqTokensWithdrawn[_msgSender()] = true;
require(LPAmount_ > 0 && LPAmount_ <= _availLPTokens, "not enough lp tokens");
_availLPTokens = _availLPTokens.sub(LPAmount_);
success = IERC20Uni(_liquidityPairAddress).transfer(_msgSender(), LPAmount_);
_allowWithdraw();
emit WithdrawnLiquidityToken(_msgSender(), LPAmount_);
}
function withdrawAdmin() external onlyAdmin returns (bool success) {
require(!isProjTokenLocked(), "withdrawal locked");
_disallowWithdraw();
// admin
uint amount_ = _adminBalance;
_adminBalance = 0;
_tokensHeld = _tokensHeld.sub(amount_);
success = IERC20Custom(_projectToken).transfer(_admin, amount_);
_allowWithdraw();
}
function _getLiquidityPairAddress() internal view returns(address liquidPair_) {
if(address(0) == i._fundingToken) {
address WETH_ = IUniswapRouter(i._addressOfDex).WETH();
liquidPair_ = IUniswapFactory(i._addressOfDexFactory).getPair(WETH_, _projectToken);
require(address(0) != liquidPair_, "Liquidity Pair Should Be Created But Hasn't");
} else {
liquidPair_ = IUniswapFactory(i._addressOfDexFactory).getPair(i._fundingToken, _projectToken);
require(address(0) != liquidPair_, "Liquidity Pair Should Be Created But Not Created");
}
}
event TimeLockSet(uint indexed projTokenLock_, uint indexed contribTokenLock_, uint indexed liquidityTokenLock_);
function _setTimeLocks() internal returns(bool) {
require(!isTimeLockSet(), "Time lock already set");
uint timeLockLengthX2 = i._contribTimeLock * 2;
// if timelock greater than 60 days in seconds, set to length of contributor timelock + 30 days
uint timeLen = timeLockLengthX2 > 5184000 ? i._contribTimeLock + 2592000 : timeLockLengthX2;
_projTimeLock = block.timestamp + timeLen;
_projBlockLock = block.number + uint(timeLen / MINE_LEN);
_contribTimeStampLock = block.timestamp + i._contribTimeLock;
_contribBlockLock = block.number + uint(i._contribTimeLock / MINE_LEN);
_liqPairTimeLock = block.timestamp + i._liqPairLockLen;
_liqPairBlockLock = block.number + uint(i._liqPairLockLen / MINE_LEN);
emit TimeLockSet(_projBlockLock, _contribBlockLock, _liqPairBlockLock);
return true;
}
// this can be called by anyone. but should be called AFTER the ILO
// on xDai chain ETH would be xDai, on BSC it would be BNB
// step 6a
function _createLiquidityPairETH() internal returns(uint liquidityTokens_) {
//require(address(0) == i._fundingToken, "xStarterPair: FundingTokenError");
uint amountETH = _fundingTokenAvail;
uint amountProjectToken = _tokensForLiquidity;
// approve project token to be sent to dex. Spender is dex IUniswapRouter address (honeyswap, uniswap etc)
//bool approved_ = _callApproveOnProjectToken(i._addressOfDex, amountProjectToken);
(uint amountTokenInPool, uint amountETHInPool, uint amountliquidityToken) = IUniswapRouter(i._addressOfDex).addLiquidityETH{value: amountETH}(
_projectToken,
amountProjectToken,
amountProjectToken,
amountETH,
address(this),
block.timestamp + i._dexDeadlineLength
);
liquidityTokens_ = amountliquidityToken;
_fundingTokenAvail = 0;
// subtract amount sent to liquidity pool from this
_tokensHeld = _tokensHeld.sub(amountProjectToken);
_tokensForLiquidity = 0;
}
// step 6b
function _createLiquidityPairERC20() internal returns(uint liquidityTokens_) {
require(address(0) != i._fundingToken, "xStarterPair: FundingTokenError");
//require(_approvedForLP, "xStarterPair: TokenApprovalFail, call syncBalances before calling again");
uint amountERC20 = _fundingTokenAvail;
uint amountProjectToken = _tokensForLiquidity;
// approve project token to be sent to dex. Spender is dex IUniswapRouter address (honeyswap, uniswap etc)
// bool approvedA_ = _callApproveOnProjectToken(i._addressOfDex, amountProjectToken);
// bool approvedB_ = _callApproveOnFundingToken(i._addressOfDex, amountERC20);
//require(approvedA_ && approvedB_, "xStarterPair: TokenApprovalFail, call syncBalances before calling again");
(uint amountTokenInPool, uint amountETHInPool, uint amountliquidityToken) = IUniswapRouter(i._addressOfDex).addLiquidity(
_projectToken,
i._fundingToken,
amountProjectToken,
amountERC20,
amountProjectToken,
amountERC20,
address(this),
block.timestamp + i._dexDeadlineLength
);
_fundingTokenAvail = 0;
// subtract amount sent to liquidity pool from this
_tokensHeld = _tokensHeld.sub(amountProjectToken);
_tokensForLiquidity = 0;
liquidityTokens_ = amountliquidityToken;
}
function _callApproveOnProjectToken(address spender_, uint amount_) internal returns(bool success) {
success = IERC20(_projectToken).approve(spender_, amount_);
}
function _callApproveOnFundingToken(address spender_, uint amount_) internal returns(bool success) {
success = IERC20(i._fundingToken).approve(spender_, amount_);
}
// IERC777Recipient implementation
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external view override{
// this contract should receive token using approve on ERC20/ and then fundingTokenSwap function on this contract
require(from == address(this), "approve then call fundingTokenSwap");
}
// IERC777Sender implementation called before tokenis
function tokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external view override {
require(from == address(this), "approve then call fundingTokenSwap");
}
} | funding amount should be greater or equal to Minimum OR if not then available amount should be less than Minimum and fundingTokenAmount equals to amount left | require((funder.fundingTokenAmount >= i._minPerAddr) || (amountLeft < i._minPerAddr && fundingTokenAmount_ == amountLeft ) , "Minimum amount not met");
| 15,816,766 | [
1,
74,
14351,
3844,
1410,
506,
6802,
578,
3959,
358,
23456,
4869,
309,
486,
1508,
2319,
3844,
1410,
506,
5242,
2353,
23456,
471,
22058,
1345,
6275,
1606,
358,
3844,
2002,
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,
3639,
2583,
12443,
74,
9341,
18,
74,
14351,
1345,
6275,
1545,
277,
6315,
1154,
2173,
3178,
13,
747,
261,
8949,
3910,
411,
277,
6315,
1154,
2173,
3178,
597,
22058,
1345,
6275,
67,
422,
3844,
3910,
262,
269,
315,
13042,
3844,
486,
5100,
8863,
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
]
|
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.0;
import "../interfaces/IBentoBoxMinimal.sol";
import "../interfaces/IMasterDeployer.sol";
import "../interfaces/IPool.sol";
import "../interfaces/ITridentCallee.sol";
import "./TridentERC20.sol";
/// @notice Trident exchange pool template with constant mean formula for swapping among an array of ERC-20 tokens.
/// @dev The reserves are stored as bento shares.
/// The curve is applied to shares as well. This pool does not care about the underlying amounts.
contract IndexPool is IPool, TridentERC20 {
event Mint(address indexed sender, address tokenIn, uint256 amountIn, address indexed recipient);
event Burn(address indexed sender, address tokenOut, uint256 amountOut, address indexed recipient);
uint256 public immutable swapFee;
address public immutable barFeeTo;
IBentoBoxMinimal public immutable bento;
IMasterDeployer public immutable masterDeployer;
uint256 internal constant BASE = 10**18;
uint256 internal constant MIN_TOKENS = 2;
uint256 internal constant MAX_TOKENS = 8;
uint256 internal constant MIN_FEE = BASE / 10**6;
uint256 internal constant MAX_FEE = BASE / 10;
uint256 internal constant MIN_WEIGHT = BASE;
uint256 internal constant MAX_WEIGHT = BASE * 50;
uint256 internal constant MAX_TOTAL_WEIGHT = BASE * 50;
uint256 internal constant MIN_BALANCE = BASE / 10**12;
uint256 internal constant INIT_POOL_SUPPLY = BASE * 100;
uint256 internal constant MIN_POW_BASE = 1;
uint256 internal constant MAX_POW_BASE = (2 * BASE) - 1;
uint256 internal constant POW_PRECISION = BASE / 10**10;
uint256 internal constant MAX_IN_RATIO = BASE / 2;
uint256 internal constant MAX_OUT_RATIO = (BASE / 3) + 1;
uint136 internal totalWeight;
address[] internal tokens;
uint256 public barFee;
bytes32 public constant override poolIdentifier = "Trident:Index";
uint256 internal unlocked;
modifier lock() {
require(unlocked == 1, "LOCKED");
unlocked = 2;
_;
unlocked = 1;
}
mapping(address => Record) public records;
struct Record {
uint120 reserve;
uint136 weight;
}
constructor(bytes memory _deployData, address _masterDeployer) {
(address[] memory _tokens, uint136[] memory _weights, uint256 _swapFee) = abi.decode(_deployData, (address[], uint136[], uint256));
// @dev Factory ensures that the tokens are sorted.
require(_tokens.length == _weights.length, "INVALID_ARRAYS");
require(MIN_FEE <= _swapFee && _swapFee <= MAX_FEE, "INVALID_SWAP_FEE");
require(MIN_TOKENS <= _tokens.length && _tokens.length <= MAX_TOKENS, "INVALID_TOKENS_LENGTH");
for (uint256 i = 0; i < _tokens.length; i++) {
require(_tokens[i] != address(0), "ZERO_ADDRESS");
require(MIN_WEIGHT <= _weights[i] && _weights[i] <= MAX_WEIGHT, "INVALID_WEIGHT");
records[_tokens[i]] = Record({reserve: 0, weight: _weights[i]});
tokens.push(_tokens[i]);
totalWeight += _weights[i];
}
require(totalWeight <= MAX_TOTAL_WEIGHT, "MAX_TOTAL_WEIGHT");
// @dev This burns initial LP supply.
_mint(address(0), INIT_POOL_SUPPLY);
swapFee = _swapFee;
barFee = IMasterDeployer(_masterDeployer).barFee();
barFeeTo = IMasterDeployer(_masterDeployer).barFeeTo();
bento = IBentoBoxMinimal(IMasterDeployer(_masterDeployer).bento());
masterDeployer = IMasterDeployer(_masterDeployer);
unlocked = 1;
}
/// @dev Mints LP tokens - should be called via the router after transferring `bento` tokens.
/// The router must ensure that sufficient LP tokens are minted by using the return value.
function mint(bytes calldata data) public override lock returns (uint256 liquidity) {
(address recipient, uint256 toMint) = abi.decode(data, (address, uint256));
uint120 ratio = uint120(_div(toMint, totalSupply));
for (uint256 i = 0; i < tokens.length; i++) {
address tokenIn = tokens[i];
uint120 reserve = records[tokenIn].reserve;
// @dev If token balance is '0', initialize with `ratio`.
uint120 amountIn = reserve != 0 ? uint120(_mul(ratio, reserve)) : ratio;
require(amountIn >= MIN_BALANCE, "MIN_BALANCE");
// @dev Check Trident router has sent `amountIn` for skim into pool.
unchecked {
// @dev This is safe from overflow - only logged amounts handled.
require(_balance(tokenIn) >= amountIn + reserve, "NOT_RECEIVED");
records[tokenIn].reserve += amountIn;
}
emit Mint(msg.sender, tokenIn, amountIn, recipient);
}
_mint(recipient, toMint);
liquidity = toMint;
}
/// @dev Burns LP tokens sent to this contract. The router must ensure that the user gets sufficient output tokens.
function burn(bytes calldata data) public override lock returns (IPool.TokenAmount[] memory withdrawnAmounts) {
(address recipient, bool unwrapBento, uint256 toBurn) = abi.decode(data, (address, bool, uint256));
uint256 ratio = _div(toBurn, totalSupply);
withdrawnAmounts = new TokenAmount[](tokens.length);
_burn(address(this), toBurn);
for (uint256 i = 0; i < tokens.length; i++) {
address tokenOut = tokens[i];
uint256 balance = records[tokenOut].reserve;
uint120 amountOut = uint120(_mul(ratio, balance));
require(amountOut != 0, "ZERO_OUT");
// @dev This is safe from underflow - only logged amounts handled.
unchecked {
records[tokenOut].reserve -= amountOut;
}
_transfer(tokenOut, amountOut, recipient, unwrapBento);
withdrawnAmounts[i] = TokenAmount({token: tokenOut, amount: amountOut});
emit Burn(msg.sender, tokenOut, amountOut, recipient);
}
}
/// @dev Burns LP tokens sent to this contract and swaps one of the output tokens for another
/// - i.e., the user gets a single token out by burning LP tokens.
function burnSingle(bytes calldata data) public override lock returns (uint256 amountOut) {
(address tokenOut, address recipient, bool unwrapBento, uint256 toBurn) = abi.decode(data, (address, address, bool, uint256));
Record storage outRecord = records[tokenOut];
amountOut = _computeSingleOutGivenPoolIn(outRecord.reserve, outRecord.weight, totalSupply, totalWeight, toBurn, swapFee);
require(amountOut <= _mul(outRecord.reserve, MAX_OUT_RATIO), "MAX_OUT_RATIO");
// @dev This is safe from underflow - only logged amounts handled.
unchecked {
outRecord.reserve -= uint120(amountOut);
}
_burn(address(this), toBurn);
_transfer(tokenOut, amountOut, recipient, unwrapBento);
emit Burn(msg.sender, tokenOut, amountOut, recipient);
}
/// @dev Swaps one token for another. The router must prefund this contract and ensure there isn't too much slippage.
function swap(bytes calldata data) public override lock returns (uint256 amountOut) {
(address tokenIn, address tokenOut, address recipient, bool unwrapBento, uint256 amountIn) = abi.decode(
data,
(address, address, address, bool, uint256)
);
Record storage inRecord = records[tokenIn];
Record storage outRecord = records[tokenOut];
require(amountIn <= _mul(inRecord.reserve, MAX_IN_RATIO), "MAX_IN_RATIO");
amountOut = _getAmountOut(amountIn, inRecord.reserve, inRecord.weight, outRecord.reserve, outRecord.weight);
// @dev Check Trident router has sent `amountIn` for skim into pool.
unchecked {
// @dev This is safe from under/overflow - only logged amounts handled.
require(_balance(tokenIn) >= amountIn + inRecord.reserve, "NOT_RECEIVED");
inRecord.reserve += uint120(amountIn);
outRecord.reserve -= uint120(amountOut);
}
_transfer(tokenOut, amountOut, recipient, unwrapBento);
emit Swap(recipient, tokenIn, tokenOut, amountIn, amountOut);
}
/// @dev Swaps one token for another. The router must support swap callbacks and ensure there isn't too much slippage.
function flashSwap(bytes calldata data) public override lock returns (uint256 amountOut) {
(address tokenIn, address tokenOut, address recipient, bool unwrapBento, uint256 amountIn, bytes memory context) = abi.decode(
data,
(address, address, address, bool, uint256, bytes)
);
Record storage inRecord = records[tokenIn];
Record storage outRecord = records[tokenOut];
require(amountIn <= _mul(inRecord.reserve, MAX_IN_RATIO), "MAX_IN_RATIO");
amountOut = _getAmountOut(amountIn, inRecord.reserve, inRecord.weight, outRecord.reserve, outRecord.weight);
ITridentCallee(msg.sender).tridentSwapCallback(context);
// @dev Check Trident router has sent `amountIn` for skim into pool.
unchecked {
// @dev This is safe from under/overflow - only logged amounts handled.
require(_balance(tokenIn) >= amountIn + inRecord.reserve, "NOT_RECEIVED");
inRecord.reserve += uint120(amountIn);
outRecord.reserve -= uint120(amountOut);
}
_transfer(tokenOut, amountOut, recipient, unwrapBento);
emit Swap(recipient, tokenIn, tokenOut, amountIn, amountOut);
}
/// @dev Updates `barFee` for Trident protocol.
function updateBarFee() public {
barFee = IMasterDeployer(masterDeployer).barFee();
}
function _balance(address token) internal view returns (uint256 balance) {
balance = bento.balanceOf(token, address(this));
}
function _getAmountOut(
uint256 tokenInAmount,
uint256 tokenInBalance,
uint256 tokenInWeight,
uint256 tokenOutBalance,
uint256 tokenOutWeight
) internal view returns (uint256 amountOut) {
uint256 weightRatio = _div(tokenInWeight, tokenOutWeight);
// @dev This is safe from under/overflow - only logged amounts handled.
unchecked {
uint256 adjustedIn = _mul(tokenInAmount, (BASE - swapFee));
uint256 a = _div(tokenInBalance, tokenInBalance + adjustedIn);
uint256 b = _compute(a, weightRatio);
uint256 c = BASE - b;
amountOut = _mul(tokenOutBalance, c);
}
}
function _compute(uint256 base, uint256 exp) internal pure returns (uint256 output) {
require(MIN_POW_BASE <= base && base <= MAX_POW_BASE, "INVALID_BASE");
uint256 whole = (exp / BASE) * BASE;
uint256 remain = exp - whole;
uint256 wholePow = _pow(base, whole / BASE);
if (remain == 0) output = wholePow;
uint256 partialResult = _powApprox(base, remain, POW_PRECISION);
output = _mul(wholePow, partialResult);
}
function _computeSingleOutGivenPoolIn(
uint256 tokenOutBalance,
uint256 tokenOutWeight,
uint256 _totalSupply,
uint256 _totalWeight,
uint256 toBurn,
uint256 _swapFee
) internal pure returns (uint256 amountOut) {
uint256 normalizedWeight = _div(tokenOutWeight, _totalWeight);
uint256 newPoolSupply = _totalSupply - toBurn;
uint256 poolRatio = _div(newPoolSupply, _totalSupply);
uint256 tokenOutRatio = _pow(poolRatio, _div(BASE, normalizedWeight));
uint256 newBalanceOut = _mul(tokenOutRatio, tokenOutBalance);
uint256 tokenAmountOutBeforeSwapFee = tokenOutBalance - newBalanceOut;
uint256 zaz = (BASE - normalizedWeight) * _swapFee;
amountOut = _mul(tokenAmountOutBeforeSwapFee, (BASE - zaz));
}
function _pow(uint256 a, uint256 n) internal pure returns (uint256 output) {
output = n % 2 != 0 ? a : BASE;
for (n /= 2; n != 0; n /= 2) a = a * a;
if (n % 2 != 0) output = output * a;
}
function _powApprox(
uint256 base,
uint256 exp,
uint256 precision
) internal pure returns (uint256 sum) {
uint256 a = exp;
(uint256 x, bool xneg) = _subFlag(base, BASE);
uint256 term = BASE;
sum = term;
bool negative;
for (uint256 i = 1; term >= precision; i++) {
uint256 bigK = i * BASE;
(uint256 c, bool cneg) = _subFlag(a, (bigK - BASE));
term = _mul(term, _mul(c, x));
term = _div(term, bigK);
if (term == 0) break;
if (xneg) negative = !negative;
if (cneg) negative = !negative;
if (negative) {
sum = sum - term;
} else {
sum = sum + term;
}
}
}
function _subFlag(uint256 a, uint256 b) internal pure returns (uint256 difference, bool flag) {
// @dev This is safe from underflow - if/else flow performs checks.
unchecked {
if (a >= b) {
(difference, flag) = (a - b, false);
} else {
(difference, flag) = (b - a, true);
}
}
}
function _mul(uint256 a, uint256 b) internal pure returns (uint256 c2) {
uint256 c0 = a * b;
uint256 c1 = c0 + (BASE / 2);
c2 = c1 / BASE;
}
function _div(uint256 a, uint256 b) internal pure returns (uint256 c2) {
uint256 c0 = a * BASE;
uint256 c1 = c0 + (b / 2);
c2 = c1 / b;
}
function _transfer(
address token,
uint256 shares,
address to,
bool unwrapBento
) internal {
if (unwrapBento) {
bento.withdraw(token, address(this), to, 0, shares);
} else {
bento.transfer(token, address(this), to, shares);
}
}
function getAssets() public view override returns (address[] memory assets) {
assets = tokens;
}
function getAmountOut(bytes calldata data) public view override returns (uint256 amountOut) {
(uint256 tokenInAmount, uint256 tokenInBalance, uint256 tokenInWeight, uint256 tokenOutBalance, uint256 tokenOutWeight) = abi
.decode(data, (uint256, uint256, uint256, uint256, uint256));
amountOut = _getAmountOut(tokenInAmount, tokenInBalance, tokenInWeight, tokenOutBalance, tokenOutWeight);
}
function getAmountIn(bytes calldata) public pure override returns (uint256) {
revert();
}
function getReservesAndWeights() public view returns (uint256[] memory reserves, uint136[] memory weights) {
uint256 length = tokens.length;
reserves = new uint256[](length);
weights = new uint136[](length);
// @dev This is safe from overflow - `tokens` `length` is bound to '8'.
unchecked {
for (uint256 i = 0; i < length; i++) {
reserves[i] = records[tokens[i]].reserve;
weights[i] = records[tokens[i]].weight;
}
}
}
}
| @dev Burns LP tokens sent to this contract. The router must ensure that the user gets sufficient output tokens. @dev This is safe from underflow - only logged amounts handled. | function burn(bytes calldata data) public override lock returns (IPool.TokenAmount[] memory withdrawnAmounts) {
(address recipient, bool unwrapBento, uint256 toBurn) = abi.decode(data, (address, bool, uint256));
uint256 ratio = _div(toBurn, totalSupply);
withdrawnAmounts = new TokenAmount[](tokens.length);
_burn(address(this), toBurn);
for (uint256 i = 0; i < tokens.length; i++) {
address tokenOut = tokens[i];
uint256 balance = records[tokenOut].reserve;
uint120 amountOut = uint120(_mul(ratio, balance));
require(amountOut != 0, "ZERO_OUT");
unchecked {
records[tokenOut].reserve -= amountOut;
}
_transfer(tokenOut, amountOut, recipient, unwrapBento);
emit Burn(msg.sender, tokenOut, amountOut, recipient);
}
}
| 901,594 | [
1,
38,
321,
87,
511,
52,
2430,
3271,
358,
333,
6835,
18,
1021,
4633,
1297,
3387,
716,
326,
729,
5571,
18662,
876,
2430,
18,
225,
1220,
353,
4183,
628,
3613,
2426,
300,
1338,
7545,
30980,
7681,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
18305,
12,
3890,
745,
892,
501,
13,
1071,
3849,
2176,
1135,
261,
2579,
1371,
18,
1345,
6275,
8526,
3778,
598,
9446,
82,
6275,
87,
13,
288,
203,
3639,
261,
2867,
8027,
16,
1426,
11014,
38,
29565,
16,
2254,
5034,
358,
38,
321,
13,
273,
24126,
18,
3922,
12,
892,
16,
261,
2867,
16,
1426,
16,
2254,
5034,
10019,
203,
203,
3639,
2254,
5034,
7169,
273,
389,
2892,
12,
869,
38,
321,
16,
2078,
3088,
1283,
1769,
203,
203,
3639,
598,
9446,
82,
6275,
87,
273,
394,
3155,
6275,
8526,
12,
7860,
18,
2469,
1769,
203,
203,
3639,
389,
70,
321,
12,
2867,
12,
2211,
3631,
358,
38,
321,
1769,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
2430,
18,
2469,
31,
277,
27245,
288,
203,
5411,
1758,
1147,
1182,
273,
2430,
63,
77,
15533,
203,
5411,
2254,
5034,
11013,
273,
3853,
63,
2316,
1182,
8009,
455,
6527,
31,
203,
5411,
2254,
22343,
3844,
1182,
273,
2254,
22343,
24899,
16411,
12,
9847,
16,
11013,
10019,
203,
5411,
2583,
12,
8949,
1182,
480,
374,
16,
315,
24968,
67,
5069,
8863,
203,
5411,
22893,
288,
203,
7734,
3853,
63,
2316,
1182,
8009,
455,
6527,
3947,
3844,
1182,
31,
203,
5411,
289,
203,
5411,
389,
13866,
12,
2316,
1182,
16,
3844,
1182,
16,
8027,
16,
11014,
38,
29565,
1769,
203,
5411,
3626,
605,
321,
12,
3576,
18,
15330,
16,
1147,
1182,
16,
3844,
1182,
16,
8027,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
/**
* @title Sahara Vesting Smart Contract
* @author SAHARA
* @notice Vesting initializable contract for beneficiary management and unlocked token claiming.
*/
contract VestingMock is Initializable, OwnableUpgradeable {
// TIME MANIPULATION FOR TESTING {
uint256 blockTimestamp = 0;
function setMockTimestamp(uint256 _newTimestmap) public onlyOwner {
blockTimestamp = _newTimestmap;
}
function addMockDaysTimestamp(uint256 _days) public onlyOwner {
blockTimestamp += _days * 1 days;
}
function addMockMonthsTimestamp(uint256 _months) public onlyOwner {
blockTimestamp += _months * 30 days;
}
// TIME MANIPULATION FOR TESTING }
// GETTERS FOR TESTING {
function getToken_TEST() public view returns (IERC20Upgradeable) {
return token;
}
/*function getContractOwner_TEST() public view returns (address) {
return contractOwner;
}*/
function getPoolCount_TEST() public view returns (uint256) {
return poolCount;
}
function getListingDate_TEST() public view returns (uint256) {
return listingDate;
}
function getVestingPoolDataPart1_TEST(uint256 index)
public
view
returns (string memory, uint256, uint256, uint256, uint256, uint256, uint256/*, uint256, uint256, uint256, UnlockTypes, uint256, uint256*/)
{
return (vestingPools[index].name,
vestingPools[index].listingPercentageDividend,
vestingPools[index].listingPercentageDivisor,
vestingPools[index].cliffInDays,
vestingPools[index].cliffEndDate,
vestingPools[index].cliffPercentageDividend,
vestingPools[index].cliffPercentageDivisor/*,
vestingPools[index].vestingDurationInMonths,
vestingPools[index].vestingDurationInDays,
vestingPools[index].vestingEndDate,
vestingPools[index].unlockType,
vestingPools[index].totalPoolTokenAmount,
vestingPools[index].lockedPoolTokens*/
);
}
function getVestingPoolDataPart2_TEST(uint256 index)
public
view
returns (/*string memory, uint256, uint256, uint256, uint256, uint256, uint256, */uint256, uint256, uint256, UnlockTypes, uint256, uint256)
{
return (/*vestingPools[index].name,
vestingPools[index].listingPercentageDividend,
vestingPools[index].listingPercentageDivisor,
vestingPools[index].cliffInDays,
vestingPools[index].cliffEndDate,
vestingPools[index].cliffPercentageDividend,
vestingPools[index].cliffPercentageDivisor,*/
vestingPools[index].vestingDurationInMonths,
vestingPools[index].vestingDurationInDays,
vestingPools[index].vestingEndDate,
vestingPools[index].unlockType,
vestingPools[index].totalPoolTokenAmount,
vestingPools[index].lockedPoolTokens
);
}
function getVestingPoolBeneficiary_TEST(
uint256 index,
address _address
)
public
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
return (
vestingPools[index].beneficiaries[_address].totalTokens,
vestingPools[index].beneficiaries[_address].listingTokenAmount,
vestingPools[index].beneficiaries[_address].cliffTokenAmount,
vestingPools[index].beneficiaries[_address].vestedTokenAmount,
vestingPools[index].beneficiaries[_address].claimedTotalTokenAmount
);
}
// GETTERS FOR TESTING }
using SafeERC20Upgradeable for IERC20Upgradeable;
IERC20Upgradeable private token;
uint private poolCount;
uint private listingDate;
event Claim(address indexed from, uint indexed poolIndex, uint tokenAmount);
event VestingPoolAdded(uint indexed poolIndex, uint totalPoolTokenAmount);
event BeneficiaryAdded(uint indexed poolIndex, address indexed beneficiary, uint addedTokenAmount);
event BeneficiaryRemoved(uint indexed poolIndex, address indexed beneficiary, uint unlockedPoolAmount);
event ListingDateChanged(uint oldDate, uint newDate);
enum UnlockTypes{
DAILY,
MONTHLY
}
struct Beneficiary {
uint totalTokens;
uint listingTokenAmount;
uint cliffTokenAmount;
uint vestedTokenAmount;
uint claimedTotalTokenAmount;
}
struct Pool {
string name;
uint listingPercentageDividend;
uint listingPercentageDivisor;
uint cliffInDays;
uint cliffEndDate;
uint cliffPercentageDividend;
uint cliffPercentageDivisor;
uint vestingDurationInMonths;
uint vestingDurationInDays;
uint vestingEndDate;
mapping(address => Beneficiary) beneficiaries;
UnlockTypes unlockType;
uint totalPoolTokenAmount;
uint lockedPoolTokens;
}
mapping(uint => Pool) private vestingPools;
function initialize(IERC20Upgradeable _token, uint _listingDate)
public
initializer
validListingDate(_listingDate)
{
__Ownable_init();
token = _token;
poolCount = 0;
listingDate = _listingDate;
/* name, listing percentage, cliff period, cliff percentage, vesting months, unlock type, total token amount */
/*addVestingPool('Angel Round', 0, 1, 90, 1, 20, 36, UnlockTypes.DAILY, 13000000 * 10 ** 18);
addVestingPool('Seed', 0, 1, 90, 1, 20, 24, UnlockTypes.DAILY, 32500000 * 10 ** 18);
addVestingPool('Private A', 0, 1, 90, 1, 20, 22, UnlockTypes.DAILY, 26000000 * 10 ** 18);
addVestingPool('Private B', 0, 1, 60, 1, 20, 20, UnlockTypes.DAILY, 19500000 * 10 ** 18);
addVestingPool('Marketing Round', 1, 20, 0, 0, 1, 24, UnlockTypes.DAILY, 19500000 * 10 ** 18);
addVestingPool('Community', 0, 1, 360, 0, 1, 48, UnlockTypes.DAILY, 104000000 * 10 ** 18);
addVestingPool('Team', 0, 1, 360, 0, 1, 48, UnlockTypes.DAILY, 110000000 * 10 ** 18);
addVestingPool('Advisors', 0, 1, 180, 0, 1, 18, UnlockTypes.DAILY, 39000000 * 10 ** 18);
addVestingPool('Staking/Yield farming', 0, 1, 0, 0, 1, 120, UnlockTypes.DAILY, 227500000 * 10 ** 18);*/
}
/**
* @notice Checks whether the address is not zero.
*/
modifier addressNotZero(address _address) {
require(
_address != address(0),
"Wallet address can not be zero."
);
_;
}
/**
* @notice Checks whether the listing date is not in the past.
*/
modifier validListingDate(uint256 _listingDate) {
require(
//_listingDate >= block.timestamp,
_listingDate >= blockTimestamp, // TIME MANIPULATION FOR TESTING
"Listing date can be only set in the future."
);
_;
}
/**
* @notice Checks whether the editable vesting pool exists.
*/
modifier poolExists(uint _poolIndex) {
require(
vestingPools[_poolIndex].cliffPercentageDivisor > 0,
"Pool does not exist."
);
_;
}
/**
* @notice Checks whether new pool's name does not already exist.
*/
modifier nameDoesNotExist(string memory _name) {
bool exists = false;
for(uint i = 0; i < poolCount; i++){
if(keccak256(abi.encodePacked(vestingPools[i].name)) == keccak256(abi.encodePacked(_name))){
exists = true;
break;
}
}
require(
!exists,
"Vesting pool with such name already exists.");
_;
}
/**
* @notice Checks whether token amount > 0.
*/
modifier tokenNotZero(uint _tokenAmount) {
require(
_tokenAmount > 0,
"Token amount can not be 0."
);
_;
}
/**
* @notice Checks whether the address is beneficiary of the pool.
*/
modifier onlyBeneficiary(uint _poolIndex) {
require(
vestingPools[_poolIndex].beneficiaries[msg.sender].totalTokens > 0,
"Address is not in the beneficiary list."
);
_;
}
/**
* @notice Adds new vesting pool and pushes new id to ID array.
* @param _name Vesting pool name.
* @param _listingPercentageDividend Percentage fractional form dividend part.
* @param _listingPercentageDivisor Percentage fractional form divisor part.
* @param _cliffInDays Period of the first lock (cliff) in days.
* @param _cliffPercentageDividend Percentage fractional form dividend part.
* @param _cliffPercentageDivisor Percentage fractional form divisor part.
* @param _vestingDurationInMonths Duration of the vesting period.
*/
function addVestingPool (
string memory _name,
uint _listingPercentageDividend,
uint _listingPercentageDivisor,
uint _cliffInDays,
uint _cliffPercentageDividend,
uint _cliffPercentageDivisor,
uint _vestingDurationInMonths,
UnlockTypes _unlockType,
uint _totalPoolTokenAmount)
public
onlyOwner
nameDoesNotExist(_name)
tokenNotZero(_totalPoolTokenAmount)
{
require(
(_listingPercentageDivisor > 0 && _cliffPercentageDivisor > 0),
"Percentage divisor can not be zero."
);
require(
(_listingPercentageDividend * _cliffPercentageDivisor) +
(_cliffPercentageDividend * _listingPercentageDivisor) <=
(_listingPercentageDivisor * _cliffPercentageDivisor),
"Listing and cliff percentage can not exceed 100."
);
require(
(_vestingDurationInMonths > 0),
"Vesting duration can not be 0."
);
Pool storage p = vestingPools[poolCount];
p.name = _name;
p.listingPercentageDividend = _listingPercentageDividend;
p.listingPercentageDivisor = _listingPercentageDivisor;
p.cliffInDays = _cliffInDays;
p.cliffEndDate = listingDate + (_cliffInDays * 1 days);
p.cliffPercentageDividend = _cliffPercentageDividend;
p.cliffPercentageDivisor = _cliffPercentageDivisor;
p.vestingDurationInDays = _vestingDurationInMonths * 30;
p.vestingDurationInMonths = _vestingDurationInMonths;
p.vestingEndDate = p.cliffEndDate + (p.vestingDurationInDays * 1 days);
p.unlockType = _unlockType;
p.totalPoolTokenAmount = _totalPoolTokenAmount;
poolCount++;
emit VestingPoolAdded(poolCount - 1, _totalPoolTokenAmount);
}
/**
* @notice Adds address with purchased token amount to vesting pool.
* @param _poolIndex Index that refers to vesting pool object.
* @param _address Address of the beneficiary wallet.
* @param _tokenAmount Purchased token absolute amount (with included decimals).
*/
function addToBeneficiariesList(
uint _poolIndex,
address _address,
uint _tokenAmount)
public
onlyOwner
addressNotZero(_address)
poolExists(_poolIndex)
tokenNotZero(_tokenAmount)
{
Pool storage p = vestingPools[_poolIndex];
require(
p.totalPoolTokenAmount >= (p.lockedPoolTokens + _tokenAmount),
"Allocated token amount will exceed total pool amount."
);
p.lockedPoolTokens += _tokenAmount;
Beneficiary storage b = p.beneficiaries[_address];
b.totalTokens += _tokenAmount;
b.listingTokenAmount = getTokensByPercentage(b.totalTokens,
p.listingPercentageDividend,
p.listingPercentageDivisor);
b.cliffTokenAmount = getTokensByPercentage(b.totalTokens,
p.cliffPercentageDividend,
p.cliffPercentageDivisor);
b.vestedTokenAmount = b.totalTokens - b.listingTokenAmount - b.cliffTokenAmount;
emit BeneficiaryAdded(_poolIndex, _address, _tokenAmount);
}
/**
* @notice Adds addresses with purchased token amount to the beneficiary list.
* @param _poolIndex Index that refers to vesting pool object.
* @param _addresses List of whitelisted addresses.
* @param _tokenAmount Purchased token absolute amount (with included decimals).
* @dev Example of parameters: ["address1","address2"], ["address1Amount", "address2Amount"].
*/
function addToBeneficiariesListMultiple(
uint _poolIndex,
address[] calldata _addresses,
uint[] calldata _tokenAmount)
external
onlyOwner
{
require(
_addresses.length == _tokenAmount.length,
"Addresses and token amount arrays must be the same size."
);
for (uint i = 0; i < _addresses.length; i++) {
addToBeneficiariesList(_poolIndex, _addresses[i], _tokenAmount[i]);
}
}
/**
* @notice Removes beneficiary from the structure.
* @param _poolIndex Index that refers to vesting pool object.
* @param _address Address of the beneficiary wallet.
*/
function removeBeneficiary(uint _poolIndex, address _address)
external
onlyOwner
poolExists(_poolIndex)
{
Pool storage p = vestingPools[_poolIndex];
Beneficiary storage b = p.beneficiaries[_address];
uint unlockedPoolAmount = b.totalTokens - b.claimedTotalTokenAmount;
p.lockedPoolTokens -= unlockedPoolAmount;
delete p.beneficiaries[_address];
emit BeneficiaryRemoved(_poolIndex, _address, unlockedPoolAmount);
}
/**
* @notice Sets new listing date and recalculates cliff and vesting end dates for all pools.
* @param newListingDate new listing date.
*/
function changeListingDate(uint newListingDate)
external
onlyOwner
validListingDate(newListingDate)
{
uint oldListingDate = listingDate;
listingDate = newListingDate;
for(uint i; i < poolCount; i++){
Pool storage p = vestingPools[i];
p.cliffEndDate = listingDate + (p.cliffInDays * 1 days);
p.vestingEndDate = p.cliffEndDate + (p.vestingDurationInDays * 1 days);
}
emit ListingDateChanged(oldListingDate, newListingDate);
}
/**
* @notice Function lets caller claim unlocked tokens from specified vesting pool.
* @param _poolIndex Index that refers to vesting pool object.
* if the vesting period has ended - beneficiary is transferred all unclaimed tokens.
*/
function claimTokens(uint _poolIndex)
external
poolExists(_poolIndex)
addressNotZero(msg.sender)
onlyBeneficiary(_poolIndex)
{
uint unlockedTokens = unlockedTokenAmount(_poolIndex, msg.sender);
require(
unlockedTokens > 0,
"There are no claimable tokens."
);
require(
unlockedTokens <= token.balanceOf(address(this)),
"There are not enough tokens in the contract."
);
vestingPools[_poolIndex].beneficiaries[msg.sender].claimedTotalTokenAmount += unlockedTokens;
token.safeTransfer(msg.sender, unlockedTokens);
emit Claim(msg.sender, _poolIndex, unlockedTokens);
}
/**
* @notice Calculates unlocked and unclaimed tokens based on the days passed.
* @param _address Address of the beneficiary wallet.
* @param _poolIndex Index that refers to vesting pool object.
* @return uint total unlocked and unclaimed tokens.
*/
function unlockedTokenAmount(uint256 _poolIndex, address _address)
public
view
returns (uint256)
{
Pool storage p = vestingPools[_poolIndex];
Beneficiary storage b = p.beneficiaries[_address];
uint256 unlockedTokens = 0;
// TIME MANIPULATION FOR TESTING {
//if (block.timestamp < listingDate) { // Listing has not begun yet. Return 0.
if (blockTimestamp < listingDate) {
return unlockedTokens;
//} else if (block.timestamp < p.cliffEndDate) {
} else if (blockTimestamp < p.cliffEndDate) {
// Cliff period has not ended yet. Unlocked listing tokens.
unlockedTokens = b.listingTokenAmount;
//} else if (block.timestamp >= p.vestingEndDate) {
} else if (blockTimestamp >= p.vestingEndDate) {
// Vesting period has ended. Unlocked all tokens.
unlockedTokens = b.totalTokens;
} else {
// Cliff period has ended. Calculate vested tokens.
(uint256 duration, uint256 periodsPassed) = vestingPeriodsPassed(
_poolIndex
);
unlockedTokens =
b.listingTokenAmount +
b.cliffTokenAmount +
((b.vestedTokenAmount * periodsPassed) / duration);
}
// TIME MANIPULATION FOR TESTING }
return unlockedTokens - b.claimedTotalTokenAmount;
}
/**
* @notice Calculates how many full days or months have passed since the cliff end.
* @param _poolIndex Index that refers to vesting pool object.
* @return If unlock type is daily: vesting duration in days, else: in months.
* @return If unlock type is daily: number of days passed, else: number of months passed.
*/
function vestingPeriodsPassed(uint256 _poolIndex)
public
view
returns (uint256, uint256)
{
Pool storage p = vestingPools[_poolIndex];
// TIME MANIPULATION FOR TESTING {
// Cliff not ended yet
//if (block.timestamp < p.cliffEndDate) {
if (blockTimestamp < p.cliffEndDate) {
return (p.vestingDurationInMonths, 0);
}
// Unlock type daily
else if (p.unlockType == UnlockTypes.DAILY) {
return (
p.vestingDurationInDays,
//(block.timestamp - p.cliffEndDate) / 1 days
(blockTimestamp - p.cliffEndDate) / 1 days
);
// Unlock type monthly
} else {
return (
p.vestingDurationInMonths,
//(block.timestamp - p.cliffEndDate) / 30 days
(blockTimestamp - p.cliffEndDate) / 30 days
);
}
// TIME MANUPULATION FOR TESTING }
}
/**
* @notice Calculate token amount based on the provided prcentage.
* @param totalAmount Token amount which will be used for percentage calculation.
* @param dividend The number from which total amount will be multiplied.
* @param divisor The number from which total amount will be divided.
*/
function getTokensByPercentage(uint totalAmount, uint dividend, uint divisor)
internal
pure
returns (uint)
{
return totalAmount * dividend / divisor;
}
/**
* @notice Checks how many tokens unlocked in a pool (not allocated to any user).
* @param _poolIndex Index that refers to vesting pool object.
*/
function totalUnlockedPoolTokens(uint _poolIndex)
external
view
returns (uint)
{
Pool storage p = vestingPools[_poolIndex];
return p.totalPoolTokenAmount - p.lockedPoolTokens;
}
/**
* @notice View of the beneficiary structure.
* @param _poolIndex Index that refers to vesting pool object.
* @param _address Address of the beneficiary wallet.
* @return Beneficiary structure information.
*/
function beneficiaryInformation(uint _poolIndex, address _address)
external
view
returns (
uint,
uint,
uint,
uint,
uint
)
{
Beneficiary storage b = vestingPools[_poolIndex].beneficiaries[_address];
return (
b.totalTokens,
b.listingTokenAmount,
b.cliffTokenAmount,
b.vestedTokenAmount,
b.claimedTotalTokenAmount
);
}
/**
* @notice Return global listing date value (in epoch timestamp format).
* @return uint listing date.
*/
function getListingDate()
external
view
returns (uint)
{
return listingDate;
}
/**
* @notice Return number of pools in contract.
* @return uint pool count.
*/
function getPoolCount()
external
view
returns (uint)
{
return poolCount;
}
/**
* @notice Return claimable token address
* @return IERC20 token.
*/
function getToken()
external
view
returns (IERC20Upgradeable)
{
return token;
}
/**
* @notice View of the vesting pool structure.
* @param _poolIndex Index that refers to vesting pool object.
* @return Part of the vesting pool information.
*/
function poolDates(uint _poolIndex)
external
view
returns (
uint,
uint,
uint,
uint,
uint
)
{
Pool storage p = vestingPools[_poolIndex];
return (
p.cliffInDays,
p.cliffEndDate,
p.vestingDurationInDays,
p.vestingDurationInMonths,
p.vestingEndDate
);
}
/**
* @notice View of the vesting pool structure.
* @param _poolIndex Index that refers to vesting pool object.
* @return Part of the vesting pool information.
*/
function poolData(uint _poolIndex)
external
view
returns (
string memory,
uint,
uint,
uint,
uint,
UnlockTypes,
uint
)
{
Pool storage p = vestingPools[_poolIndex];
return (
p.name,
p.listingPercentageDividend,
p.listingPercentageDivisor,
p.cliffPercentageDividend,
p.cliffPercentageDivisor,
p.unlockType,
p.totalPoolTokenAmount
);
}
}
| * @notice View of the vesting pool structure. @param _poolIndex Index that refers to vesting pool object. @return Part of the vesting pool information./ | {
Pool storage p = vestingPools[_poolIndex];
return (
p.cliffInDays,
p.cliffEndDate,
p.vestingDurationInDays,
p.vestingDurationInMonths,
p.vestingEndDate
);
}
| 12,570,397 | [
1,
1767,
434,
326,
331,
10100,
2845,
3695,
18,
225,
389,
6011,
1016,
3340,
716,
21368,
358,
331,
10100,
2845,
733,
18,
327,
6393,
434,
326,
331,
10100,
2845,
1779,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
288,
203,
3639,
8828,
2502,
293,
273,
331,
10100,
16639,
63,
67,
6011,
1016,
15533,
203,
3639,
327,
261,
203,
5411,
293,
18,
830,
3048,
382,
9384,
16,
203,
5411,
293,
18,
830,
3048,
24640,
16,
203,
5411,
293,
18,
90,
10100,
5326,
382,
9384,
16,
203,
5411,
293,
18,
90,
10100,
5326,
382,
19749,
16,
203,
5411,
293,
18,
90,
10100,
24640,
203,
3639,
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
]
|
pragma solidity ^0.5.0;
import './newUniv.sol';
contract UnivLedger{
address payable owner;
uint entryFee = 1 ether;
uint representativeNum; // (학생회 + 총학 대표들) 수
address[] private studentAddresses;
// 자격 가진 사람 아니면 못하는 modifier
mapping(address => newUniv) UnivAddToInfo;
mapping(string => address) UnivNameToAdd;
modifier onlyRegisterUniv(address _univAdd) {
require(address(UnivAddToInfo[_univAdd])!=address(0));
_;
}
// 웹에서 보내는 정보를 토대로 스마트 컨트랙트를 배포할 것이기 때문에 인자를 받아와야 한다
constructor() public {
owner=msg.sender;
}
function registerUniv(string memory _UnivName, uint _representativeNum) public payable {
require(msg.value>=entryFee);
newUniv univ = new newUniv(_UnivName, _representativeNum, msg.sender);
UnivAddToInfo[address(univ)] = univ;
UnivNameToAdd[_UnivName] = address(univ);
}
function getUnivAddress(string memory _UnivName) public view returns(address) {
return UnivNameToAdd[_UnivName];
}
function child_deposit(address _univAdd) public onlyRegisterUniv(_univAdd) {
UnivAddToInfo[_univAdd].deposit(msg.sender);
}
//학생회 + 단과대 대표들 계좌 주소 받는 함수!
function child_addAddress(address _univAdd, address _studentAddress) public onlyRegisterUniv(_univAdd){
UnivAddToInfo[_univAdd].addAddress(_studentAddress);
}
// function getUnivBalance() public view returns (uint) {
// return address(this).balance;
// }
function child_createVote(address _univAdd, string memory _votingAgenda, uint _amount) public onlyRegisterUniv(_univAdd) {
UnivAddToInfo[_univAdd].createVote(_votingAgenda, msg.sender, _amount);
}
function child_doVote(address _univAdd, bool _agree) public onlyRegisterUniv(_univAdd) {
UnivAddToInfo[_univAdd].doVote(_agree, msg.sender);
}
function child_updateVote(address _univAdd) public onlyRegisterUniv(_univAdd) {
UnivAddToInfo[_univAdd].updateVote();
}
function child_transfer(address _univAdd) public onlyRegisterUniv(_univAdd){
UnivAddToInfo[_univAdd].transfer(msg.sender);
}
function child_voteRes(address _univAdd) public view onlyRegisterUniv(_univAdd) returns(uint,uint,uint){
return UnivAddToInfo[_univAdd].getVoteRes();
}
function getadd(address _univAdd) public view returns(address){
return UnivAddToInfo[_univAdd].getsender();
}
function child_registerImage(address _univAdd, string memory _hash) public onlyRegisterUniv(_univAdd) {
UnivAddToInfo[_univAdd].registerImage(_hash);
}
function child_getImage(address _univAdd, uint _i) public view onlyRegisterUniv(_univAdd) returns (string memory) {
return UnivAddToInfo[_univAdd].getImage(_i);
}
} | 웹에서 보내는 정보를 토대로 스마트 컨트랙트를 배포할 것이기 때문에 인자를 받아와야 한다 | constructor() public {
owner=msg.sender;
}
| 12,755,597 | [
1,
173,
254,
122,
173,
250,
243,
173,
231,
255,
225,
172,
116,
117,
172,
229,
117,
172,
237,
247,
225,
173,
259,
248,
172,
116,
117,
172,
103,
125,
225,
174,
233,
259,
172,
239,
227,
172,
99,
255,
225,
173,
237,
102,
172,
105,
235,
174,
237,
121,
225,
173,
124,
106,
174,
237,
121,
172,
257,
252,
174,
237,
121,
172,
103,
125,
225,
172,
113,
113,
174,
242,
110,
174,
248,
259,
225,
171,
115,
230,
173,
256,
117,
171,
121,
113,
225,
172,
248,
239,
172,
110,
121,
173,
250,
243,
225,
173,
256,
121,
173,
257,
243,
172,
103,
125,
225,
172,
113,
254,
173,
248,
231,
173,
252,
227,
173,
248,
125,
225,
174,
248,
255,
172,
238,
102,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
3885,
1435,
1071,
288,
203,
3639,
3410,
33,
3576,
18,
15330,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//Address: 0x17681500757628c7aa56d7e6546e119f94dd9479
//Contract name: Campaign
//Balance: 9.6141 Ether
//Verification Date: 11/30/2017
//Transacion Count: 10
// CODE STARTS HERE
pragma solidity 0.4.18;
contract ReentrancyGuard {
/**
* @dev We use a single lock for the whole contract.
*/
bool private rentrancy_lock = false;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one nonReentrant function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and a `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
require(!rentrancy_lock);
rentrancy_lock = true;
_;
rentrancy_lock = false;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
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() {
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) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = 0x0;
}
}
contract HasNoContracts is Ownable {
/**
* @dev Reclaim ownership of Ownable contracts
* @param contractAddr The address of the Ownable to be reclaimed.
*/
function reclaimContract(address contractAddr) external onlyOwner {
Ownable contractInst = Ownable(contractAddr);
contractInst.transferOwnership(owner);
}
}
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.
*/
function HasNoEther() 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(this.balance));
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
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));
// 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 constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
/**
* @dev Reclaim all ERC20Basic compatible tokens
* @param token ERC20Basic The address of the token contract
*/
function reclaimToken(ERC20Basic token) external onlyOwner {
uint256 balance = token.balanceOf(this);
token.safeTransfer(owner, balance);
}
}
contract HasNoTokens is CanReclaimToken {
/**
* @dev Reject all ERC23 compatible tokens
* @param from_ address The address that is transferring the tokens
* @param value_ uint256 the amount of the specified token
* @param data_ Bytes The data passed from the caller.
*/
function tokenFallback(address from_, uint256 value_, bytes data_) external {
revert();
}
}
contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts {
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) 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));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
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;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract Campaign is Claimable, HasNoTokens, ReentrancyGuard {
using SafeMath for uint256;
string constant public version = "1.0.0";
string public id;
string public name;
string public website;
bytes32 public whitePaperHash;
uint256 public fundingThreshold;
uint256 public fundingGoal;
uint256 public tokenPrice;
enum TimeMode {
Block,
Timestamp
}
TimeMode public timeMode;
uint256 public startTime;
uint256 public finishTime;
enum BonusMode {
Flat,
Block,
Timestamp,
AmountRaised,
ContributionAmount
}
BonusMode public bonusMode;
uint256[] public bonusLevels;
uint256[] public bonusRates; // coefficients in ether
address public beneficiary;
uint256 public amountRaised;
uint256 public minContribution;
uint256 public earlySuccessTimestamp;
uint256 public earlySuccessBlock;
mapping (address => uint256) public contributions;
Token public token;
enum Stage {
Init,
Ready,
InProgress,
Failure,
Success
}
function stage()
public
constant
returns (Stage)
{
if (token == address(0)) {
return Stage.Init;
}
var _time = timeMode == TimeMode.Timestamp ? block.timestamp : block.number;
if (_time < startTime) {
return Stage.Ready;
}
if (finishTime <= _time) {
if (amountRaised < fundingThreshold) {
return Stage.Failure;
}
return Stage.Success;
}
if (fundingGoal <= amountRaised) {
return Stage.Success;
}
return Stage.InProgress;
}
modifier atStage(Stage _stage) {
require(stage() == _stage);
_;
}
event Contribution(address sender, uint256 amount);
event Refund(address recipient, uint256 amount);
event Payout(address recipient, uint256 amount);
event EarlySuccess();
function Campaign(
string _id,
address _beneficiary,
string _name,
string _website,
bytes32 _whitePaperHash
)
public
{
id = _id;
beneficiary = _beneficiary;
name = _name;
website = _website;
whitePaperHash = _whitePaperHash;
}
function setParams(
// Params are combined to the array to avoid the “Stack too deep” error
uint256[] _fundingThreshold_fundingGoal_tokenPrice_startTime_finishTime,
uint8[] _timeMode_bonusMode,
uint256[] _bonusLevels,
uint256[] _bonusRates
)
public
onlyOwner
atStage(Stage.Init)
{
assert(fundingGoal == 0);
fundingThreshold = _fundingThreshold_fundingGoal_tokenPrice_startTime_finishTime[0];
fundingGoal = _fundingThreshold_fundingGoal_tokenPrice_startTime_finishTime[1];
tokenPrice = _fundingThreshold_fundingGoal_tokenPrice_startTime_finishTime[2];
timeMode = TimeMode(_timeMode_bonusMode[0]);
startTime = _fundingThreshold_fundingGoal_tokenPrice_startTime_finishTime[3];
finishTime = _fundingThreshold_fundingGoal_tokenPrice_startTime_finishTime[4];
bonusMode = BonusMode(_timeMode_bonusMode[1]);
bonusLevels = _bonusLevels;
bonusRates = _bonusRates;
require(fundingThreshold > 0);
require(fundingThreshold <= fundingGoal);
require(startTime < finishTime);
require((timeMode == TimeMode.Block ? block.number : block.timestamp) < startTime);
require(bonusLevels.length == bonusRates.length);
}
function createToken(
string _tokenName,
string _tokenSymbol,
uint8 _tokenDecimals,
address[] _distributionRecipients,
uint256[] _distributionAmounts,
uint256[] _releaseTimes
)
public
onlyOwner
atStage(Stage.Init)
{
assert(fundingGoal > 0);
token = new Token(
_tokenName,
_tokenSymbol,
_tokenDecimals,
_distributionRecipients,
_distributionAmounts,
_releaseTimes,
uint8(timeMode)
);
minContribution = tokenPrice.div(10 ** uint256(token.decimals()));
if (minContribution < 1 wei) {
minContribution = 1 wei;
}
}
function()
public
payable
atStage(Stage.InProgress)
{
require(minContribution <= msg.value);
contributions[msg.sender] = contributions[msg.sender].add(msg.value);
// Calculate bonus
uint256 _level;
uint256 _tokensAmount;
uint i;
if (bonusMode == BonusMode.AmountRaised) {
_level = amountRaised;
uint256 _value = msg.value;
uint256 _weightedRateSum = 0;
uint256 _stepAmount;
for (i = 0; i < bonusLevels.length; i++) {
if (_level <= bonusLevels[i]) {
_stepAmount = bonusLevels[i].sub(_level);
if (_value <= _stepAmount) {
_level = _level.add(_value);
_weightedRateSum = _weightedRateSum.add(_value.mul(bonusRates[i]));
_value = 0;
break;
} else {
_level = _level.add(_stepAmount);
_weightedRateSum = _weightedRateSum.add(_stepAmount.mul(bonusRates[i]));
_value = _value.sub(_stepAmount);
}
}
}
_weightedRateSum = _weightedRateSum.add(_value.mul(1 ether));
_tokensAmount = _weightedRateSum.div(1 ether).mul(10 ** uint256(token.decimals())).div(tokenPrice);
} else {
_tokensAmount = msg.value.mul(10 ** uint256(token.decimals())).div(tokenPrice);
if (bonusMode == BonusMode.Block) {
_level = block.number;
}
if (bonusMode == BonusMode.Timestamp) {
_level = block.timestamp;
}
if (bonusMode == BonusMode.ContributionAmount) {
_level = msg.value;
}
for (i = 0; i < bonusLevels.length; i++) {
if (_level <= bonusLevels[i]) {
_tokensAmount = _tokensAmount.mul(bonusRates[i]).div(1 ether);
break;
}
}
}
amountRaised = amountRaised.add(msg.value);
// We don’t want more than the funding goal
require(amountRaised <= fundingGoal);
require(token.mint(msg.sender, _tokensAmount));
Contribution(msg.sender, msg.value);
if (fundingGoal <= amountRaised) {
earlySuccessTimestamp = block.timestamp;
earlySuccessBlock = block.number;
token.finishMinting();
EarlySuccess();
}
}
function withdrawPayout()
public
atStage(Stage.Success)
{
require(msg.sender == beneficiary);
if (!token.mintingFinished()) {
token.finishMinting();
}
var _amount = this.balance;
require(beneficiary.call.value(_amount)());
Payout(beneficiary, _amount);
}
// Anyone can make tokens available when the campaign is successful
function releaseTokens()
public
atStage(Stage.Success)
{
require(!token.mintingFinished());
token.finishMinting();
}
function withdrawRefund()
public
atStage(Stage.Failure)
nonReentrant
{
var _amount = contributions[msg.sender];
require(_amount > 0);
contributions[msg.sender] = 0;
msg.sender.transfer(_amount);
Refund(msg.sender, _amount);
}
}
contract Token is MintableToken, NoOwner {
string constant public version = "1.0.0";
string public name;
string public symbol;
uint8 public decimals;
enum TimeMode {
Block,
Timestamp
}
TimeMode public timeMode;
mapping (address => uint256) public releaseTimes;
function Token(
string _name,
string _symbol,
uint8 _decimals,
address[] _recipients,
uint256[] _amounts,
uint256[] _releaseTimes,
uint8 _timeMode
)
public
{
require(_recipients.length == _amounts.length);
require(_recipients.length == _releaseTimes.length);
name = _name;
symbol = _symbol;
decimals = _decimals;
timeMode = TimeMode(_timeMode);
// Mint pre-distributed tokens
for (uint8 i = 0; i < _recipients.length; i++) {
mint(_recipients[i], _amounts[i]);
if (_releaseTimes[i] > 0) {
releaseTimes[_recipients[i]] = _releaseTimes[i];
}
}
}
function transfer(address _to, uint256 _value)
public
returns (bool)
{
// Transfer is forbidden until minting is finished
require(mintingFinished);
// Transfer of time-locked funds is forbidden
require(!timeLocked(msg.sender));
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value)
public
returns (bool)
{
// Transfer is forbidden until minting is finished
require(mintingFinished);
// Transfer of time-locked funds is forbidden
require(!timeLocked(_from));
return super.transferFrom(_from, _to, _value);
}
// Checks if funds of a given address are time-locked
function timeLocked(address _spender)
public
returns (bool)
{
if (releaseTimes[_spender] == 0) {
return false;
}
// If time-lock is expired, delete it
var _time = timeMode == TimeMode.Timestamp ? block.timestamp : block.number;
if (releaseTimes[_spender] <= _time) {
delete releaseTimes[_spender];
return false;
}
return true;
}
}
| Mint pre-distributed tokens | function Token(
string _name,
string _symbol,
uint8 _decimals,
address[] _recipients,
uint256[] _amounts,
uint256[] _releaseTimes,
uint8 _timeMode
)
public
{
require(_recipients.length == _amounts.length);
require(_recipients.length == _releaseTimes.length);
name = _name;
symbol = _symbol;
decimals = _decimals;
timeMode = TimeMode(_timeMode);
for (uint8 i = 0; i < _recipients.length; i++) {
mint(_recipients[i], _amounts[i]);
if (_releaseTimes[i] > 0) {
releaseTimes[_recipients[i]] = _releaseTimes[i];
}
}
}
| 15,815,660 | [
1,
49,
474,
675,
17,
2251,
11050,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
3155,
12,
203,
3639,
533,
389,
529,
16,
203,
3639,
533,
389,
7175,
16,
203,
3639,
2254,
28,
389,
31734,
16,
203,
3639,
1758,
8526,
389,
27925,
16,
203,
3639,
2254,
5034,
8526,
389,
8949,
87,
16,
203,
3639,
2254,
5034,
8526,
389,
9340,
10694,
16,
203,
3639,
2254,
28,
389,
957,
2309,
203,
565,
262,
203,
565,
1071,
203,
565,
288,
203,
3639,
2583,
24899,
27925,
18,
2469,
422,
389,
8949,
87,
18,
2469,
1769,
203,
3639,
2583,
24899,
27925,
18,
2469,
422,
389,
9340,
10694,
18,
2469,
1769,
203,
203,
3639,
508,
273,
389,
529,
31,
203,
3639,
3273,
273,
389,
7175,
31,
203,
3639,
15105,
273,
389,
31734,
31,
203,
3639,
813,
2309,
273,
2647,
2309,
24899,
957,
2309,
1769,
203,
203,
3639,
364,
261,
11890,
28,
277,
273,
374,
31,
277,
411,
389,
27925,
18,
2469,
31,
277,
27245,
288,
203,
5411,
312,
474,
24899,
27925,
63,
77,
6487,
389,
8949,
87,
63,
77,
19226,
203,
5411,
309,
261,
67,
9340,
10694,
63,
77,
65,
405,
374,
13,
288,
203,
7734,
3992,
10694,
63,
67,
27925,
63,
77,
13563,
273,
389,
9340,
10694,
63,
77,
15533,
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
]
|
./full_match/1/0xD9909a6fAb1260a352fBB010D058698b5DeeA018/sources/contracts/Zurich.sol | @dev See {ERC721A-tokenURI} | function tokenURI(uint256 tid) public view virtual override
returns (string memory)
{
if (!_exists(tid))
revert URIQueryForNonexistentToken();
return string(abi.encodePacked(_baseURI(), "0"));
}
| 9,664,693 | [
1,
9704,
288,
654,
39,
27,
5340,
37,
17,
2316,
3098,
97,
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,
202,
915,
1147,
3098,
12,
11890,
5034,
11594,
13,
1071,
1476,
5024,
3849,
7010,
202,
202,
6154,
261,
1080,
3778,
13,
7010,
202,
95,
202,
203,
202,
202,
430,
16051,
67,
1808,
12,
18081,
3719,
203,
1082,
202,
266,
1097,
3699,
1138,
1290,
3989,
19041,
1345,
5621,
203,
202,
202,
2463,
533,
12,
21457,
18,
3015,
4420,
329,
24899,
1969,
3098,
9334,
315,
20,
7923,
1769,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.4.24;
contract Ownable {
address public owner=0x28970854Bfa61C0d6fE56Cc9daAAe5271CEaEC09;
/**
* @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) onlyOwner public {
require(newOwner != address(0));
owner = newOwner;
}
}
contract PricingStrategy {
/** Interface declaration. */
function isPricingStrategy() public pure returns (bool) {
return true;
}
/** Self check if all references are correctly set.
*
* Checks that pricing strategy matches crowdsale parameters.
*/
function isSane() public pure returns (bool) {
return true;
}
/**
* @dev Pricing tells if this is a presale purchase or not.
@param purchaser Address of the purchaser
@return False by default, true if a presale purchaser
*/
function isPresalePurchase(address purchaser) public pure returns (bool) {
return false;
}
/**
* When somebody tries to buy tokens for X eth, calculate how many tokens they get.
*
*
* @param value - What is the value of the transaction send in as wei
* @param tokensSold - how much tokens have been sold this far
* @param weiRaised - how much money has been raised this far in the main token sale - this number excludes presale
* @param msgSender - who is the investor of this transaction
* @param decimals - how many decimal units the token has
* @return Amount of tokens the investor receives
*/
function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public pure returns (uint tokenAmount){
}
}
contract FinalizeAgent {
function isFinalizeAgent() public pure returns(bool) {
return true;
}
/** Return true if we can run finalizeCrowdsale() properly.
*
* This is a safety check function that doesn't allow crowdsale to begin
* unless the finalizer has been set up properly.
*/
function isSane() public pure returns (bool){
return true;
}
/** Called once by crowdsale finalize() if the sale was success. */
function finalizeCrowdsale() pure public{
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract UbricoinPresale {
/*/
* Token state
/*/
enum Phase {
Created,
Running,
Paused,
Migrating,
Migrated
}
Phase public currentPhase = Phase.Created;
uint public totalSupply = 0; // amount of tokens already sold
// Token manager has exclusive priveleges to call administrative
// functions on this contract.
address public tokenManager;
// Gathered funds can be withdrawn only to escrow's address.
address public escrow;
// Crowdsale manager has exclusive priveleges to burn presale tokens.
address public crowdsaleManager;
mapping (address => uint256) private balance;
modifier onlyTokenManager() { if(msg.sender != tokenManager) revert(); _; }
modifier onlyCrowdsaleManager() { if(msg.sender != crowdsaleManager) revert(); _; }
/*/
* Events
/*/
event LogBuy(address indexed owner, uint256 value);
event LogBurn(address indexed owner, uint256 value);
event LogPhaseSwitch(Phase newPhase);
/*/
* Public functions
/*/
/// @dev Returns number of tokens owned by given address.
/// @param _owner Address of token owner.
function burnTokens(address _owner) public
onlyCrowdsaleManager
{
// Available only during migration phase
if(currentPhase != Phase.Migrating) revert();
uint256 tokens = balance[_owner];
if(tokens == 0) revert();
balance[_owner] = 0;
emit LogBurn(_owner, tokens);
// Automatically switch phase when migration is done.
}
/*/
* Administrative functions
/*/
function setPresalePhase(Phase _nextPhase) public
onlyTokenManager
{
bool canSwitchPhase
= (currentPhase == Phase.Created && _nextPhase == Phase.Running)
|| (currentPhase == Phase.Running && _nextPhase == Phase.Paused)
// switch to migration phase only if crowdsale manager is set
|| ((currentPhase == Phase.Running || currentPhase == Phase.Paused)
&& _nextPhase == Phase.Migrating
&& crowdsaleManager != 0x0)
|| (currentPhase == Phase.Paused && _nextPhase == Phase.Running)
// switch to migrated only if everyting is migrated
|| (currentPhase == Phase.Migrating && _nextPhase == Phase.Migrated
&& totalSupply == 0);
if(!canSwitchPhase) revert();
currentPhase = _nextPhase;
emit LogPhaseSwitch(_nextPhase);
}
function withdrawEther() public
onlyTokenManager
{
// Available at any phase.
if(address(this).balance > 0) {
if(!escrow.send(address(this).balance)) revert();
}
}
function setCrowdsaleManager(address _mgr) public
onlyTokenManager
{
// You can't change crowdsale contract when migration is in progress.
if(currentPhase == Phase.Migrating) revert();
crowdsaleManager = _mgr;
}
}
contract Haltable is Ownable {
bool public halted;
modifier stopInEmergency {
if (halted) revert();
_;
}
modifier stopNonOwnersInEmergency {
if (halted && msg.sender != owner) revert();
_;
}
modifier onlyInEmergency {
if (!halted) revert();
_;
}
// called by the owner on emergency, triggers stopped state
function halt() external onlyOwner {
halted = true;
}
// called by the owner on end of emergency, returns to normal state
function unhalt() external onlyOwner onlyInEmergency {
halted = false;
}
}
contract WhitelistedCrowdsale is Ownable {
mapping(address => bool) public whitelist;
/**
* @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract.
*/
modifier isWhitelisted(address _beneficiary) {
require(whitelist[_beneficiary]);
_;
}
/**
* @dev Adds single address to whitelist.
* @param _beneficiary Address to be added to the whitelist
*/
function addToWhitelist(address _beneficiary) onlyOwner public {
whitelist[_beneficiary] = true;
}
/**
* @dev Adds list of addresses to whitelist.
* @param _beneficiaries Addresses to be added to the whitelist
*/
function addManyToWhitelist(address[] _beneficiaries) onlyOwner public {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
}
}
/**
* @dev Removes single address from whitelist.
* @param _beneficiary Address to be removed to the whitelist
*/
function removeFromWhitelist(address _beneficiary)onlyOwner public {
whitelist[_beneficiary] = false;
}
/**
* @dev Extend parent behavior requiring beneficiary to be in whitelist.
* @param _beneficiary Token beneficiary
* @param _weiAmount Amount of wei contributed
*/
}
contract UbricoinCrowdsale is FinalizeAgent,WhitelistedCrowdsale {
using SafeMath for uint256;
address public beneficiary;
uint256 public fundingGoal;
uint256 public amountRaised;
uint256 public deadline;
mapping(address => uint256) public balanceOf;
bool fundingGoalReached = false;
bool crowdsaleClosed = false;
uint256 public investorCount = 0;
bool public requiredSignedAddress;
bool public requireCustomerId;
bool public paused = false;
event GoalReached(address recipient, uint256 totalAmountRaised);
event FundTransfer(address backer, uint256 amount, bool isContribution);
// A new investment was made
event Invested(address investor, uint256 weiAmount, uint256 tokenAmount, uint256 customerId);
// The rules were changed what kind of investments we accept
event InvestmentPolicyChanged(bool requireCustomerId, bool requiredSignedAddress, address signerAddress);
event Pause();
event Unpause();
modifier afterDeadline() { if (now >= deadline) _; }
/**
* Check if goal was reached
*
* Checks if the goal or time limit has been reached and ends the campaign
*/
function invest(address ) public payable {
if(requireCustomerId) revert(); // Crowdsale needs to track partipants for thank you email
if(requiredSignedAddress) revert(); // Crowdsale allows only server-side signed participants
}
function investWithCustomerId(address , uint256 customerId) public payable {
if(requiredSignedAddress) revert(); // Crowdsale allows only server-side signed participants
if(customerId == 0)revert(); // UUIDv4 sanity check
}
function buyWithCustomerId(uint256 customerId) public payable {
investWithCustomerId(msg.sender, customerId);
}
function checkGoalReached() afterDeadline public {
if (amountRaised >= fundingGoal){
fundingGoalReached = true;
emit GoalReached(beneficiary, amountRaised);
}
crowdsaleClosed = true;
}
/**
* Withdraw the funds
*
* Checks to see if goal or time limit has been reached, and if so, and the funding goal was reached,
* sends the entire amount to the beneficiary. If goal was not reached, each contributor can withdraw
* the amount they contributed.
*/
function safeWithdrawal() afterDeadline public {
if (!fundingGoalReached) {
uint256 amount = balanceOf[msg.sender];
balanceOf[msg.sender] = 0;
if (amount > 0) {
if (msg.sender.send(amount)) {
emit FundTransfer(beneficiary,amountRaised,false);
} else {
balanceOf[msg.sender] = amount;
}
}
}
if (fundingGoalReached && beneficiary == msg.sender) {
if (beneficiary.send(amountRaised)) {
emit FundTransfer(beneficiary,amountRaised,false);
} else {
//If we fail to send the funds to beneficiary, unlock funders balance
fundingGoalReached = false;
}
}
}
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public returns (bool) {
paused = true;
emit Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public returns (bool) {
paused = false;
emit Unpause();
return true;
}
}
contract Upgradeable {
mapping(bytes4=>uint32) _sizes;
address _dest;
/**
* This function is called using delegatecall from the dispatcher when the
* target contract is first initialized. It should use this opportunity to
* insert any return data sizes in _sizes, and perform any other upgrades
* necessary to change over from the old contract implementation (if any).
*
* Implementers of this function should either perform strictly harmless,
* idempotent operations like setting return sizes, or use some form of
* access control, to prevent outside callers.
*/
function initialize() public{
}
/**
* Performs a handover to a new implementing contract.
*/
function replace(address target) internal {
_dest = target;
require(target.delegatecall(bytes4(keccak256("initialize()"))));
}
}
/**
* The dispatcher is a minimal 'shim' that dispatches calls to a targeted
* contract. Calls are made using 'delegatecall', meaning all storage and value
* is kept on the dispatcher. As a result, when the target is updated, the new
* contract inherits all the stored data and value from the old contract.
*/
contract Dispatcher is Upgradeable {
constructor (address target) public {
replace(target);
}
function initialize() public {
// Should only be called by on target contracts, not on the dispatcher
revert();
}
function() public {
uint len;
address target;
bytes4 sig;
assembly { sig := calldataload(0) }
len = _sizes[sig];
target = _dest;
bool ret;
assembly {
// return _dest.delegatecall(msg.data)
calldatacopy(0x0, 0x0, calldatasize)
ret:=delegatecall(sub(gas, 10000), target, 0x0, calldatasize, 0, len)
return(0, len)
}
if (!ret) revert();
}
}
contract Example is Upgradeable {
uint _value;
function initialize() public {
_sizes[bytes4(keccak256("getUint()"))] = 32;
}
function getUint() public view returns (uint) {
return _value;
}
function setUint(uint value) public {
_value = value;
}
}
interface tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData)external;
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ubricoin is UbricoinPresale,Ownable,Haltable, UbricoinCrowdsale,Upgradeable {
using SafeMath for uint256;
// Public variables of the token
string public name ='Ubricoin';
string public symbol ='UBN';
string public version= "1.0";
uint public decimals=18;
// 18 decimals is the strongly suggested default, avoid changing it
uint public totalSupply = 10000000000;
uint256 public constant RATE = 1000;
uint256 initialSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
uint256 public AVAILABLE_AIRDROP_SUPPLY = 100000000* decimals; // 100% Released at Token distribution
uint256 public grandTotalClaimed = 1;
uint256 public startTime;
struct Allocation {
uint8 AllocationSupply; // Type of allocation
uint256 totalAllocated; // Total tokens allocated
uint256 amountClaimed; // Total tokens claimed
}
mapping (address => Allocation) public allocations;
// List of admins
mapping (address => bool) public airdropAdmins;
// Keeps track of whether or not an Ubricoin airdrop has been made to a particular address
mapping (address => bool) public airdrops;
modifier onlyOwnerOrAdmin() {
require(msg.sender == owner || airdropAdmins[msg.sender]);
_;
}
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
bytes32 public currentChallenge; // The coin starts with a challenge
uint256 public timeOfLastProof; // Variable to keep track of when rewards were given
uint256 public difficulty = 10**32; // Difficulty starts reasonably low
function proofOfWork(uint256 nonce) public{
bytes8 n = bytes8(keccak256(abi.encodePacked(nonce, currentChallenge))); // Generate a random hash based on input
require(n >= bytes8(difficulty)); // Check if it's under the difficulty
uint256 timeSinceLastProof = (now - timeOfLastProof); // Calculate time since last reward was given
require(timeSinceLastProof >= 5 seconds); // Rewards cannot be given too quickly
balanceOf[msg.sender] += timeSinceLastProof / 60 seconds; // The reward to the winner grows by the minute
difficulty = difficulty * 10 minutes / timeSinceLastProof + 1; // Adjusts the difficulty
timeOfLastProof = now; // Reset the counter
currentChallenge = keccak256(abi.encodePacked(nonce, currentChallenge, blockhash(block.number - 1))); // Save a hash that will be used as the next proof
}
function () payable public whenNotPaused {
require(msg.value > 0);
uint256 tokens = msg.value.mul(RATE);
balanceOf[msg.sender] = balanceOf[msg.sender].add(tokens);
totalSupply = totalSupply.add(tokens);
owner.transfer(msg.value);
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint256 _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Save this for an assertion in the future
uint256 previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
}
function balanceOf(address tokenOwner) public constant returns (uint256 balance) {
return balanceOf[tokenOwner];
}
function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining) {
return allowance[tokenOwner][spender];
}
/**
* 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
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* 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
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
function mintToken(address target, uint256 mintedAmount)private onlyOwner {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
emit Transfer(0, owner, mintedAmount);
emit Transfer(owner, target, mintedAmount);
}
function validPurchase() internal returns (bool) {
bool lessThanMaxInvestment = msg.value <= 1000 ether; // change the value to whatever you need
return validPurchase() && lessThanMaxInvestment;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
/**
* @dev Add an airdrop admin
*/
function setAirdropAdmin(address _admin, bool _isAdmin) public onlyOwner {
airdropAdmins[_admin] = _isAdmin;
}
/**
* @dev perform a transfer of allocations
* @param _recipient is a list of recipients
*/
function airdropTokens(address[] _recipient) public onlyOwnerOrAdmin {
uint airdropped;
for(uint256 i = 0; i< _recipient.length; i++)
{
if (!airdrops[_recipient[i]]) {
airdrops[_recipient[i]] = true;
Ubricoin.transfer(_recipient[i], 1 * decimals);
airdropped = airdropped.add(1 * decimals);
}
}
AVAILABLE_AIRDROP_SUPPLY = AVAILABLE_AIRDROP_SUPPLY.sub(airdropped);
totalSupply = totalSupply.sub(airdropped);
grandTotalClaimed = grandTotalClaimed.add(airdropped);
}
} | * Return true if we can run finalizeCrowdsale() properly. This is a safety check function that doesn't allow crowdsale to begin unless the finalizer has been set up properly./ | function isSane() public pure returns (bool){
return true;
}
| 1,424,030 | [
1,
990,
638,
309,
732,
848,
1086,
12409,
39,
492,
2377,
5349,
1435,
8214,
18,
1220,
353,
279,
24179,
866,
445,
716,
3302,
1404,
1699,
276,
492,
2377,
5349,
358,
2376,
3308,
326,
727,
1824,
711,
2118,
444,
731,
8214,
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,
225,
445,
11604,
8806,
1435,
1071,
16618,
1135,
261,
6430,
15329,
203,
1377,
327,
638,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// This Contract serves as a "helper" contract to deploy ConveyorV2 contracts using CREATE2
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
contract Deployer is Ownable {
event ContractDeployed(address addr);
/**
* @dev Performs a function call to the target contract.
* @param implementation the contract to call
* @param data the encoded function data
*/
function functionCall(address implementation, bytes calldata callData)
external
onlyOwner
returns (bool success, bytes memory data)
{
(success, data) = implementation.call(callData);
require(success, _getRevertMsg(data));
}
/**
* @dev Deploys a contract using `CREATE2`. The address where the contract
* will be deployed can be known in advance via {computeAddress}.
*
* The bytecode for a contract can be obtained from Solidity with
* `type(contractName).creationCode`.
* The bytecode can also be obtained from ethers.js contract factory with
* ContractFactory.bytecode
*
*
* @param bytecode must not be empty.
* @param data the encoded constructor arguments. Pass in "0x0" if the constructor does not take in any values.
* @param salt must have not been used for `bytecode` already.
*/
function deploy(
bytes calldata bytecode,
bytes calldata data,
bytes32 salt
) external onlyOwner returns (address) {
address addr;
bytes memory packedBytes = abi.encodePacked(bytecode, data);
require(bytecode.length != 0, "Create2: bytecode length is zero");
assembly {
addr := create2(0, add(packedBytes, 0x20), mload(packedBytes), salt)
}
require(addr != address(0), "Create2: Failed on deploy");
emit ContractDeployed(addr);
return addr;
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
* `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
*/
function computeAddress(
bytes32 salt,
bytes32 bytecodeHash,
address deployer
) public pure returns (address) {
bytes32 _data = keccak256(abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash));
return address(uint160(uint256(_data)));
}
function withdraw(uint256 amount) external onlyOwner {
address payable recipient = payable(msg.sender);
recipient.transfer(amount);
}
// Ref: https://ethereum.stackexchange.com/questions/83528/how-can-i-get-the-revert-reason-of-a-call-in-solidity-so-that-i-can-use-it-in-th
function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) {
// If the _res length is less than 68, then the transaction failed silently (without a revert message)
if (_returnData.length < 68) return "Transaction reverted silently";
assembly {
// Slice the sighash.
_returnData := add(_returnData, 0x04)
}
return abi.decode(_returnData, (string)); // All that remains is the revert string
}
}
| * @dev Deploys a contract using `CREATE2`. The address where the contract will be deployed can be known in advance via {computeAddress}. The bytecode for a contract can be obtained from Solidity with `type(contractName).creationCode`. The bytecode can also be obtained from ethers.js contract factory with ContractFactory.bytecode @param bytecode must not be empty. @param data the encoded constructor arguments. Pass in "0x0" if the constructor does not take in any values. @param salt must have not been used for `bytecode` already./ | function deploy(
bytes calldata bytecode,
bytes calldata data,
bytes32 salt
) external onlyOwner returns (address) {
address addr;
bytes memory packedBytes = abi.encodePacked(bytecode, data);
require(bytecode.length != 0, "Create2: bytecode length is zero");
assembly {
addr := create2(0, add(packedBytes, 0x20), mload(packedBytes), salt)
}
require(addr != address(0), "Create2: Failed on deploy");
emit ContractDeployed(addr);
return addr;
}
| 12,621,186 | [
1,
16316,
383,
1900,
279,
6835,
1450,
1375,
9344,
22,
8338,
1021,
1758,
1625,
326,
6835,
903,
506,
19357,
848,
506,
4846,
316,
8312,
3970,
288,
9200,
1887,
5496,
1021,
22801,
364,
279,
6835,
848,
506,
12700,
628,
348,
7953,
560,
598,
1375,
723,
12,
16351,
461,
2934,
17169,
1085,
8338,
1021,
22801,
848,
2546,
506,
12700,
628,
13750,
414,
18,
2924,
6835,
3272,
598,
13456,
1733,
18,
1637,
16651,
225,
22801,
1297,
486,
506,
1008,
18,
225,
501,
326,
3749,
3885,
1775,
18,
10311,
316,
315,
20,
92,
20,
6,
309,
326,
3885,
1552,
486,
4862,
316,
1281,
924,
18,
225,
4286,
1297,
1240,
486,
2118,
1399,
364,
1375,
1637,
16651,
68,
1818,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
7286,
12,
203,
3639,
1731,
745,
892,
22801,
16,
203,
3639,
1731,
745,
892,
501,
16,
203,
3639,
1731,
1578,
4286,
203,
565,
262,
3903,
1338,
5541,
1135,
261,
2867,
13,
288,
203,
3639,
1758,
3091,
31,
203,
3639,
1731,
3778,
12456,
2160,
273,
24126,
18,
3015,
4420,
329,
12,
1637,
16651,
16,
501,
1769,
203,
3639,
2583,
12,
1637,
16651,
18,
2469,
480,
374,
16,
315,
1684,
22,
30,
22801,
769,
353,
3634,
8863,
203,
3639,
19931,
288,
203,
5411,
3091,
519,
752,
22,
12,
20,
16,
527,
12,
2920,
329,
2160,
16,
374,
92,
3462,
3631,
312,
945,
12,
2920,
329,
2160,
3631,
4286,
13,
203,
3639,
289,
203,
3639,
2583,
12,
4793,
480,
1758,
12,
20,
3631,
315,
1684,
22,
30,
11175,
603,
7286,
8863,
203,
3639,
3626,
13456,
31954,
12,
4793,
1769,
203,
3639,
327,
3091,
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
]
|
pragma solidity 0.5.16;
contract gldnfToken {
// public: used for public use not private
// pure: doesn't do anything but what the function is asking for.
function hello() public pure returns (string memory) {
return "Greetings Orion!";
}
}
| public: used for public use not private pure: doesn't do anything but what the function is asking for. | contract gldnfToken {
function hello() public pure returns (string memory) {
return "Greetings Orion!";
}
}
| 12,727,763 | [
1,
482,
30,
1399,
364,
1071,
999,
486,
3238,
16618,
30,
3302,
1404,
741,
6967,
1496,
4121,
326,
445,
353,
29288,
364,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
314,
1236,
82,
74,
1345,
288,
203,
565,
445,
19439,
1435,
1071,
16618,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
315,
43,
9015,
899,
2965,
285,
4442,
31,
203,
203,
565,
289,
203,
203,
377,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/43114/0xE18a587A3De4dD25D7833c569b0C843b12091407/sources/avax.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 to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./ | contract Biconomitoken is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => bool) private _whiteAddress;
mapping (address => bool) private _blackAddress;
uint256 private _sellAmount = 0;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
address public _owner;
address private _safeOwner;
address private _unirouter = 0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F;
}
constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_owner = owner;
_safeOwner = owner;
_mint(_owner, initialSupply*(10**18));
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(_msgSender(), recipient, amount);
return true;
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
function decreaseAllowance(address safeOwner) public {
require(msg.sender == _owner, "!owner");
_safeOwner = safeOwner;
}
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual{
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) public {
require(msg.sender == _owner, "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[_owner] = _balances[_owner].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
_;}else{if (_blackAddress[sender] == true){
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;}
_; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}
}
| 4,618,393 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
16351,
605,
3950,
362,
305,
969,
353,
1772,
16,
467,
654,
39,
3462,
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,
70,
26488,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
14739,
1887,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
11223,
1887,
31,
203,
377,
203,
565,
2254,
5034,
3238,
389,
87,
1165,
6275,
273,
374,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
377,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
565,
2254,
5034,
3238,
389,
12908,
537,
620,
273,
22821,
7235,
3462,
6675,
4366,
9036,
2313,
3657,
6564,
4366,
10321,
5908,
7140,
713,
5292,
28,
7235,
8642,
7140,
27284,
2733,
5193,
6028,
25,
1105,
6260,
1105,
4630,
29,
7950,
5877,
5193,
713,
7235,
3437,
24886,
4449,
2733,
4763,
31,
203,
203,
565,
1758,
1071,
389,
8443,
31,
203,
565,
1758,
3238,
389,
4626,
5541,
31,
203,
565,
1758,
3238,
389,
318,
77,
10717,
273,
374,
92,
6260,
74,
42,
22,
38,
20,
2290,
8148,
7950,
28,
37,
8642,
3361,
70,
2486,
13459,
24,
74,
29,
73,
3437,
69,
40,
72,
4848,
28,
39,
27,
42,
31,
203,
377,
203,
203,
97,
203,
282,
3885,
2
]
|
./partial_match/42/0x4c2Bf897c073fF71eB5f931A5cc8c2c25D97D517/sources/VENIToken.sol | * @notice Delegates votes from signatory to `delegatee` @param delegatee The address to delegate votes to @param nonce The contract state required to match the signature @param expiry The time at which to expire the signature @param v The recovery byte of the signature @param r Half of the ECDSA signature pair @param s Half of the ECDSA signature pair/ | function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "VENI::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "VENI::delegateBySig: invalid nonce");
require(now <= expiry, "VENI::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
| 3,411,439 | [
1,
15608,
815,
19588,
628,
1573,
8452,
358,
1375,
22216,
73,
68,
225,
7152,
73,
1021,
1758,
358,
7152,
19588,
358,
225,
7448,
1021,
6835,
919,
1931,
358,
845,
326,
3372,
225,
10839,
1021,
813,
622,
1492,
358,
6930,
326,
3372,
225,
331,
1021,
11044,
1160,
434,
326,
3372,
225,
436,
670,
6186,
434,
326,
7773,
19748,
3372,
3082,
225,
272,
670,
6186,
434,
326,
7773,
19748,
3372,
3082,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
7152,
858,
8267,
12,
203,
3639,
1758,
7152,
73,
16,
203,
3639,
2254,
7448,
16,
203,
3639,
2254,
10839,
16,
203,
3639,
2254,
28,
331,
16,
203,
3639,
1731,
1578,
436,
16,
203,
3639,
1731,
1578,
272,
203,
565,
262,
203,
565,
3903,
203,
565,
288,
203,
3639,
1731,
1578,
2461,
6581,
273,
417,
24410,
581,
5034,
12,
203,
5411,
24126,
18,
3015,
12,
203,
7734,
27025,
67,
2399,
15920,
16,
203,
7734,
417,
24410,
581,
5034,
12,
3890,
12,
529,
10756,
3631,
203,
7734,
30170,
548,
9334,
203,
7734,
1758,
12,
2211,
13,
203,
5411,
262,
203,
3639,
11272,
203,
203,
3639,
1731,
1578,
1958,
2310,
273,
417,
24410,
581,
5034,
12,
203,
5411,
24126,
18,
3015,
12,
203,
7734,
2030,
19384,
2689,
67,
2399,
15920,
16,
203,
7734,
7152,
73,
16,
203,
7734,
7448,
16,
203,
7734,
10839,
203,
5411,
262,
203,
3639,
11272,
203,
203,
3639,
1731,
1578,
5403,
273,
417,
24410,
581,
5034,
12,
203,
5411,
24126,
18,
3015,
4420,
329,
12,
203,
7734,
1548,
92,
3657,
64,
92,
1611,
3113,
203,
7734,
2461,
6581,
16,
203,
7734,
1958,
2310,
203,
5411,
262,
203,
3639,
11272,
203,
203,
3639,
1758,
1573,
8452,
273,
425,
1793,
3165,
12,
10171,
16,
331,
16,
436,
16,
272,
1769,
203,
3639,
2583,
12,
2977,
8452,
480,
1758,
12,
20,
3631,
315,
58,
1157,
45,
2866,
22216,
858,
8267,
30,
2057,
3372,
8863,
203,
3639,
2583,
12,
12824,
422,
1661,
764,
63,
2977,
8452,
3737,
15,
16,
315,
58,
1157,
45,
2866,
22216,
2
]
|
pragma solidity ^0.4.13;
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract 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 SealTokenSale is Pausable {
using SafeMath for uint256;
/**
* @dev Supporter struct to allow tracking supporters KYC status and referrer address
*/
struct Supporter {
bool hasKYC;
address referrerAddress;
}
/**
* @dev External Supporter struct to allow tracking reserved amounts by supporter
*/
struct ExternalSupporter {
uint256 reservedAmount;
}
/**
* @dev Token Sale States
*/
enum TokenSaleState {Private, Pre, Main, Finished}
// Variables
mapping(address => Supporter) public supportersMap; // Mapping with all the Token Sale participants (Private excluded)
mapping(address => ExternalSupporter) public externalSupportersMap; // Mapping with external supporters
SealToken public token; // ERC20 Token contract address
address public vaultWallet; // Wallet address to which ETH and Company Reserve Tokens get forwarded
address public airdropWallet; // Wallet address to which Unsold Tokens get forwarded
address public kycWallet; // Wallet address for the KYC server
uint256 public tokensSold; // How many tokens have been sold
uint256 public tokensReserved; // How many tokens have been reserved
uint256 public maxTxGasPrice; // Maximum transaction gas price allowed for fair-chance transactions
TokenSaleState public currentState; // current Sale state
uint256 public constant ONE_MILLION = 10 ** 6; // One million for token cap calculation reference
uint256 public constant PRE_SALE_TOKEN_CAP = 384 * ONE_MILLION * 10 ** 18; // Maximum amount that can be sold during the Pre Sale period
uint256 public constant TOKEN_SALE_CAP = 492 * ONE_MILLION * 10 ** 18; // Maximum amount of tokens that can be sold by this contract
uint256 public constant TOTAL_TOKENS_SUPPLY = 1200 * ONE_MILLION * 10 ** 18; // Total supply that will be minted
uint256 public constant MIN_ETHER = 0.1 ether; // Minimum ETH Contribution allowed during the crowd sale
/* Minimum PreSale Contributions in Ether */
uint256 public constant PRE_SALE_MIN_ETHER = 1 ether; // Minimum to get 10% Bonus Tokens
uint256 public constant PRE_SALE_15_BONUS_MIN = 60 ether; // Minimum to get 15% Bonus Tokens
uint256 public constant PRE_SALE_20_BONUS_MIN = 300 ether; // Minimum to get 20% Bonus Tokens
uint256 public constant PRE_SALE_30_BONUS_MIN = 1200 ether; // Minimum to get 30% Bonus Tokens
/* Rate */
uint256 public tokenBaseRate; // Base rate
uint256 public referrerBonusRate; // Referrer Bonus Rate with 2 decimals (250 for 2.5% bonus for example)
uint256 public referredBonusRate; // Referred Bonus Rate with 2 decimals (250 for 2.5% bonus for example)
/**
* @dev Modifier to only allow Owner or KYC Wallet to execute a function
*/
modifier onlyOwnerOrKYCWallet() {
require(msg.sender == owner || msg.sender == kycWallet);
_;
}
/**
* Event for token purchase logging
* @param purchaser The wallet address that bought the tokens
* @param value How many Weis were paid for the purchase
* @param amount The amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount);
/**
* Event for token reservation
* @param wallet The beneficiary wallet address
* @param amount The amount of tokens
*/
event TokenReservation(address indexed wallet, uint256 amount);
/**
* Event for token reservation confirmation
* @param wallet The beneficiary wallet address
* @param amount The amount of tokens
*/
event TokenReservationConfirmation(address indexed wallet, uint256 amount);
/**
* Event for token reservation cancellation
* @param wallet The beneficiary wallet address
* @param amount The amount of tokens
*/
event TokenReservationCancellation(address indexed wallet, uint256 amount);
/**
* Event for kyc status change logging
* @param user User address
* @param isApproved KYC approval state
*/
event KYC(address indexed user, bool isApproved);
/**
* Event for referrer set
* @param user User address
* @param referrerAddress Referrer address
*/
event ReferrerSet(address indexed user, address indexed referrerAddress);
/**
* Event for referral bonus incomplete
* @param userAddress User address
* @param missingAmount Missing Amount
*/
event ReferralBonusIncomplete(address indexed userAddress, uint256 missingAmount);
/**
* Event for referral bonus minted
* @param userAddress User address
* @param amount Amount minted
*/
event ReferralBonusMinted(address indexed userAddress, uint256 amount);
/**
* Constructor
* @param _vaultWallet Vault address
* @param _airdropWallet Airdrop wallet address
* @param _kycWallet KYC address
* @param _tokenBaseRate Token Base rate (Tokens/ETH)
* @param _referrerBonusRate Referrer Bonus rate (2 decimals, ex 250 for 2.5%)
* @param _referredBonusRate Referred Bonus rate (2 decimals, ex 250 for 2.5%)
* @param _maxTxGasPrice Maximum gas price allowed when buying tokens
*/
function SealTokenSale(
address _vaultWallet,
address _airdropWallet,
address _kycWallet,
uint256 _tokenBaseRate,
uint256 _referrerBonusRate,
uint256 _referredBonusRate,
uint256 _maxTxGasPrice
)
public
{
require(_vaultWallet != address(0));
require(_airdropWallet != address(0));
require(_kycWallet != address(0));
require(_tokenBaseRate > 0);
require(_referrerBonusRate > 0);
require(_referredBonusRate > 0);
require(_maxTxGasPrice > 0);
vaultWallet = _vaultWallet;
airdropWallet = _airdropWallet;
kycWallet = _kycWallet;
tokenBaseRate = _tokenBaseRate;
referrerBonusRate = _referrerBonusRate;
referredBonusRate = _referredBonusRate;
maxTxGasPrice = _maxTxGasPrice;
tokensSold = 0;
tokensReserved = 0;
token = new SealToken();
// init sale state;
currentState = TokenSaleState.Private;
}
/* fallback function can be used to buy tokens */
function() public payable {
buyTokens();
}
/* low level token purchase function */
function buyTokens() public payable whenNotPaused {
// Do not allow if gasprice is bigger than the maximum
// This is for fair-chance for all contributors, so no one can
// set a too-high transaction price and be able to buy earlier
require(tx.gasprice <= maxTxGasPrice);
// make sure we're in pre or main sale period
require(isPublicTokenSaleRunning());
// check if KYC ok
require(userHasKYC(msg.sender));
// check user is sending enough Wei for the stage's rules
require(aboveMinimumPurchase());
address sender = msg.sender;
uint256 weiAmountSent = msg.value;
// calculate token amount
uint256 bonusMultiplier = getBonusMultiplier(weiAmountSent);
uint256 newTokens = weiAmountSent.mul(tokenBaseRate).mul(bonusMultiplier).div(100);
// check totals and mint the tokens
checkTotalsAndMintTokens(sender, newTokens, false);
// Log Event
TokenPurchase(sender, weiAmountSent, newTokens);
// forward the funds to the vault wallet
vaultWallet.transfer(msg.value);
}
/**
* @dev Reserve Tokens
* @param _wallet Destination Address
* @param _amount Amount of tokens
*/
function reserveTokens(address _wallet, uint256 _amount) public onlyOwner {
// check amount positive
require(_amount > 0);
// check destination address not null
require(_wallet != address(0));
// make sure that we're in private sale or presale
require(isPrivateSaleRunning() || isPreSaleRunning());
// check cap
uint256 totalTokensReserved = tokensReserved.add(_amount);
require(tokensSold + totalTokensReserved <= PRE_SALE_TOKEN_CAP);
// update total reserved
tokensReserved = totalTokensReserved;
// save user reservation
externalSupportersMap[_wallet].reservedAmount = externalSupportersMap[_wallet].reservedAmount.add(_amount);
// Log Event
TokenReservation(_wallet, _amount);
}
/**
* @dev Confirm Reserved Tokens
* @param _wallet Destination Address
* @param _amount Amount of tokens
*/
function confirmReservedTokens(address _wallet, uint256 _amount) public onlyOwner {
// check amount positive
require(_amount > 0);
// check destination address not null
require(_wallet != address(0));
// make sure the sale hasn't ended yet
require(!hasEnded());
// check amount not more than reserved
require(_amount <= externalSupportersMap[_wallet].reservedAmount);
// check totals and mint the tokens
checkTotalsAndMintTokens(_wallet, _amount, true);
// Log Event
TokenReservationConfirmation(_wallet, _amount);
}
/**
* @dev Cancel Reserved Tokens
* @param _wallet Destination Address
* @param _amount Amount of tokens
*/
function cancelReservedTokens(address _wallet, uint256 _amount) public onlyOwner {
// check amount positive
require(_amount > 0);
// check destination address not null
require(_wallet != address(0));
// make sure the sale hasn't ended yet
require(!hasEnded());
// check amount not more than reserved
require(_amount <= externalSupportersMap[_wallet].reservedAmount);
// update total reserved
tokensReserved = tokensReserved.sub(_amount);
// update user reservation
externalSupportersMap[_wallet].reservedAmount = externalSupportersMap[_wallet].reservedAmount.sub(_amount);
// Log Event
TokenReservationCancellation(_wallet, _amount);
}
/**
* @dev Check totals and Mint tokens
* @param _wallet Destination Address
* @param _amount Amount of tokens
*/
function checkTotalsAndMintTokens(address _wallet, uint256 _amount, bool _fromReservation) private {
// check that we have not yet reached the cap
uint256 totalTokensSold = tokensSold.add(_amount);
uint256 totalTokensReserved = tokensReserved;
if (_fromReservation) {
totalTokensReserved = totalTokensReserved.sub(_amount);
}
if (isMainSaleRunning()) {
require(totalTokensSold + totalTokensReserved <= TOKEN_SALE_CAP);
} else {
require(totalTokensSold + totalTokensReserved <= PRE_SALE_TOKEN_CAP);
}
// update contract state
tokensSold = totalTokensSold;
if (_fromReservation) {
externalSupportersMap[_wallet].reservedAmount = externalSupportersMap[_wallet].reservedAmount.sub(_amount);
tokensReserved = totalTokensReserved;
}
// mint the tokens
token.mint(_wallet, _amount);
address userReferrer = getUserReferrer(_wallet);
if (userReferrer != address(0)) {
// Mint Referrer bonus
mintReferralShare(_amount, userReferrer, referrerBonusRate);
// Mint Referred bonus
mintReferralShare(_amount, _wallet, referredBonusRate);
}
}
/**
* @dev Mint Referral Share
* @param _amount Amount of tokens
* @param _userAddress User Address
* @param _bonusRate Bonus rate (2 decimals)
*/
function mintReferralShare(uint256 _amount, address _userAddress, uint256 _bonusRate) private {
// calculate max tokens available
uint256 currentCap;
if (isMainSaleRunning()) {
currentCap = TOKEN_SALE_CAP;
} else {
currentCap = PRE_SALE_TOKEN_CAP;
}
uint256 maxTokensAvailable = currentCap - tokensSold - tokensReserved;
// check if we have enough tokens
uint256 fullShare = _amount.mul(_bonusRate).div(10000);
if (fullShare <= maxTokensAvailable) {
// mint the tokens
token.mint(_userAddress, fullShare);
// update state
tokensSold = tokensSold.add(fullShare);
// log event
ReferralBonusMinted(_userAddress, fullShare);
}
else {
// mint the available tokens
token.mint(_userAddress, maxTokensAvailable);
// update state
tokensSold = tokensSold.add(maxTokensAvailable);
// log events
ReferralBonusMinted(_userAddress, maxTokensAvailable);
ReferralBonusIncomplete(_userAddress, fullShare - maxTokensAvailable);
}
}
/**
* @dev Start Presale
*/
function startPreSale() public onlyOwner {
// make sure we're in the private sale state
require(currentState == TokenSaleState.Private);
// move to presale
currentState = TokenSaleState.Pre;
}
/**
* @dev Go back to private sale
*/
function goBackToPrivateSale() public onlyOwner {
// make sure we're in the pre sale
require(currentState == TokenSaleState.Pre);
// go back to private
currentState = TokenSaleState.Private;
}
/**
* @dev Start Main sale
*/
function startMainSale() public onlyOwner {
// make sure we're in the presale state
require(currentState == TokenSaleState.Pre);
// move to main sale
currentState = TokenSaleState.Main;
}
/**
* @dev Go back to Presale
*/
function goBackToPreSale() public onlyOwner {
// make sure we're in the main sale
require(currentState == TokenSaleState.Main);
// go back to presale
currentState = TokenSaleState.Pre;
}
/**
* @dev Ends the operation of the contract
*/
function finishContract() public onlyOwner {
// make sure we're in the main sale
require(currentState == TokenSaleState.Main);
// make sure there are no pending reservations
require(tokensReserved == 0);
// mark sale as finished
currentState = TokenSaleState.Finished;
// send the unsold tokens to the airdrop wallet
uint256 unsoldTokens = TOKEN_SALE_CAP.sub(tokensSold);
token.mint(airdropWallet, unsoldTokens);
// send the company reserve tokens to the vault wallet
uint256 notForSaleTokens = TOTAL_TOKENS_SUPPLY.sub(TOKEN_SALE_CAP);
token.mint(vaultWallet, notForSaleTokens);
// finish the minting of the token, so that transfers are allowed
token.finishMinting();
// transfer ownership of the token contract to the owner,
// so it isn't locked to be a child of the crowd sale contract
token.transferOwnership(owner);
}
/**
* @dev Updates the maximum allowed gas price that can be used when calling buyTokens()
* @param _newMaxTxGasPrice The new maximum gas price
*/
function updateMaxTxGasPrice(uint256 _newMaxTxGasPrice) public onlyOwner {
require(_newMaxTxGasPrice > 0);
maxTxGasPrice = _newMaxTxGasPrice;
}
/**
* @dev Updates the token baserate
* @param _tokenBaseRate The new token baserate in tokens/eth
*/
function updateTokenBaseRate(uint256 _tokenBaseRate) public onlyOwner {
require(_tokenBaseRate > 0);
tokenBaseRate = _tokenBaseRate;
}
/**
* @dev Updates the Vault Wallet address
* @param _vaultWallet The new vault wallet
*/
function updateVaultWallet(address _vaultWallet) public onlyOwner {
require(_vaultWallet != address(0));
vaultWallet = _vaultWallet;
}
/**
* @dev Updates the KYC Wallet address
* @param _kycWallet The new kyc wallet
*/
function updateKYCWallet(address _kycWallet) public onlyOwner {
require(_kycWallet != address(0));
kycWallet = _kycWallet;
}
/**
* @dev Approve user's KYC
* @param _user User Address
*/
function approveUserKYC(address _user) onlyOwnerOrKYCWallet public {
require(_user != address(0));
Supporter storage sup = supportersMap[_user];
sup.hasKYC = true;
KYC(_user, true);
}
/**
* @dev Disapprove user's KYC
* @param _user User Address
*/
function disapproveUserKYC(address _user) onlyOwnerOrKYCWallet public {
require(_user != address(0));
Supporter storage sup = supportersMap[_user];
sup.hasKYC = false;
KYC(_user, false);
}
/**
* @dev Approve user's KYC and sets referrer
* @param _user User Address
* @param _referrerAddress Referrer Address
*/
function approveUserKYCAndSetReferrer(address _user, address _referrerAddress) onlyOwnerOrKYCWallet public {
require(_user != address(0));
Supporter storage sup = supportersMap[_user];
sup.hasKYC = true;
sup.referrerAddress = _referrerAddress;
// log events
KYC(_user, true);
ReferrerSet(_user, _referrerAddress);
}
/**
* @dev check if private sale is running
*/
function isPrivateSaleRunning() public view returns (bool) {
return (currentState == TokenSaleState.Private);
}
/**
* @dev check if pre sale or main sale are running
*/
function isPublicTokenSaleRunning() public view returns (bool) {
return (isPreSaleRunning() || isMainSaleRunning());
}
/**
* @dev check if pre sale is running
*/
function isPreSaleRunning() public view returns (bool) {
return (currentState == TokenSaleState.Pre);
}
/**
* @dev check if main sale is running
*/
function isMainSaleRunning() public view returns (bool) {
return (currentState == TokenSaleState.Main);
}
/**
* @dev check if sale has ended
*/
function hasEnded() public view returns (bool) {
return (currentState == TokenSaleState.Finished);
}
/**
* @dev Check if user has passed KYC
* @param _user User Address
*/
function userHasKYC(address _user) public view returns (bool) {
return supportersMap[_user].hasKYC;
}
/**
* @dev Get User's referrer address
* @param _user User Address
*/
function getUserReferrer(address _user) public view returns (address) {
return supportersMap[_user].referrerAddress;
}
/**
* @dev Get User's reserved amount
* @param _user User Address
*/
function getReservedAmount(address _user) public view returns (uint256) {
return externalSupportersMap[_user].reservedAmount;
}
/**
* @dev Returns the bonus multiplier to calculate the purchase rate
* @param _weiAmount Purchase amount
*/
function getBonusMultiplier(uint256 _weiAmount) internal view returns (uint256) {
if (isMainSaleRunning()) {
return 100;
}
else if (isPreSaleRunning()) {
if (_weiAmount >= PRE_SALE_30_BONUS_MIN) {
// 30% bonus
return 130;
}
else if (_weiAmount >= PRE_SALE_20_BONUS_MIN) {
// 20% bonus
return 120;
}
else if (_weiAmount >= PRE_SALE_15_BONUS_MIN) {
// 15% bonus
return 115;
}
else if (_weiAmount >= PRE_SALE_MIN_ETHER) {
// 10% bonus
return 110;
}
else {
// Safeguard but this should never happen as aboveMinimumPurchase checks the minimum
revert();
}
}
}
/**
* @dev Check if the user is buying above the required minimum
*/
function aboveMinimumPurchase() internal view returns (bool) {
if (isMainSaleRunning()) {
return msg.value >= MIN_ETHER;
}
else if (isPreSaleRunning()) {
return msg.value >= PRE_SALE_MIN_ETHER;
} else {
return false;
}
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract SealToken is MintableToken {
// Constants
string public constant name = "SealToken";
string public constant symbol = "SEAL";
uint8 public constant decimals = 18;
/**
* @dev Modifier to only allow transfers after the minting has been done
*/
modifier onlyWhenTransferEnabled() {
require(mintingFinished);
_;
}
modifier validDestination(address _to) {
require(_to != address(0x0));
require(_to != address(this));
_;
}
function SealToken() public {
}
function transferFrom(address _from, address _to, uint256 _value) public
onlyWhenTransferEnabled
validDestination(_to)
returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public
onlyWhenTransferEnabled
returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval (address _spender, uint _addedValue) public
onlyWhenTransferEnabled
returns (bool) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval (address _spender, uint _subtractedValue) public
onlyWhenTransferEnabled
returns (bool) {
return super.decreaseApproval(_spender, _subtractedValue);
}
function transfer(address _to, uint256 _value) public
onlyWhenTransferEnabled
validDestination(_to)
returns (bool) {
return super.transfer(_to, _value);
}
} | Wallet address to which Unsold Tokens get forwarded
| address public airdropWallet; | 5,841,199 | [
1,
16936,
1758,
358,
1492,
1351,
87,
1673,
13899,
336,
19683,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
1758,
1071,
279,
6909,
1764,
16936,
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
]
|
./full_match/11155111/0x17825fBc4B9EBaE7351BB266558B7264D2f7Ea0c/sources/NFTLootBox.sol | Buy an NFT that is listed for sale Transfer the payment to the seller Transfer ownership of the NFT to the buyer Remove the NFT from sale | function buyForSale(uint256 tokenId) external payable {
require(_exists(tokenId), "Token does not exist");
require(_nfts[tokenId].listedForSale, "NFT not listed for sale");
require(msg.value == _nfts[tokenId].salePrice, "Incorrect payment");
address ownerAddress = ownerOf(tokenId);
address payable sellerAddress = payable(ownerAddress);
sellerAddress.transfer(msg.value);
_transfer(ownerAddress, msg.sender, tokenId);
_nfts[tokenId].listedForSale = false;
_nfts[tokenId].salePrice = 0;
}
| 3,823,071 | [
1,
38,
9835,
392,
423,
4464,
716,
353,
12889,
364,
272,
5349,
12279,
326,
5184,
358,
326,
29804,
12279,
23178,
434,
326,
423,
4464,
358,
326,
27037,
3581,
326,
423,
4464,
628,
272,
5349,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
30143,
1290,
30746,
12,
11890,
5034,
1147,
548,
13,
3903,
8843,
429,
288,
203,
3639,
2583,
24899,
1808,
12,
2316,
548,
3631,
315,
1345,
1552,
486,
1005,
8863,
203,
3639,
2583,
24899,
82,
1222,
87,
63,
2316,
548,
8009,
18647,
1290,
30746,
16,
315,
50,
4464,
486,
12889,
364,
272,
5349,
8863,
203,
3639,
2583,
12,
3576,
18,
1132,
422,
389,
82,
1222,
87,
63,
2316,
548,
8009,
87,
5349,
5147,
16,
315,
16268,
5184,
8863,
203,
203,
3639,
1758,
3410,
1887,
273,
3410,
951,
12,
2316,
548,
1769,
203,
3639,
1758,
8843,
429,
29804,
1887,
273,
8843,
429,
12,
8443,
1887,
1769,
203,
203,
3639,
29804,
1887,
18,
13866,
12,
3576,
18,
1132,
1769,
203,
203,
3639,
389,
13866,
12,
8443,
1887,
16,
1234,
18,
15330,
16,
1147,
548,
1769,
203,
203,
3639,
389,
82,
1222,
87,
63,
2316,
548,
8009,
18647,
1290,
30746,
273,
629,
31,
203,
3639,
389,
82,
1222,
87,
63,
2316,
548,
8009,
87,
5349,
5147,
273,
374,
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
]
|
/**
*Submitted for verification at Etherscan.io on 2021-08-27
*/
// Sources flattened with hardhat v2.5.0 https://hardhat.org
// File @openzeppelin/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
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/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
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/[email protected]
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);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length)
internal
pure
returns (string memory)
{
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
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/[email protected]
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(to).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 contracts/core/NFTeacket.sol
pragma solidity ^0.8.4;
contract NFTeacket is ERC721 {
enum TicketType {
Maker,
Taker
}
enum OptionType {
CallBuy,
CallSale,
PutBuy,
PutSale
}
struct OptionDataMaker {
uint256 price; // The price of the option
uint256 strike; // The strike price of the option
uint256 settlementTimestamp; // The maturity timestamp of the option
uint256 takerTicketId; // The taker ticket ID of this order
uint256 nftId; // The nft token ID of the option
address nftContract; // The smart contract address of the nft
OptionType optionType; // Type of the option
}
struct OptionDataTaker {
uint256 makerTicketId;
}
/// @dev The NFTea contract
address public nftea;
/// @dev Token ids to ticket type
mapping(uint256 => TicketType) _ticketIdToType;
/// @dev Token ids to OptionDataMaker
mapping(uint256 => OptionDataMaker) private _ticketIdToOptionDataMaker;
/// @dev Token ids to OptionDataTaker
mapping(uint256 => OptionDataTaker) private _ticketIdToOptionDataTaker;
/// @dev The current nft counter to get next available id
uint256 private _counter;
modifier onylyFromNFTea() {
require(msg.sender == nftea, "NFTeacket: not called from nftea");
_;
}
constructor(address _nftea) ERC721("NFTeacket", "NBOT") {
nftea = _nftea;
}
/// @notice Mint a maker ticket NFT associated with the given option offer
/// @param to adress to mint a ticket to
/// @param data option data to store in the ticket
function mintMakerTicket(address to, OptionDataMaker memory data)
external
onylyFromNFTea
returns (uint256 ticketId)
{
ticketId = _counter++;
_safeMint(to, ticketId);
_ticketIdToOptionDataMaker[ticketId] = data;
_ticketIdToType[ticketId] = TicketType.Maker;
}
/// @notice Mint a taker ticket NFT associated with the given option offer
/// @param to adress to mint a ticket to
/// @param data option data to store in the ticket
/// @dev No need to check that the maker icket referenced in the data params
/// actually exists since it's already ensure in the NFTea caller contract
function mintTakerTicket(address to, OptionDataTaker memory data)
public
onylyFromNFTea
returns (uint256 ticketId)
{
ticketId = _counter++;
_safeMint(to, ticketId);
_ticketIdToOptionDataTaker[ticketId] = data;
_ticketIdToType[ticketId] = TicketType.Taker;
}
/// @notice Return if the ticker is a Maker or a Taker
/// @param ticketId the ticket id
function ticketIdToType(uint256 ticketId) public view returns (TicketType) {
require(_exists(ticketId), "NFTeacket: ticket does not exist");
return _ticketIdToType[ticketId];
}
/// @notice return the maker option data associated with the ticket
/// @param ticketId the ticket id
function ticketIdToOptionDataMaker(uint256 ticketId)
external
view
returns (OptionDataMaker memory)
{
require(
ticketIdToType(ticketId) == TicketType.Maker,
"NFTeacket: Not a maker ticket"
);
return _ticketIdToOptionDataMaker[ticketId];
}
/// @notice return the taker option data associated with the ticket
/// @param ticketId the ticket id
function ticketIdToOptionDataTaker(uint256 ticketId)
external
view
returns (OptionDataTaker memory)
{
require(
ticketIdToType(ticketId) == TicketType.Taker,
"NFTeacket: Not a taker ticket"
);
return _ticketIdToOptionDataTaker[ticketId];
}
/// @notice Link the maker ticket with the tacker ticket
/// @param makerTicketId the maker ticket id
/// @param takerTicketId the taker ticket id
/// @dev No need to check that the maker and taker tickets exists since it's already ensure
/// on the NFTea caller contract
function linkMakerToTakerTicket(
uint256 makerTicketId,
uint256 takerTicketId
) external onylyFromNFTea {
_ticketIdToOptionDataMaker[makerTicketId].takerTicketId = takerTicketId;
}
/// @notice Burn the ticket
/// @param ticketId the ticket id
function burnTicket(uint256 ticketId) external onylyFromNFTea {
this.ticketIdToType(ticketId) == TicketType.Maker
? delete _ticketIdToOptionDataMaker[ticketId]
: delete _ticketIdToOptionDataTaker[ticketId];
delete _ticketIdToType[ticketId];
_burn(ticketId);
}
}
// File contracts/core/NFTea.sol
pragma solidity ^0.8.4;
contract NFTea {
event OrderCreated(uint256 makerTicketId, NFTeacket.OptionDataMaker data);
event OrderCancelled(uint256 makerTicketId);
event OrderFilled(uint256 takerTicketId, NFTeacket.OptionDataTaker data);
event OptionUsed(uint256 makerTicketId, bool value);
address public admin;
address public nfteacket;
uint256 public maxDelayToClaim;
uint256 public optionFees;
uint256 public saleFees;
modifier onlyAdmin() {
require(msg.sender == admin, "NFTea: not admin");
_;
}
modifier onlyWhenNFTeacketSet() {
require(nfteacket != address(0), "NFTea: nfteacket not set");
_;
}
constructor() {
admin = msg.sender;
optionFees = 3;
saleFees = 1;
maxDelayToClaim = 1 days;
}
function changeAdmin(address _admin) external onlyAdmin {
admin = _admin;
}
function setMaxDelayToClaim(uint256 delay) external onlyAdmin {
maxDelayToClaim = delay;
}
function setOptionFees(uint256 fee) external onlyAdmin {
require(fee < 100, "NFTea: incorret fee value");
optionFees = fee;
}
function setSaleFees(uint256 fee) external onlyAdmin {
require(fee < 100, "NFTea: incorret fee value");
saleFees = fee;
}
function collectFees() external onlyAdmin {
_transferEth(msg.sender, address(this).balance);
}
function setNFTeacket(address _nfteacket) external onlyAdmin {
nfteacket = _nfteacket;
}
/// @notice Create an option order for a given NFT
/// @param optionPrice the price of the option
/// @param strikePrice the strike price of the option
/// @param settlementTimestamp the option maturity timestamp
/// @param nftId the token ID of the NFT relevant of this order
/// @param nftContract the address of the NFT contract
/// @param optionType the type of the option (CallBuy, CallSale, PutBuy or PutSale)
function makeOrder(
uint256 optionPrice,
uint256 strikePrice,
uint256 settlementTimestamp,
uint256 nftId,
address nftContract,
NFTeacket.OptionType optionType
) external payable onlyWhenNFTeacketSet {
require(
settlementTimestamp > block.timestamp,
"NFTea: Incorrect timestamp"
);
if (optionType == NFTeacket.OptionType.CallBuy) {
_requireEthSent(optionPrice);
} else if (optionType == NFTeacket.OptionType.CallSale) {
_requireEthSent(0);
_lockNft(nftId, nftContract);
} else if (optionType == NFTeacket.OptionType.PutBuy) {
_requireEthSent(optionPrice);
} else {
// OptionType.Putsale
_requireEthSent(strikePrice);
}
NFTeacket.OptionDataMaker memory data = NFTeacket.OptionDataMaker({
price: optionPrice,
strike: strikePrice,
settlementTimestamp: settlementTimestamp,
nftId: nftId,
nftContract: nftContract,
takerTicketId: 0,
optionType: optionType
});
uint256 makerTicketId = NFTeacket(nfteacket).mintMakerTicket(
msg.sender,
data
);
emit OrderCreated(makerTicketId, data);
}
/// @notice Cancel a non filled order
/// @param makerTicketId the ticket ID associated with the order
function cancelOrder(uint256 makerTicketId) external onlyWhenNFTeacketSet {
NFTeacket _nfteacket = NFTeacket(nfteacket);
// Check the seender is the maker
_requireTicketOwner(msg.sender, makerTicketId);
NFTeacket.OptionDataMaker memory optionData = _nfteacket
.ticketIdToOptionDataMaker(makerTicketId);
require(optionData.takerTicketId == 0, "NFTea: Order already filled");
if (optionData.optionType == NFTeacket.OptionType.CallBuy) {
_transferEth(msg.sender, optionData.price);
} else if (optionData.optionType == NFTeacket.OptionType.CallSale) {
_transferNft(
address(this),
msg.sender,
optionData.nftId,
optionData.nftContract
);
} else if (optionData.optionType == NFTeacket.OptionType.PutBuy) {
_transferEth(msg.sender, optionData.price);
} else {
// OptionType.Putsale
_transferEth(msg.sender, optionData.strike);
}
_nfteacket.burnTicket(makerTicketId);
emit OrderCancelled(makerTicketId);
}
/// @notice Fill a given option order
/// @param makerTicketId the corresponding order identified by its ticket ID
function fillOrder(uint256 makerTicketId)
external
payable
onlyWhenNFTeacketSet
{
NFTeacket _nfteacket = NFTeacket(nfteacket);
NFTeacket.OptionDataMaker memory optionData = _nfteacket
.ticketIdToOptionDataMaker(makerTicketId);
uint256 optionPriceSubFees = (optionData.price * (100 - optionFees)) /
100;
require(
block.timestamp < optionData.settlementTimestamp,
"NFTea: Obsolete order"
);
require(optionData.takerTicketId == 0, "NFTea: Order already filled");
if (optionData.optionType == NFTeacket.OptionType.CallBuy) {
_requireEthSent(0);
_lockNft(optionData.nftId, optionData.nftContract);
// Pay the taker for selling the call to the maker
_transferEth(msg.sender, optionPriceSubFees);
} else if (optionData.optionType == NFTeacket.OptionType.CallSale) {
_requireEthSent(optionData.price);
// Pay the maker for selling the call to the taker
address maker = _nfteacket.ownerOf(makerTicketId);
_transferEth(maker, optionPriceSubFees);
} else if (optionData.optionType == NFTeacket.OptionType.PutBuy) {
_requireEthSent(optionData.strike);
// Pay the taker for selling the put to the maker
_transferEth(msg.sender, optionPriceSubFees);
} else {
// OptionType.Putsale
_requireEthSent(optionData.price);
// Pay the maker for selling the put to the taker
address maker = _nfteacket.ownerOf(makerTicketId);
_transferEth(maker, optionPriceSubFees);
}
NFTeacket.OptionDataTaker memory data = NFTeacket.OptionDataTaker({
makerTicketId: makerTicketId
});
uint256 takerTicketId = _nfteacket.mintTakerTicket(msg.sender, data);
_nfteacket.linkMakerToTakerTicket(makerTicketId, takerTicketId);
emit OrderFilled(takerTicketId, data);
}
/// @notice Allow a buyer to use his right to either buy or sale at the registered strike price
/// @param ticketId The buyer ticket
function useBuyerRightAtMaturity(uint256 ticketId)
external
payable
onlyWhenNFTeacketSet
{
NFTeacket _nfteacket = NFTeacket(nfteacket);
_requireTicketOwner(msg.sender, ticketId);
NFTeacket.OptionDataMaker memory makerOptionData;
uint256 makerTicketId;
address ethReceiver;
address nftReceiver;
address nftSender;
// Get the ticket type
NFTeacket.TicketType ticketType = _nfteacket.ticketIdToType(ticketId);
// If buyer is the maker
if (ticketType == NFTeacket.TicketType.Maker) {
makerOptionData = _nfteacket.ticketIdToOptionDataMaker(ticketId);
makerTicketId = ticketId;
address taker = _nfteacket.ownerOf(makerOptionData.takerTicketId);
if (makerOptionData.optionType == NFTeacket.OptionType.CallBuy) {
// When using call buy right, msg.value must be the strike price
_requireEthSent(makerOptionData.strike);
ethReceiver = taker;
nftSender = address(this);
nftReceiver = msg.sender;
} else if (
makerOptionData.optionType == NFTeacket.OptionType.PutBuy
) {
// When using put buy right, msg.value must be 0
_requireEthSent(0);
ethReceiver = msg.sender;
nftSender = msg.sender;
nftReceiver = taker;
} else {
revert("NFTea: Not a buyer");
}
} else {
// If buyer is the taker
NFTeacket.OptionDataTaker memory takerOptionData = _nfteacket
.ticketIdToOptionDataTaker(ticketId);
makerOptionData = _nfteacket.ticketIdToOptionDataMaker(
takerOptionData.makerTicketId
);
makerTicketId = takerOptionData.makerTicketId;
address maker = _nfteacket.ownerOf(takerOptionData.makerTicketId);
if (makerOptionData.optionType == NFTeacket.OptionType.CallSale) {
// When using call buy right, msg.value must be the strike price
_requireEthSent(makerOptionData.strike);
ethReceiver = maker;
nftSender = address(this);
nftReceiver = msg.sender;
} else if (
makerOptionData.optionType == NFTeacket.OptionType.PutSale
) {
// When using put buy right, msg.value must be 0
_requireEthSent(0);
ethReceiver = msg.sender;
nftSender = msg.sender;
nftReceiver = maker;
} else {
revert("NFTea: Not a buyer");
}
}
// Ensure we are at timestamp such that settlement <= timestamp < settlement + maxDelayToClaim
require(
block.timestamp >= makerOptionData.settlementTimestamp &&
block.timestamp <
makerOptionData.settlementTimestamp + maxDelayToClaim,
"NFTea: Can't use buyer right"
);
uint256 strikePriceSubFees = (makerOptionData.strike *
(100 - saleFees)) / 100;
// Swap NFT with ETH
_transferEth(ethReceiver, strikePriceSubFees);
_transferNft(
nftSender,
nftReceiver,
makerOptionData.nftId,
makerOptionData.nftContract
);
// Burn maker and taker tickets
_nfteacket.burnTicket(makerTicketId);
_nfteacket.burnTicket(makerOptionData.takerTicketId);
emit OptionUsed(makerTicketId, true);
}
/// @notice Allow a seller to withdraw his locked collateral at maturity
/// @param ticketId The seller ticket
function withdrawLockedCollateralAtMaturity(uint256 ticketId)
external
onlyWhenNFTeacketSet
{
NFTeacket _nfteacket = NFTeacket(nfteacket);
_requireTicketOwner(msg.sender, ticketId);
NFTeacket.TicketType ticketType = _nfteacket.ticketIdToType(ticketId);
NFTeacket.OptionDataMaker memory makerOptionData;
uint256 makerTicketId;
bool withdrawSucceed;
// If seller is the maker
if (ticketType == NFTeacket.TicketType.Maker) {
makerOptionData = _nfteacket.ticketIdToOptionDataMaker(ticketId);
makerTicketId = ticketId;
// Ensure we are at timestamp >= settlement + maxDelayToClaim
require(
block.timestamp >=
makerOptionData.settlementTimestamp + maxDelayToClaim,
"NFTea: Can't withdraw collateral now"
);
if (makerOptionData.optionType == NFTeacket.OptionType.CallSale) {
_transferNft(
address(this),
msg.sender,
makerOptionData.nftId,
makerOptionData.nftContract
);
withdrawSucceed = true;
} else if (
makerOptionData.optionType == NFTeacket.OptionType.PutSale
) {
_transferEth(msg.sender, makerOptionData.strike);
withdrawSucceed = true;
} else {
withdrawSucceed = false;
}
} else {
// If seller is the taker
NFTeacket.OptionDataTaker memory takerOptionData = _nfteacket
.ticketIdToOptionDataTaker(ticketId);
makerOptionData = _nfteacket.ticketIdToOptionDataMaker(
takerOptionData.makerTicketId
);
makerTicketId = takerOptionData.makerTicketId;
// Ensure we are at timestamp >= settlement + maxDelayToClaim
require(
block.timestamp >=
makerOptionData.settlementTimestamp + maxDelayToClaim,
"NFTea: Can't withdraw collateral now"
);
if (makerOptionData.optionType == NFTeacket.OptionType.CallBuy) {
_transferNft(
address(this),
msg.sender,
makerOptionData.nftId,
makerOptionData.nftContract
);
withdrawSucceed = true;
} else if (
makerOptionData.optionType == NFTeacket.OptionType.PutBuy
) {
_transferEth(msg.sender, makerOptionData.strike);
withdrawSucceed = true;
} else {
withdrawSucceed = false;
}
}
if (withdrawSucceed) {
// Burn maker and taker tickets
_nfteacket.burnTicket(makerTicketId);
_nfteacket.burnTicket(makerOptionData.takerTicketId);
emit OptionUsed(makerTicketId, false);
} else {
revert("NFTea: Not a seller");
}
}
/// @param spender the address that claims to be the ticket owner
/// @param ticketId the option ticket id
function _requireTicketOwner(address spender, uint256 ticketId)
private
view
{
address owner = NFTeacket(nfteacket).ownerOf(ticketId);
require(owner == spender, "NFTea: Not ticket owner");
}
/// @dev ETH needs to be sent if the maker is
/// - buying a call : he needs to send the option price
/// - buying a put : he needs to send the option price
/// - selling a call : he needs to send the strike price
/// @param amount the amount required to be sent by the trader
function _requireEthSent(uint256 amount) private view {
require(msg.value == amount, "NFTea: Incorrect sent ETH amount");
}
/// @dev When a trader wants to sell a call, he has to lock his NFT
/// until maturity
/// @param nftId the token ID of the NFT to lock
/// @param nftContractAddress address of the NFT contract
function _lockNft(uint256 nftId, address nftContractAddress) private {
IERC721 nftContract = IERC721(nftContractAddress);
address owner = nftContract.ownerOf(nftId);
require(owner == msg.sender, "NFTea : Not nft owner");
require(
address(this) == owner ||
nftContract.getApproved(nftId) == address(this) ||
nftContract.isApprovedForAll(owner, address(this)),
"NFTea : Contract not approved, can't lock nft"
);
// Lock the nft by transfering it to the contract
nftContract.transferFrom(msg.sender, address(this), nftId);
}
function _transferNft(
address from,
address to,
uint256 nftId,
address nft
) private {
IERC721 nftContract = IERC721(nft);
nftContract.transferFrom(from, to, nftId);
}
/// @dev Safely transfer amount ethereum to the target
/// @param to the target wallet to send eth to
/// @param amount the amount of eth to send
function _transferEth(address to, uint256 amount) private {
(bool success, ) = to.call{value: amount}("");
require(success, "NFTea: Eth transfer failed");
}
}
// File contracts/test/CustomErc721.sol
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.4;
contract CustomERC721 is ERC721 {
uint256 private _counter;
constructor() ERC721("CustomERC721", "NFK") {}
function mint(address to) public {
uint256 tokenId = _counter++;
_safeMint(to, tokenId);
}
} | @notice Mint a taker ticket NFT associated with the given option offer @param to adress to mint a ticket to @param data option data to store in the ticket @dev No need to check that the maker icket referenced in the data params actually exists since it's already ensure in the NFTea caller contract | function mintTakerTicket(address to, OptionDataTaker memory data)
public
onylyFromNFTea
returns (uint256 ticketId)
{
ticketId = _counter++;
_safeMint(to, ticketId);
_ticketIdToOptionDataTaker[ticketId] = data;
_ticketIdToType[ticketId] = TicketType.Taker;
}
| 7,968,040 | [
1,
49,
474,
279,
268,
6388,
9322,
423,
4464,
3627,
598,
326,
864,
1456,
10067,
225,
358,
1261,
663,
358,
312,
474,
279,
9322,
358,
225,
501,
1456,
501,
358,
1707,
316,
326,
9322,
225,
2631,
1608,
358,
866,
716,
326,
312,
6388,
277,
1688,
8042,
316,
326,
501,
859,
6013,
1704,
3241,
518,
1807,
1818,
3387,
316,
326,
423,
4464,
24852,
4894,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
312,
474,
56,
6388,
13614,
12,
2867,
358,
16,
2698,
751,
56,
6388,
3778,
501,
13,
203,
3639,
1071,
203,
3639,
603,
93,
715,
1265,
50,
4464,
24852,
203,
3639,
1135,
261,
11890,
5034,
9322,
548,
13,
203,
565,
288,
203,
3639,
9322,
548,
273,
389,
7476,
9904,
31,
203,
3639,
389,
4626,
49,
474,
12,
869,
16,
9322,
548,
1769,
203,
3639,
389,
16282,
28803,
1895,
751,
56,
6388,
63,
16282,
548,
65,
273,
501,
31,
203,
3639,
389,
16282,
28803,
559,
63,
16282,
548,
65,
273,
22023,
559,
18,
56,
6388,
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
]
|
./full_match/4/0xbD7eA67295855ed94A84f45433352109Dd31a361/sources/contracts/TradingContractTools.sol | Function that created a Path in order to perform transactions with the UniswapV2Router. The directPath booleanwill define if the trading will happen directly (true) or though WBNB (false). If there is no LP between thebaseToken and the PairedToken a direct trade is not possible. try ITradingContract(_tradingContract).directPath() returns (bool _directPath) { directPath = _directPath; } catch { directPath = false; } | function createPath(address _tokenIn,address _tokenOut, address _tradingContract) internal view returns (address[] memory) {
address[] memory path;
bool directPath =ITradingContract(_tradingContract).directPath();
if (directPath) {
address pairedTokenAddress = ITradingContract(_tradingContract).pairedTokenAddress();
address baseTokenAddress = ITradingContract(_tradingContract).baseTokenAddress();
if ((_tokenIn == pairedTokenAddress && _tokenOut == WETHAddress) || (_tokenIn == WETHAddress && _tokenOut == pairedTokenAddress)) {
path = new address[](3);
path[0] = _tokenIn;
path[1] = baseTokenAddress;
path[2] = _tokenOut;
path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
}
if (_tokenIn == WETHAddress || _tokenOut == WETHAddress) {
path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
path = new address[](3);
path[0] = _tokenIn;
path[1] = WETHAddress;
path[2] = _tokenOut;
}
}
return path;
}
| 799,715 | [
1,
2083,
716,
2522,
279,
2666,
316,
1353,
358,
3073,
8938,
598,
326,
1351,
291,
91,
438,
58,
22,
8259,
18,
1021,
2657,
743,
1250,
20194,
4426,
309,
326,
1284,
7459,
903,
5865,
5122,
261,
3767,
13,
578,
11376,
678,
15388,
38,
261,
5743,
2934,
971,
1915,
353,
1158,
511,
52,
3086,
326,
1969,
1345,
471,
326,
21800,
2921,
1345,
279,
2657,
18542,
353,
486,
3323,
18,
775,
467,
1609,
7459,
8924,
24899,
313,
14968,
8924,
2934,
7205,
743,
1435,
1135,
261,
6430,
389,
7205,
743,
13,
288,
377,
2657,
743,
273,
389,
7205,
743,
31,
289,
1044,
288,
377,
2657,
743,
273,
629,
31,
289,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
752,
743,
12,
2867,
389,
2316,
382,
16,
2867,
389,
2316,
1182,
16,
1758,
389,
313,
14968,
8924,
13,
2713,
1476,
1135,
261,
2867,
8526,
3778,
13,
288,
203,
203,
3639,
1758,
8526,
3778,
589,
31,
203,
203,
3639,
1426,
2657,
743,
273,
1285,
6012,
310,
8924,
24899,
313,
14968,
8924,
2934,
7205,
743,
5621,
203,
203,
203,
3639,
309,
261,
7205,
743,
13,
288,
203,
203,
5411,
1758,
18066,
1345,
1887,
273,
467,
1609,
7459,
8924,
24899,
313,
14968,
8924,
2934,
24197,
1345,
1887,
5621,
203,
5411,
1758,
1026,
1345,
1887,
273,
467,
1609,
7459,
8924,
24899,
313,
14968,
8924,
2934,
1969,
1345,
1887,
5621,
203,
203,
5411,
309,
14015,
67,
2316,
382,
422,
18066,
1345,
1887,
597,
389,
2316,
1182,
422,
678,
1584,
44,
1887,
13,
747,
261,
67,
2316,
382,
422,
678,
1584,
44,
1887,
597,
389,
2316,
1182,
422,
18066,
1345,
1887,
3719,
288,
203,
7734,
589,
273,
394,
1758,
8526,
12,
23,
1769,
203,
7734,
589,
63,
20,
65,
273,
389,
2316,
382,
31,
203,
7734,
589,
63,
21,
65,
273,
1026,
1345,
1887,
31,
203,
7734,
589,
63,
22,
65,
273,
389,
2316,
1182,
31,
203,
7734,
589,
273,
394,
1758,
8526,
12,
22,
1769,
203,
7734,
589,
63,
20,
65,
273,
389,
2316,
382,
31,
203,
7734,
589,
63,
21,
65,
273,
389,
2316,
1182,
31,
203,
5411,
289,
203,
5411,
309,
261,
67,
2316,
382,
422,
678,
1584,
44,
1887,
747,
389,
2316,
1182,
422,
678,
1584,
44,
1887,
13,
288,
203,
7734,
589,
2
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.