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 |
---|---|---|---|---|---|---|
pragma solidity ^0.5.2;
interface PriceFeed {
function read(uint _marketId) external view returns (uint);
}
contract Rewards {
function addMiner(address _minter) external returns (bool);
function removeMiner(address _minter) external returns (bool);
function approveFor(address owner, uint256 value) public returns (bool);
function updateRMSub(uint256 _amount) public returns (bool);
function computeRewards(address _source) public returns (uint256);
}
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public auth
{
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public auth
{
authority = authority_;
emit LogSetAuthority(address(authority));
}
modifier auth {
assert(isAuthorized(msg.sender, msg.sig));
_;
}
modifier authorized(bytes4 sig) {
assert(isAuthorized(msg.sender, sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, address(this), sig);
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
emit LogNote(msg.sig, msg.sender, foo, bar, msg.data);
_;
}
}
contract DSMath {
/*
standard uint256 functions
*/
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
assert((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
assert((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
assert((z = x * y) >= x);
}
function div(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x / y;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x >= y ? x : y;
}
/*
uint128 functions (h is for half)
*/
function hadd(uint128 x, uint128 y) internal pure returns (uint128 z) {
assert((z = x + y) >= x);
}
function hsub(uint128 x, uint128 y) internal pure returns (uint128 z) {
assert((z = x - y) <= x);
}
function hmul(uint128 x, uint128 y) internal pure returns (uint128 z) {
assert((z = x * y) >= x);
}
function hdiv(uint128 x, uint128 y) internal pure returns (uint128 z) {
z = x / y;
}
function hmin(uint128 x, uint128 y) internal pure returns (uint128 z) {
return x <= y ? x : y;
}
function hmax(uint128 x, uint128 y) internal pure returns (uint128 z) {
return x >= y ? x : y;
}
/*
int256 functions
*/
function imin(int256 x, int256 y) internal pure returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) internal pure returns (int256 z) {
return x >= y ? x : y;
}
/*
WAD math
*/
uint128 WAD = 10 ** 18;
function wadd(uint128 x, uint128 y) internal pure returns (uint128) {
return hadd(x, y);
}
function wsub(uint128 x, uint128 y) internal pure returns (uint128) {
return hsub(x, y);
}
function wmul(uint128 x, uint128 y) internal view returns (uint128 z) {
z = cast((uint256(x) * y + WAD / 2) / WAD);
}
function wdiv(uint128 x, uint128 y) internal view returns (uint128 z) {
z = cast((uint256(x) * WAD + y / 2) / y);
}
function wmin(uint128 x, uint128 y) internal pure returns (uint128) {
return hmin(x, y);
}
function wmax(uint128 x, uint128 y) internal pure returns (uint128) {
return hmax(x, y);
}
/*
RAY math
*/
uint128 RAY = 10 ** 27;
function radd(uint128 x, uint128 y) internal pure returns (uint128) {
return hadd(x, y);
}
function rsub(uint128 x, uint128 y) internal pure returns (uint128) {
return hsub(x, y);
}
function rmul(uint128 x, uint128 y) internal view returns (uint128 z) {
z = cast((uint256(x) * y + RAY / 2) / RAY);
}
function rdiv(uint128 x, uint128 y) internal view returns (uint128 z) {
z = cast((uint256(x) * RAY + y / 2) / y);
}
function rpow(uint128 x, uint64 n) internal view 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) internal pure returns (uint128) {
return hmin(x, y);
}
function rmax(uint128 x, uint128 y) internal pure returns (uint128) {
return hmax(x, y);
}
function cast(uint256 x) internal pure returns (uint128 z) {
assert((z = uint128(x)) == x);
}
}
contract DSThing is DSAuth, DSNote, DSMath {}
contract DSValue is DSThing {
bool has;
uint val;
function peek() public view returns (uint, bool) {
return (val,has);
}
function read() public view returns (uint) {
uint wut;
bool haz;
(wut, haz) = peek();
assert(haz);
return wut;
}
function poke(uint wut) public note auth {
val = wut;
has = true;
}
function void() public note auth { // unset the value
has = false;
}
}
/**
* EIP 900: Simple Staking Interface https://eips.ethereum.org/EIPS/eip-900
*/
interface SimpleStakeInterface {
event Staked(address indexed user, uint256 amount, uint256 total, bytes data);
event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data);
function stake(address user, uint256 amount) external returns (bool);
function unstake(address _user) external returns (bool);
function totalStakedFor(address addr) external view returns (uint256);
function token() external view returns (address);
}
contract Medianizer is DSThing, SimpleStakeInterface {
using SafeMath for uint256;
event LogValue(uint marketId, uint val);
event MinBlocksUpdated(uint newValue);
event Staked(address indexed user, uint256 amount, uint256 total);
event Unstaked(address indexed user, uint256 amount, uint256 total);
event FeedSet(uint pos, address feed);
event IsSub (uint256 expiryTime, uint256 blockNow);
event Subscribed(address indexed user, uint256 expiryTime, uint256 amountPaid);
uint public minStakeDuration = 0;
uint public stakeSize = 0; // Stake size in Wei. Note: this is token agnostic.
uint public next = 1;
uint public myn = 1;
address public token;
uint256 public subscribeFee = 10000000000000000000; //@note: 10 tokens, real application 10K tokens
uint256 public subBlockDuration = 100; // @note: which interval of blocks that sub lasts for
mapping (uint => uint) private values;
mapping (uint => address) public feeds; // int ID => feed address
mapping (address => uint) public indexes; // feed address => int ID
mapping (address => address) public ownerToFeed; // msg.sender => feedAddress
mapping (address => uint) public stakeTime; // feed address => timestamp
mapping (address => uint) public stakesFor; // feed address => stake amount (accounting)
mapping(address => uint256) public expiryTimes;
modifier unsubscribed() {
require(expiryTimes[msg.sender] < now, "Already subscribed");
_;
}
modifier subscribed() {
require(expiryTimes[msg.sender] >= now, "Not subscribed!");
_;
}
constructor(uint _minStakeDuration, address _token, uint _stakeSize) public {
minStakeDuration = _minStakeDuration;
emit MinBlocksUpdated(_minStakeDuration);
token = _token;
stakeSize = _stakeSize;
}
/** USER INTERFACE Functions */
/**
* @dev function to poke the medianizer by price feed to calculate median
*/
function poke(uint _marketId) external returns (bool) {
uint value = compute(_marketId);
values[_marketId] = value;
emit LogValue(_marketId, value);
return true;
}
/**
* @dev function to check price feed owner
* @param _address is owner address
* @return price feed address related to owner
*/
function getOwnerToFeed(address _address) public view returns (address) {
address pfAddress = ownerToFeed[_address];
return pfAddress;
}
/**
* @dev function to check if token address = address(0)
*/
function usesYBT() public view returns (bool) {
return token != address(0);
}
function withdrawRewards(address _user) public returns (bool) {
require(usesYBT(), "Not using token");
require(msg.sender == _user || ownerToFeed[msg.sender] == _user, "Unauthorised");
uint256 _amountToReturn = Rewards(token).computeRewards(_user);
ERC20(token).transfer(msg.sender, _amountToReturn);
}
/** USER INTERFACE Functions */
/** STAKING Functions */
/**
* @dev function to stake a price feed by an owner
*/
function stake(address user, uint256 amount) external returns (bool) {
require(indexes[user] == 0, "Can't stake more than once");
require(ownerToFeed[msg.sender] == address(0), "Can't stake more than once");
require(amount == stakeSize, "Invalid stake size");
if (usesYBT()) {
require(ERC20(token).balanceOf(msg.sender) >= stakeSize, "insufficient balance");
Rewards(token).approveFor(msg.sender, amount);
ERC20(token).transferFrom(msg.sender, address(this), amount);
Rewards(token).addMiner(user);
}
stakesFor[user] = amount;
ownerToFeed[msg.sender] = user;
stakeTime[user] = block.timestamp;
set(user);
emit Staked(user, amount, amount);
return true;
}
/**
* @dev function to unstake a price feed by an owner
*/
function unstake(address _user) external returns (bool) {
require(usesYBT(), "Not using token");
require(msg.sender == _user || ownerToFeed[msg.sender] == _user, "Unauthorised");
uint256 _amountToReturn = (Rewards(token).computeRewards(_user)).add(stakesFor[_user]);
require(ERC20(token).balanceOf(address(this)) >= _amountToReturn, "Amount exceeds contract balance");
require(block.timestamp >= (stakeTime[_user] + minStakeDuration), "Can't unstake now.");
Rewards(token).removeMiner(_user);
stakesFor[_user] = 0;
ownerToFeed[msg.sender] = address(0);
ERC20(token).transfer(msg.sender, _amountToReturn);
unset(_user);
emit Unstaked(_user, _amountToReturn, stakesFor[_user]);
return true;
}
/**
* @notice Returns total staked for address.
* @param addr Address to check.
* @return amount of ethers staked.
*/
function totalStakedFor(address addr) public view returns (uint256) {
return stakesFor[addr];
}
/** STAKING Functions */
/** SUBSCRIPTION Functions */
/**
* @dev Subscribe user to the system
* @param _amount of tokens paid to subscribe
* @param _expiry time is when the subscribe ends
*/
function subscribe(uint256 _amount, uint256 _expiry) external unsubscribed returns (bool) {
require(_amount == subscribeFee, "Invalid subscribtion amount");
Rewards(token).approveFor(msg.sender, _amount);
ERC20(token).transferFrom(msg.sender, address(this), _amount);
expiryTimes[msg.sender] = _expiry;
Rewards(token).updateRMSub(_amount);
return true;
}
/**
* @dev Function that returns median to subscribers
* @param _marketId corresponding market's median is returned
*/
function read(uint _marketId) external view returns (uint) {
require(values[_marketId] != 0, "Medianizer: Value is not set");
return values[_marketId];
}
/** SUBSCRIPTION Functions */
/** DATA FILTER Functions */
function compute(uint _marketId) public view returns (uint) {
uint[] memory vals = new uint[](next - 1);
uint count = 0;
// Sort feed values
for (uint i = 1; i < next; i++) {
if (feeds[i] != address(0)) {
uint feedVal = PriceFeed(feeds[i]).read(_marketId);
if (feedVal > 0) {
if (count == 0 || feedVal >= vals[count - 1]) {
vals[count] = feedVal;
} else {
uint j = 0;
while (feedVal >= vals[j]) {
j++;
}
for (uint k = count; k > j; k--) {
vals[k] = vals[k - 1];
}
vals[j] = feedVal;
}
count++;
}
}
}
require (count >= myn, "Not enough active feeds");
uint value;
if (count % 2 == 0) {
uint val1 = vals[(count / 2) - 1];
uint val2 = vals[count / 2];
value = (val1 / 2) + (val2 / 2);
} else {
value = vals[(count - 1) / 2];
}
return value;
}
function set(address feed) private returns (bool) {
set(next, feed);
next++;
return true;
}
function set(uint pos, address feed) private returns (bool) {
require(pos > 0, "Position must be a positive integer");
require(indexes[feed] == 0);
indexes[feed] = pos; //give the feed a number
feeds[pos] = feed; //put the address of the feed into that number
emit FeedSet(pos, feed);
return true;
}
/**
- core logic
- get the old position from the pricefeed using indexes[pf] = old position
- if old position == next -1 , then just do cleanup
- if not then store the information of the last price feed + index
- dump thast into the old position
- clean up last one
*/
function unset(uint pos, address feed) private returns (bool) {
//edge case take care of a) 1 pf in the system b) when last of tries to unstake
if (next == 2 || pos == (next - 1)) {
//address pf = feeds[pos];
feedCleanUp(pos, feed);
} else {
feedCleanUp(pos, feed);
//next will be assigned to new feed, so last feed = next-1
address lastFeed = feeds[next - 1];
uint lastIndex = indexes[lastFeed];
//clean up the last element in the mapping
feedCleanUp(lastIndex, lastFeed);
//replace in the empty slot in the mappings
set(pos, lastFeed);
}
next--;
return true;
}
//@dev: used for cleaning up mapping values
function feedCleanUp(uint pos, address feed) private returns (bool) {
indexes[feed] = 0 ;
feeds[pos] = address(0);
return true;
}
// when unsetting we replace the target with the last
// item in the mapping
function unset(address feed) private returns (bool) {
uint pos = indexes[feed];
unset(pos, feed);
return true;
}
} | * @dev Subscribe user to the system @param _amount of tokens paid to subscribe @param _expiry time is when the subscribe ends/ | function subscribe(uint256 _amount, uint256 _expiry) external unsubscribed returns (bool) {
require(_amount == subscribeFee, "Invalid subscribtion amount");
Rewards(token).approveFor(msg.sender, _amount);
ERC20(token).transferFrom(msg.sender, address(this), _amount);
expiryTimes[msg.sender] = _expiry;
Rewards(token).updateRMSub(_amount);
return true;
}
| 6,478,312 | [
1,
16352,
729,
358,
326,
2619,
225,
389,
8949,
434,
2430,
30591,
358,
9129,
225,
389,
22409,
813,
353,
1347,
326,
9129,
3930,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
9129,
12,
11890,
5034,
389,
8949,
16,
2254,
5034,
389,
22409,
13,
3903,
640,
27847,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
24899,
8949,
422,
9129,
14667,
16,
315,
1941,
10189,
24252,
3844,
8863,
203,
3639,
534,
359,
14727,
12,
2316,
2934,
12908,
537,
1290,
12,
3576,
18,
15330,
16,
389,
8949,
1769,
203,
3639,
4232,
39,
3462,
12,
2316,
2934,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
8949,
1769,
203,
3639,
10839,
10694,
63,
3576,
18,
15330,
65,
273,
389,
22409,
31,
203,
3639,
534,
359,
14727,
12,
2316,
2934,
2725,
8717,
1676,
24899,
8949,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 Lottery
{
address admin;
uint fee;
uint end;
uint redemption;
uint constant betAmount = 100;
uint totalPot;
uint whiteballs;
uint powerball;
struct Bet
{
uint amount;
uint whiteballs;
uint powerball;
}
// mapping of ticket number to player.
mapping(address => Bet[]) lotto;
// list of winners.
address[] winners;
modifier AdminOnly()
{
if (msg.sender == admin)
{
_ // continue
}
}
modifier InPlay()
{
if(msg.sender != admin && block.timestamp < end)
{
_ // continue
}
}
modifier EndPlay()
{
if(msg.sender != admin &&
block.timestamp >= end &&
block.timestamp < redemption)
{
_ // continue
}
}
event Logging(string output, address caller);
// constructor
function Lottery(uint feePercent, uint unixEndTime, uint daysToRedeem)
{
if(admin != address(0))
{
throw;
}
fee = feePercent;
end = unixEndTime;
redemption = daysToRedeem * 86400; // unix seconds in a day.
totalPot = 0;
admin = msg.sender;
}
function DrawWinning(uint _whiteballs, uint _powerball) AdminOnly EndPlay
{
// prevent administrator from calling this function more than once.
if(whiteballs != 0 && powerball != 0)
{
Logging("This function has already called. It can only be called once.", msg.sender);
return;
}
// pay administrative fee.
uint _tax = totalPot * fee;
if(!admin.send(_tax))
{
throw;
}
// reduce pot size by administrative fee.
totalPot -= _tax;
whiteballs = _whiteballs;
powerball = _powerball;
}
function DisburseEarnings() AdminOnly EndPlay
{
// split pot amongst winners.
uint _earnings = totalPot / winners.length;
// disburse winnings.
for(uint i = 0; i < winners.length; i++)
{
if(!winners[i].send(_earnings))
{
throw;
}
}
// pay admin administrative fee and terminate lottery contract [reference: #2 reported by zbobbert]
selfdestruct(admin);
}
// allow the player to collect their winnings [reference: #1 reported by zbobbert]
function CollectEarning() EndPlay
{
// calculate winner's earnings.
uint _earnings = totalPot / winners.length;
// disburse winnings.
for(uint i = 0; i < winners.length; i++)
{
if(winners[i] == msg.sender)
{
if(!winners[i].send(_earnings))
{
throw;
}
// remove player from winners list since they have been paid.
delete winners[i];
// reduce the size of the pot correspondingly.
totalPot -= _earnings;
break;
}
}
}
function Play(uint _whiteballs, uint _powerball) InPlay
{
// check betting amount is correct.
if(msg.value != betAmount)
{
Logging("bet amount is incorrect", msg.sender);
return;
}
// check if user hasn't already played the same number.
Bet[] _playerbets = lotto[msg.sender];
// prevent players from playing the same number multiple times.
for(uint i = 0; i < _playerbets.length; i++)
{
if(_playerbets[i].whiteballs == _whiteballs)
{
Logging("betting on the same number not permitted", msg.sender);
return;
}
}
// add bet to pot.
totalPot += msg.value;
// track player's bet.
lotto[msg.sender].push(Bet({
amount: msg.value,
whiteballs: _whiteballs,
powerball: _powerball
}));
}
function Check() EndPlay
{
if(whiteballs == 0 && powerball == 0)
{
Logging("please check again. Winning balls have not been drawn yet.", msg.sender);
return;
}
var _bets = lotto[msg.sender];
for(uint i = 0; i < _bets.length; i++)
{
if( _bets[i].whiteballs == whiteballs &&
_bets[i].powerball == powerball)
{
Logging("You're a PowerBall winner!", msg.sender);
// track winners.
winners.push(msg.sender);
}
}
}
function ()
{
throw;
}
} | allow the player to collect their winnings [reference: #1 reported by zbobbert] calculate winner's earnings. disburse winnings. | function CollectEarning() EndPlay
{
uint _earnings = totalPot / winners.length;
for(uint i = 0; i < winners.length; i++)
{
if(winners[i] == msg.sender)
{
if(!winners[i].send(_earnings))
{
throw;
}
break;
}
}
}
| 5,388,476 | [
1,
5965,
326,
7291,
358,
3274,
3675,
5657,
82,
899,
306,
6180,
30,
404,
14010,
635,
27473,
947,
25925,
65,
4604,
5657,
1224,
1807,
425,
1303,
899,
18,
1015,
70,
295,
307,
5657,
82,
899,
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,
9302,
41,
9542,
1435,
4403,
11765,
203,
565,
288,
203,
3639,
2254,
389,
73,
1303,
899,
273,
2078,
18411,
342,
5657,
9646,
18,
2469,
31,
203,
540,
203,
3639,
364,
12,
11890,
277,
273,
374,
31,
277,
411,
5657,
9646,
18,
2469,
31,
277,
27245,
7010,
3639,
288,
203,
5411,
309,
12,
8082,
9646,
63,
77,
65,
422,
1234,
18,
15330,
13,
203,
5411,
288,
203,
7734,
309,
12,
5,
8082,
9646,
63,
77,
8009,
4661,
24899,
73,
1303,
899,
3719,
7010,
7734,
288,
203,
10792,
604,
31,
203,
7734,
289,
203,
1082,
3639,
898,
31,
203,
5411,
289,
203,
3639,
289,
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
]
|
./full_match/8453/0xb106255C5A2DD658c3D06aEC642a4E5d5A2C8897/sources/contracts/CookiCard.sol | Modifiers and Constructor | contract CookiCard is ICookiCard, IERC4906, ERC721, Ownable, ReentrancyGuard {
ICookiData public immutable cookiData;
ICookiFrame public immutable cookiFrame;
bool public initialised;
uint256 public nonce;
uint256 public seed;
uint256 public immutable maxSupply;
uint256 public immutable fee;
NamedDisplaySetting[] public namedDisplaySettingArray;
NamedBackgroundColours[] public namedBackgroundColoursArray;
NamedFaceColours[] public namedFaceColoursArray;
NamedHatColours[] public namedHatColoursArray;
NamedNeutralColours[] public namedNeutralColoursArray;
pragma solidity 0.8.17;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {IERC4906} from "@openzeppelin/contracts/interfaces/IERC4906.sol";
import {ICookiData} from "./interfaces/ICookiData.sol";
import {ICookiCard} from "./interfaces/ICookiCard.sol";
import {ICookiFrame} from "./interfaces/ICookiFrame.sol";
modifier onlyCookiData() {
require(msg.sender == address(cookiData));
_;
}
modifier onlyCookiFrame() {
require(msg.sender == address(cookiFrame));
_;
}
constructor(ICookiData _cookiData, ICookiFrame _cookiFrame) ERC721("Cooki Card", "CC") {
cookiData = _cookiData;
cookiFrame = _cookiFrame;
maxSupply = 780;
fee = 1e15 wei;
initialised = false;
}
function init() external onlyOwner {
require(!initialised);
cookiData.loadData();
initialised = true;
}
function mint() external payable nonReentrant {
require(initialised);
require(nonce < maxSupply);
require(msg.value >= fee);
seed = uint256(keccak256(abi.encodePacked(block.number + seed + nonce)));
cookiFrame.storeInitCardSettings(
nonce,
namedDisplaySettingArray[0],
namedBackgroundColoursArray[seed % namedBackgroundColoursArray.length],
namedFaceColoursArray[seed % namedFaceColoursArray.length],
namedHatColoursArray[seed % namedHatColoursArray.length],
namedNeutralColoursArray[seed % namedNeutralColoursArray.length]
);
_mint(msg.sender, nonce);
nonce++;
}
function totalSupply() external view returns (uint256) {
return nonce;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
_requireMinted(tokenId);
return cookiFrame.drawFull(tokenId);
}
function emitBatchMetadataUpdate() external {
emit BatchMetadataUpdate(0, type(uint256).max);
}
function loadDisplaySetting(NamedDisplaySetting memory _namedDisplaySetting) external onlyCookiData {
namedDisplaySettingArray.push(_namedDisplaySetting);
}
function loadBackgroundColours(NamedBackgroundColours memory _namedBackgroundColours) external onlyCookiData {
namedBackgroundColoursArray.push(_namedBackgroundColours);
}
function loadFaceColours(NamedFaceColours memory _namedFaceColours) external onlyCookiData {
namedFaceColoursArray.push(_namedFaceColours);
}
function loadHatColours(NamedHatColours memory _namedHatColours) external onlyCookiData {
namedHatColoursArray.push(_namedHatColours);
}
function loadNeutralColours(NamedNeutralColours memory _namedNeutralColours) external onlyCookiData {
namedNeutralColoursArray.push(_namedNeutralColours);
}
function getNamedDisplaySetting(uint256 _newDisplaySetting) external view onlyCookiFrame returns (NamedDisplaySetting memory) {
return namedDisplaySettingArray[_newDisplaySetting];
}
function getRandomisedBackgroundColours(uint256 _tokenId) external onlyCookiFrame returns (NamedBackgroundColours memory) {
seed = uint256(keccak256(abi.encodePacked(block.number + seed + _tokenId)));
return namedBackgroundColoursArray[seed % namedBackgroundColoursArray.length];
}
function getRandomisedFaceColours(uint256 _tokenId) external onlyCookiFrame returns (NamedFaceColours memory) {
seed = uint256(keccak256(abi.encodePacked(block.number + seed + _tokenId)));
return namedFaceColoursArray[seed % namedFaceColoursArray.length];
}
function getRandomisedHatColours(uint256 _tokenId) external onlyCookiFrame returns (NamedHatColours memory) {
seed = uint256(keccak256(abi.encodePacked(block.number + seed + _tokenId)));
return namedHatColoursArray[seed % namedHatColoursArray.length];
}
function getRandomisedNeutralColours(uint256 _tokenId) external onlyCookiFrame returns (NamedNeutralColours memory) {
seed = uint256(keccak256(abi.encodePacked(block.number + seed + _tokenId)));
return namedNeutralColoursArray[seed % namedNeutralColoursArray.length];
}
receive() external payable {}
function withdraw() external onlyOwner {
require(success);
}
(bool success, ) = (owner()).call{value: address(this).balance }("");
function README() external view returns (string memory) {
return string.concat('Modify your Cooki Card with the Cooki Frame contract: ', Strings.toHexString(address(cookiFrame)));
}
} | 11,545,949 | [
1,
11948,
471,
11417,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
385,
1184,
77,
6415,
353,
26899,
1184,
77,
6415,
16,
467,
654,
39,
7616,
7677,
16,
4232,
39,
27,
5340,
16,
14223,
6914,
16,
868,
8230,
12514,
16709,
288,
203,
565,
26899,
1184,
77,
751,
1071,
11732,
15860,
77,
751,
31,
203,
565,
26899,
1184,
77,
3219,
1071,
11732,
15860,
77,
3219,
31,
203,
203,
565,
1426,
1071,
30372,
31,
203,
203,
565,
2254,
5034,
1071,
7448,
31,
203,
565,
2254,
5034,
1071,
5009,
31,
203,
565,
2254,
5034,
1071,
11732,
943,
3088,
1283,
31,
203,
565,
2254,
5034,
1071,
11732,
14036,
31,
203,
203,
565,
9796,
4236,
5568,
8526,
1071,
4141,
4236,
5568,
1076,
31,
203,
565,
9796,
8199,
914,
4390,
8526,
1071,
4141,
8199,
914,
4390,
1076,
31,
203,
565,
9796,
11824,
914,
4390,
8526,
1071,
4141,
11824,
914,
4390,
1076,
31,
203,
565,
9796,
44,
270,
914,
4390,
8526,
1071,
4141,
44,
270,
914,
4390,
1076,
31,
203,
565,
9796,
6586,
14566,
287,
914,
4390,
8526,
1071,
4141,
6586,
14566,
287,
914,
4390,
1076,
31,
203,
203,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
4033,
31,
203,
5666,
288,
5460,
429,
97,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
3860,
19,
5460,
429,
18,
18281,
14432,
203,
5666,
288,
7957,
97,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
5471,
19,
7957,
18,
18281,
14432,
203,
5666,
288,
426,
8230,
12514,
16709,
97,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
7462,
19,
426,
8230,
2
]
|
./full_match/1/0x7Cd8e8bA20cdb9339543f0e1BE772fF880d7E1b4/sources/contracts/pools/common/RealWorldAssetReceipt.sol | @param _name Receipt token name @param _symbol Receipt token symbol | constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {
usdt = IERC20(USDT);
receipt = IERC20(address(this));
}
| 9,614,160 | [
1,
67,
529,
29787,
1147,
508,
225,
389,
7175,
29787,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
12,
1080,
3778,
389,
529,
16,
533,
3778,
389,
7175,
13,
4232,
39,
3462,
24899,
529,
16,
389,
7175,
13,
288,
203,
3639,
584,
7510,
273,
467,
654,
39,
3462,
12,
3378,
9081,
1769,
203,
3639,
16030,
273,
467,
654,
39,
3462,
12,
2867,
12,
2211,
10019,
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
]
|
./full_match/1/0xF5abAdec1bcb7d79D0E972981F13D731D5d06aA8/sources/contracts/factory/GenArtCollectionFactory.sol | * @dev Add an ERC721 implementation contract and map by index/ | function addErc721Implementation(uint8 index, address implementation)
external
onlyAdmin
{
erc721Implementations[index] = implementation;
}
| 4,883,637 | [
1,
986,
392,
4232,
39,
27,
5340,
4471,
6835,
471,
852,
635,
770,
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,
527,
41,
1310,
27,
5340,
13621,
12,
11890,
28,
770,
16,
1758,
4471,
13,
203,
3639,
3903,
203,
3639,
1338,
4446,
203,
565,
288,
203,
3639,
6445,
71,
27,
5340,
5726,
1012,
63,
1615,
65,
273,
4471,
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
]
|
/*
Zethr | https://zethr.io
(c) Copyright 2018 | All Rights Reserved
This smart contract was developed by the Zethr Dev Team and its source code remains property of the Zethr Project.
*/
pragma solidity ^0.4.24;
// File: contracts/Libraries/SafeMath.sol
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
assert(c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts/Bankroll/ZethrSnap.sol
contract ZethrInterface {
function transfer(address _from, uint _amount) public;
function myFrontEndTokens() public view returns (uint);
}
contract ZethrMultiSigWalletInterface {
mapping(address => bool) public isOwner;
}
contract ZethrSnap {
struct SnapEntry {
uint blockNumber;
uint profit;
}
struct Sig {
bytes32 r;
bytes32 s;
uint8 v;
}
// Reference to the Zethr multi sig wallet for authentication
ZethrMultiSigWalletInterface public multiSigWallet;
// Reference to Zethr token contract
ZethrInterface zethr;
// The server's public address (used to confirm valid claims)
address signer;
// Mapping of user address => snap.id => claimStatus
mapping(address => mapping(uint => bool)) public claimedMap;
// Array of all snaps
SnapEntry[] public snaps;
// Used to pause the contract in an emergency
bool public paused;
// The number of tokens in this contract allocated to snaps
uint public allocatedTokens;
constructor(address _multiSigWalletAddress, address _zethrAddress, address _signer)
public
{
multiSigWallet = ZethrMultiSigWalletInterface(_multiSigWalletAddress);
zethr = ZethrInterface(_zethrAddress);
signer = _signer;
paused = false;
}
/**
* @dev Needs to accept ETH dividends from Zethr token contract
*/
function()
public payable
{}
/**
* @dev Paused claims in an emergency
* @param _paused The new pause state
*/
function ownerSetPaused(bool _paused)
public
ownerOnly
{
paused = _paused;
}
/**
* @dev Updates the multi sig wallet reference
* @param _multiSigWalletAddress The new multi sig wallet address
*/
function walletSetWallet(address _multiSigWalletAddress)
public
walletOnly
{
multiSigWallet = ZethrMultiSigWalletInterface(_multiSigWalletAddress);
}
/**
* @dev Withdraws dividends to multi sig wallet
*/
function withdraw()
public
{
(address(multiSigWallet)).transfer(address(this).balance);
}
/**
* @dev Updates the signer address
*/
function walletSetSigner(address _signer)
public walletOnly
{
signer = _signer;
}
/**
* @dev Withdraws tokens (for migrating to a new contract)
*/
function walletWithdrawTokens(uint _amount)
public walletOnly
{
zethr.transfer(address(multiSigWallet), _amount);
}
/**
* @return Total number of snaps stored
*/
function getSnapsLength()
public view
returns (uint)
{
return snaps.length;
}
/**
* @dev Creates a new snap
* @param _blockNumber The block number the server should use to calculate ownership
* @param _profitToShare The amount of profit to divide between all holders
*/
function walletCreateSnap(uint _blockNumber, uint _profitToShare)
public
walletOnly
{
uint index = snaps.length;
snaps.length++;
snaps[index].blockNumber = _blockNumber;
snaps[index].profit = _profitToShare;
// Make sure we have enough free tokens to create this snap
uint balance = zethr.myFrontEndTokens();
balance = balance - allocatedTokens;
require(balance >= _profitToShare);
// Update allocation token count
allocatedTokens = allocatedTokens + _profitToShare;
}
/**
* @dev Retrieves snap details
* @param _snapId The ID of the snap to get details of
*/
function getSnap(uint _snapId)
public view
returns (uint blockNumber, uint profit, bool claimed)
{
SnapEntry storage entry = snaps[_snapId];
return (entry.blockNumber, entry.profit, claimedMap[msg.sender][_snapId]);
}
/**
* @dev Process a claim
* @param _snapId ID of the snap this claim is for
* @param _payTo Address to send the proceeds to
* @param _amount The amount of profit claiming
* @param _signatureBytes Signature of the server approving this claim
*/
function claim(uint _snapId, address _payTo, uint _amount, bytes _signatureBytes)
public
{
// Check pause state
require(!paused);
// Prevent multiple calls
require(claimedMap[msg.sender][_snapId] == false);
claimedMap[msg.sender][_snapId] = true;
// Confirm that the server has approved this claim
// Note: the player cannot modify the _amount arbitrarily because it will invalidate the signature
Sig memory sig = toSig(_signatureBytes);
bytes32 hash = keccak256(abi.encodePacked("SNAP", _snapId, msg.sender, _amount));
address recoveredSigner = ecrecover(hash, sig.v, sig.r, sig.s);
require(signer == recoveredSigner);
// Reduce allocated tokens by claim amount
require(_amount <= allocatedTokens);
allocatedTokens = allocatedTokens - _amount;
// Send tokens
zethr.transfer(_payTo, _amount);
}
/**
* @dev The contract accepts ZTH tokens in order to pay out claims
*/
function tokenFallback(address /*_from*/, uint /*_amountOfTokens*/, bytes /*_data*/)
public view
returns (bool)
{
require(msg.sender == address(zethr), "Tokens must be ZTH");
return true;
}
/**
* @dev Extract a Sig struct from given bytes
*/
function toSig(bytes b)
internal pure
returns (Sig memory sig)
{
sig.r = bytes32(toUint(b, 0));
sig.s = bytes32(toUint(b, 32));
sig.v = uint8(b[64]);
}
/**
* @dev Extracts a uint from bytes
*/
function toUint(bytes _bytes, uint _start)
internal pure
returns (uint256)
{
require(_bytes.length >= (_start + 32));
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
// Only the multi sig wallet can call this method
modifier walletOnly()
{
require(msg.sender == address(multiSigWallet));
_;
}
// Only an owner can call this method (multi sig is always an owner)
modifier ownerOnly()
{
require(msg.sender == address(multiSigWallet) || multiSigWallet.isOwner(msg.sender));
_;
}
} | * @dev The contract accepts ZTH tokens in order to pay out claims/ | function tokenFallback(address /*_from*/, uint /*_amountOfTokens*/, bytes /*_data*/)
public view
returns (bool)
{
require(msg.sender == address(zethr), "Tokens must be ZTH");
return true;
}
| 1,817,864 | [
1,
1986,
6835,
8104,
2285,
2455,
2430,
316,
1353,
358,
8843,
596,
11955,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
1147,
12355,
12,
2867,
1748,
67,
2080,
5549,
16,
2254,
1748,
67,
8949,
951,
5157,
5549,
16,
1731,
1748,
67,
892,
5549,
13,
203,
225,
1071,
1476,
203,
225,
1135,
261,
6430,
13,
203,
225,
288,
203,
565,
2583,
12,
3576,
18,
15330,
422,
1758,
12,
94,
546,
86,
3631,
315,
5157,
1297,
506,
2285,
2455,
8863,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2021-04-21
*/
// SPDX-License-Identifier: AGPL-3.0-or-later
// 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.6.12;
interface VatLike {
function hope(address) external;
}
interface GemJoinLike {
function dec() external view returns (uint256);
function gem() external view returns (TokenLike);
function exit(address, uint256) external;
}
interface DaiJoinLike {
function dai() external view returns (TokenLike);
function vat() external view returns (VatLike);
function join(address, uint256) external;
}
interface TokenLike {
function approve(address, uint256) external;
function transfer(address, uint256) external;
function balanceOf(address) external view returns (uint256);
}
interface OtcLike {
function buyAllAmount(address, uint256, address, uint256) external returns (uint256);
function sellAllAmount(address, uint256, address, uint256) external returns (uint256);
}
// Simple Callee Example to interact with MatchingMarket
// This Callee contract exists as a standalone contract
contract CalleeMakerOtc {
OtcLike public otc;
DaiJoinLike public daiJoin;
TokenLike public dai;
uint256 public constant RAY = 10 ** 27;
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function divup(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(x, sub(y, 1)) / y;
}
function setUp(address otc_, address clip_, address daiJoin_) internal {
otc = OtcLike(otc_);
daiJoin = DaiJoinLike(daiJoin_);
dai = daiJoin.dai();
daiJoin.vat().hope(clip_);
dai.approve(daiJoin_, uint256(-1));
}
function _fromWad(address gemJoin, uint256 wad) internal view returns (uint256 amt) {
amt = wad / 10 ** (sub(18, GemJoinLike(gemJoin).dec()));
}
}
// Maker-Otc is MatchingMarket, which is the core contract of OasisDex
contract CalleeMakerOtcDai is CalleeMakerOtc {
constructor(address otc_, address clip_, address daiJoin_) public {
setUp(otc_, clip_, daiJoin_);
}
function clipperCall(
address sender, // Clipper Caller and Dai deliveryaddress
uint256 daiAmt, // Dai amount to payback[rad]
uint256 gemAmt, // Gem amount received [wad]
bytes calldata data // Extra data needed (gemJoin)
) external {
// Get address to send remaining DAI, gemJoin adapter and minProfit in DAI to make
(address to, address gemJoin, uint256 minProfit) = abi.decode(data, (address, address, uint256));
// Convert gem amount to token precision
gemAmt = _fromWad(gemJoin, gemAmt);
// Exit collateral to token version
GemJoinLike(gemJoin).exit(address(this), gemAmt);
// Approve otc to take gem
TokenLike gem = GemJoinLike(gemJoin).gem();
gem.approve(address(otc), gemAmt);
// Calculate amount of DAI to Join (as erc20 WAD value)
uint256 daiToJoin = divup(daiAmt, RAY);
// Do operation and get dai amount bought (checking the profit is achieved)
uint256 daiBought = otc.sellAllAmount(address(gem), gemAmt, address(dai), add(daiToJoin, minProfit));
// Although maker-otc reverts if order book is empty, this check is a sanity check for other exchnages
// Transfer any lingering gem to specified address
if (gem.balanceOf(address(this)) > 0) {
gem.transfer(to, gem.balanceOf(address(this)));
}
// Convert DAI bought to internal vat value of the msg.sneder of Clipper.take
daiJoin.join(sender, daiToJoin);
// Transfer remaining DAI to specified address
dai.transfer(to, dai.balanceOf(address(this)));
}
}
// Maker-Otc is MatchingMarket, which is the core contract of OasisDex
/* contract CalleeMakerOtcGem is CalleeMakerOtc {
constructor(address otc_, address clip_, address daiJoin_) public {
setUp(otc_, clip_, daiJoin_);
}
function clipperCall(
uint256 daiAmt, // Dai amount to payback[rad]
uint256 gemAmt, // Gem amount received [wad]
bytes calldata data // Extra data needed (gemJoin)
) external {
// Get address to send remaining Gem, gemJoin adapter and minProfit in Gem to make
(address to, address gemJoin, uint256 minProfit) = abi.decode(data, (address, address, uint256));
// Convert gem amount to token precision
gemAmt = _fromWad(gemJoin, gemAmt);
// Exit collateral to token version
GemJoinLike(gemJoin).exit(address(this), gemAmt);
// Approve otc to take gem
TokenLike gem = GemJoinLike(gemJoin).gem();
gem.approve(address(otc), gemAmt);
// Calculate amount of DAI to Join (as erc20 WAD value)
uint256 daiToJoin = daiAmt / RAY;
if (daiToJoin * RAY < daiAmt) {
daiToJoin = daiToJoin + 1;
}
// Do operation and get gem amount sold (checking the profit is achieved)
uint256 gemSold = otc.buyAllAmount(address(dai), daiToJoin, address(gem), gemAmt - minProfit);
// TODO: make sure daiToJoin is actually the amount received from buyAllAmount (due rounding)
// Convert DAI bought to internal vat value
daiJoin.join(address(this), daiToJoin);
// Transfer remaining gem to specified address
gem.transfer(to, gemAmt - gemSold);
}
} */ | Convert DAI bought to internal vat value of the msg.sneder of Clipper.take | daiJoin.join(sender, daiToJoin);
| 1,965,056 | [
1,
2723,
463,
18194,
800,
9540,
358,
2713,
17359,
460,
434,
326,
1234,
18,
8134,
329,
264,
434,
385,
3169,
457,
18,
22188,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3639,
5248,
77,
4572,
18,
5701,
12,
15330,
16,
5248,
77,
774,
4572,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/*
*visit: https://beerhouse.farm
*Telegram: https://t.me/BeerHousefarm
*Start : Block 10965437
*Bonus END: Block 11023037
*Bonus Multiplier: 3x
*Deployer: Omega Protocol Ltd.
*/
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/BeerToken.sol
pragma solidity 0.6.12;
// BeerToken with Governance.
contract BeerToken is ERC20("Beer Token", "BEER"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (BrewMaster).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @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), "BEER::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "BEER::delegateBySig: invalid nonce");
require(now <= expiry, "BEER::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "BEER::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying BEERs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "BEER::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// File: contracts/BrewMaster.sol
pragma solidity 0.6.12;
interface IMigratorChef {
function migrate(IERC20 token) external returns (IERC20);
}
contract BrewMaster is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of BEERs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accEggPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accEggPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. BEERs to distribute per block.
uint256 lastRewardBlock; // Last block number that BEERs distribution occurs.
uint256 accEggPerShare; // Accumulated BEERs per share, times 1e12. See below.
}
// The BEER TOKEN!
BeerToken public beer;
// Dev address.
address public devaddr;
// Block number when bonus BEER period ends.
uint256 public bonusEndBlock;
// BEER tokens created per block.
uint256 public beerPerBlock;
// Bonus muliplier for early beer makers.
uint256 public constant BONUS_MULTIPLIER = 3;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when BEER mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
BeerToken _beer,
address _devaddr,
uint256 _beerPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
beer = _beer;
devaddr = _devaddr;
beerPerBlock = _beerPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accEggPerShare: 0
}));
}
// Update the given pool's BEER allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending BEERs on frontend.
function pendingEgg(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accEggPerShare = pool.accEggPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 beerReward = multiplier.mul(beerPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accEggPerShare = accEggPerShare.add(beerReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accEggPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 beerReward = multiplier.mul(beerPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
beer.mint(devaddr, beerReward.div(10));
beer.mint(address(this), beerReward);
pool.accEggPerShare = pool.accEggPerShare.add(beerReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to BrewMaster for BEER allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt);
safeEggTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from BrewMaster.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt);
safeEggTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe beer transfer function, just in case if rounding error causes pool to not have enough BEERs.
function safeEggTransfer(address _to, uint256 _amount) internal {
uint256 beerBal = beer.balanceOf(address(this));
if (_amount > beerBal) {
beer.transfer(_to, beerBal);
} else {
beer.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: addy?");
devaddr = _devaddr;
}
} | BEER tokens created per block. | uint256 public beerPerBlock;
| 10,558,181 | [
1,
5948,
654,
2430,
2522,
1534,
1203,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
1071,
506,
264,
2173,
1768,
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 solidity ^0.5.0;
contract CoinFlip {
// ERC-20 standard
string public name = "CoinFlip";
string public symbol = "CF";
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer (
address indexed _from,
address indexed _to,
uint256 _value
);
event Approval (
address indexed _owner,
address indexed _spender,
uint256 _value
);
// State variables for coin flip functions
address payable public player1;
address payable public player2;
address payable public winner;
bytes32 public player1Commitment;
bool public player2Choice;
uint256 public expiration;
uint public pot;
uint minBet;
constructor() public {
minBet = 10 wei;
// Creator of contract will hold 1000000 tokens
balanceOf[msg.sender] = 1000000;
totalSupply = 1000000;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
balanceOf[msg.sender] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= balanceOf[_from]);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
}
function getPot() public view returns(uint) {
return pot;
}
function getWinner() public view returns(address payable) {
return winner;
}
function getPlayer1() public view returns(address payable) {
return player1;
}
function getPlayer2() public view returns(address payable) {
return player2;
}
function reset() public {
player1 = address(0);
player2 = address(0);
expiration = 0;
pot = 0;
}
function flipCoin(bool _bet, uint256 _nonce) public payable {
// Player 1 must bet at least the minimum bet
if(msg.value < minBet) {
revert("Must bet minimally 10 Wei");
}
player1 = msg.sender;
player1Commitment = keccak256(abi.encodePacked(_bet, _nonce));
pot += msg.value;
}
function takeBet(bool _bet) public payable {
// Only two players can play
if(player2 != address(0)) {
revert("There is already a Player 2, wait for next betting round");
}
// player 2 must bet at least the minimum bet
if(msg.value < minBet) {
revert("Must bet minimally 10 Wei");
}
// Player 2 is the caller of this function
player2 = msg.sender;
// Set player 2 choice to arg passed
player2Choice = _bet;
// Update the pot
pot += msg.value;
// Set expiration timer for player 1 to reveal commitment
expiration = now + 30 minutes;
}
// Called by player 1 to reveal his earlier bet
function reveal(bool _choice, uint256 _nonce) public payable {
//require(player2 != address(0));
if(now > expiration || player2 == address(0)) {
revert("The expiration has been exceeded or there is no Player 2");
}
// choice must be the same as his initial commitment
if (keccak256(abi.encodePacked(_choice, _nonce)) != player1Commitment) {
// if player 1 deviates from protocol, he loses his bet amount to player 2
address(player2).transfer(address(this).balance);
}
if (player2Choice == _choice) {
winner = player2;
address(player2).transfer(address(this).balance);
}
else {
winner = player1;
address(player1).transfer(address(this).balance);
}
// Reset all state variables before new game
player1 = address(0);
player2 = address(0);
expiration = 0;
pot = 0;
}
// player 1 can cancel the bet before player 2 calls takeBet
function cancel() public {
if(msg.sender != player1 || player2 != address(0)) {
revert("Only Player 1 can call cancel function or Player 2 has already entered bet");
}
// give player 1 his money back
address(msg.sender).transfer(address(this).balance);
}
// player 2 can call timeout on player 1 if player 1 refuses to call reveal()
function claimTimeout() public {
if(now < expiration) {
revert("Cannot claim until after expiration period");
}
address(player2).transfer(address(this).balance);
}
} | Player 1 must bet at least the minimum bet | function flipCoin(bool _bet, uint256 _nonce) public payable {
if(msg.value < minBet) {
revert("Must bet minimally 10 Wei");
}
player1 = msg.sender;
player1Commitment = keccak256(abi.encodePacked(_bet, _nonce));
pot += msg.value;
}
| 2,552,515 | [
1,
12148,
404,
1297,
2701,
622,
4520,
326,
5224,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
202,
915,
9668,
27055,
12,
6430,
389,
70,
278,
16,
2254,
5034,
389,
12824,
13,
1071,
8843,
429,
288,
203,
202,
565,
309,
12,
3576,
18,
1132,
411,
1131,
38,
278,
13,
288,
203,
202,
3639,
15226,
2932,
10136,
2701,
18172,
1230,
1728,
1660,
77,
8863,
203,
202,
565,
289,
203,
202,
202,
14872,
21,
273,
1234,
18,
15330,
31,
203,
202,
202,
14872,
21,
5580,
475,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
24899,
70,
278,
16,
389,
12824,
10019,
203,
202,
202,
13130,
1011,
1234,
18,
1132,
31,
203,
202,
97,
203,
202,
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
]
|
./full_match/4/0x33CC0d896932F63eB11C4bEBB6D76278c4AE78c8/sources/contracts/NekoDaruma.sol | Function to toggle the public mint | function toggleMint() public onlyOwner {
publicMint = !publicMint;
}
| 652,271 | [
1,
2083,
358,
10486,
326,
1071,
312,
474,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
10486,
49,
474,
1435,
1071,
1338,
5541,
288,
203,
565,
1071,
49,
474,
273,
401,
482,
49,
474,
31,
203,
225,
289,
203,
7010,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//Address: 0x5951924bb16e69bfe272491202ff3597a456af25
//Contract name: Asset
//Balance: 0 Ether
//Verification Date: 10/29/2017
//Transacion Count: 2
// CODE STARTS HERE
pragma solidity ^0.4.11;
/*
Token Contract with batch assignments
ERC-20 Token Standar Compliant - ConsenSys
Contract developer: Fares A. Akel C.
[email protected]
MIT PGP KEY ID: 078E41CB
*/
/**
* @title SafeMath by OpenZeppelin
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
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 admined { //This token contract is administered
address public admin; //Admin address is public
uint public lockThreshold; //Lock tiime is public
address public allowedAddr; //There can be an address that can use the token during a lock, its public
function admined() internal {
admin = msg.sender; //Set initial admin to contract creator
Admined(admin);
}
modifier onlyAdmin() { //A modifier to define admin-only functions
require(msg.sender == admin);
_;
}
modifier endOfLock() { //A modifier to lock transactions until finish of time (or being allowed)
require(now > lockThreshold || msg.sender == allowedAddr);
_;
}
function transferAdminship(address _newAdmin) onlyAdmin public { //Admin can be transfered
admin = _newAdmin;
TransferAdminship(admin);
}
function addAllowedToTransfer (address _allowedAddr) onlyAdmin public { //Here the special address that can transfer during a lock is set
allowedAddr = _allowedAddr;
AddAllowedToTransfer (allowedAddr);
}
function setLock(uint _timeInMins) onlyAdmin public { //Only the admin can set a lock on transfers
require(_timeInMins > 0);
uint mins = _timeInMins * 1 minutes;
lockThreshold = SafeMath.add(now,mins);
SetLock(lockThreshold);
}
//All admin actions have a log for public review
event SetLock(uint timeInMins);
event AddAllowedToTransfer (address allowedAddress);
event TransferAdminship(address newAdminister);
event Admined(address administer);
}
contract Token is admined {
uint256 public totalSupply;
mapping (address => uint256) balances; //Balances mapping
mapping (address => mapping (address => uint256)) allowed; //Allowance mapping
function balanceOf(address _owner) public constant returns (uint256 bal) {
return balances[_owner];
}
function transfer(address _to, uint256 _value) endOfLock public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value);
balances[_to] = SafeMath.add(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) endOfLock public returns (bool success) {
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value);
balances[_to] = SafeMath.add(balances[_to], _value);
balances[_from] = SafeMath.sub(balances[_from], _value);
allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) endOfLock public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function mintToken(address _target, uint256 _mintedAmount) onlyAdmin endOfLock public {
balances[_target] = SafeMath.add(balances[_target], _mintedAmount);
totalSupply = SafeMath.add(totalSupply, _mintedAmount);
Transfer(0, this, _mintedAmount);
Transfer(this, _target, _mintedAmount);
}
function burnToken(address _target, uint256 _burnedAmount) onlyAdmin endOfLock public {
balances[_target] = SafeMath.sub(balances[_target], _burnedAmount);
totalSupply = SafeMath.sub(totalSupply, _burnedAmount);
Burned(_target, _burnedAmount);
}
//This is an especial Admin-only function to make massive tokens assignments
function batch(address[] data,uint256 amount) onlyAdmin public { //It takes an array of addresses and an amount
require(balances[this] >= data.length*amount); //The contract must hold the needed tokens
for (uint i=0; i<data.length; i++) { //It moves over the array
address target = data[i]; //Take an address
balances[target] = SafeMath.add(balances[target], amount); //Add an amount to the target address
balances[this] = SafeMath.sub(balances[this], amount); //Sub that amount from the contract
allowed[this][msg.sender] = SafeMath.sub(allowed[this][msg.sender], amount); //Sub allowance from the contract creator over the contract
Transfer(this, target, amount); //log every transfer
}
}
//Events to log transactions
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burned(address indexed _target, uint256 _value);
}
contract Asset is admined, Token {
string public name;
uint8 public decimals = 18;
string public symbol;
string public version = '0.1';
uint256 initialAmount = 80000000000000000000000000; //80Million tonkens to be created
function Asset(
string _tokenName,
string _tokenSymbol
) public {
balances[this] = 79920000000000000000000000; // Initial 99.9% stay on the contract
balances[0xFAB6368b0F7be60c573a6562d82469B5ED9e7eE6] = 80000000000000000000000; //Initial 0.1% for contract writer
allowed[this][msg.sender] = 79920000000000000000000000; //Set allowance for the contract creator/administer over the contract holded amount
totalSupply = initialAmount; //Total supply is the initial amount at Asset
name = _tokenName; //Name set on deployment
symbol = _tokenSymbol; //Simbol set on deployment
Transfer(0, this, initialAmount);
Transfer(this, 0xFAB6368b0F7be60c573a6562d82469B5ED9e7eE6, 80000000000000000000000);
Approval(this, msg.sender, 79920000000000000000000000);
}
function() {
revert();
}
}
| Total supply is the initial amount at Asset
| totalSupply = initialAmount; | 7,237,448 | [
1,
5269,
14467,
353,
326,
2172,
3844,
622,
10494,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2078,
3088,
1283,
273,
2172,
6275,
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
]
|
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "../erc1820/ERC1820Client.sol";
import "../erc1820/ERC1820Implementer.sol";
import "../extensions/userExtensions/IERC1400TokensRecipient.sol";
import "../interface/IERC20HoldableToken.sol";
import "../interface/IHoldableERC1400TokenExtension.sol";
import "../IERC1400.sol";
import '../helpers/Errors.sol';
/**
* @title Swaps
* @dev Delivery-Vs-Payment contract for investor-to-investor token trades.
* @dev Intended usage:
* The purpose of the contract is to allow secure token transfers/exchanges between 2 stakeholders (called holder1 and holder2).
* From now on, an operation in the Swaps smart contract (transfer/exchange) is called a trade.
* Depending on the type of trade, one/multiple token transfers will be executed.
*
* The simplified workflow is the following:
* 1) A trade request is created in the Swaps smart contract, it specifies:
* - The token holder(s) involved in the trade
* - The trade executer (optional)
* - An expiration date
* - Details on the first token (address, requested amount, standard)
* - Details on the second token (address, requested amount, standard)
* - Whether the tokens need to be escrowed in the Swaps contract or not
* - The current status of the trade (pending / executed / forced / cancelled)
* 2) The trade is accepted by both token holders
* 3) [OPTIONAL] The trade is approved by token controllers (only if requested by tokens controllers)
* 4) The trade is executed (either by the executer in case the executer is specified, or by anyone)
*
* STANDARD-AGNOSTIC:
* The Swaps smart contract is standard-agnostic, it supports ETH, ERC20, ERC721, ERC1400.
* The advantage of using an ERC1400 token is to leverages its hook property, thus requiring ONE single
* transaction (operatorTransferByPartition()) to send tokens to the Swaps smart contract instead of TWO
* with the ERC20 token standard (approve() + transferFrom()).
*
* OFF-CHAIN PAYMENT:
* The contract can be used as escrow contract while waiting for an off-chain payment.
* Once payment is received off-chain, the token sender realeases the tokens escrowed in
* the Swaps contract to deliver them to the recipient.
*
* ESCROW VS SWAP MODE:
* In case escrow mode is selected, tokens need to be escrowed in Swaps smart contract
* before the trade can occur.
* In case swap mode is selected, tokens are not escrowed in the Swaps. Instead, the Swaps
* contract is only allowed to transfer tokens ON BEHALF of their owners. When trade is
* executed, an atomic token swap occurs.
*
* EXPIRATION DATE:
* The trade can be cancelled by both parties in case expiration date is passed.
*
* CLAIMS:
* The executer has the ability to force or cancel the trade.
* In case of disagreement/missing payment, both parties can contact the "executer"
* of the trade to deposit a claim and solve the issue.
*
* MARKETPLACE:
* The contract can be used as a token marketplace. Indeed, when trades are created
* without specifying the recipient address, anyone can purchase them by sending
* the requested payment in exchange.
*
* PRICE ORACLES:
* When price oracles are defined, those can define the price at which trades need to be executed.
* This feature is particularly useful for assets with NAV (net asset value).
*
*/
contract Swaps is Ownable, ERC1820Client, IERC1400TokensRecipient, ERC1820Implementer {
string constant internal DELIVERY_VS_PAYMENT = "DeliveryVsPayment";
string constant internal ERC1400_TOKENS_RECIPIENT = "ERC1400TokensRecipient";
uint256 constant internal SECONDS_IN_MONTH = 86400 * 30;
uint256 constant internal SECONDS_IN_WEEK = 86400 * 7;
bytes32 constant internal TRADE_PROPOSAL_FLAG = 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc;
bytes32 constant internal TRADE_ACCEPTANCE_FLAG = 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd;
bytes32 constant internal BYPASS_ACTION_FLAG = 0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;
bytes32 constant internal ALL_PARTITIONS = 0x0000000000000000000000000000000000000000000000000000000000000000;
enum Standard {OffChain, ETH, ERC20, ERC721, ERC1400}
enum State {Undefined, Pending, Executed, Forced, Cancelled}
enum TradeType {Allowance, Hold, Escrow}
enum Holder {Holder1, Holder2}
string internal constant ERC1400_TOKENS_VALIDATOR = "ERC1400TokensValidator";
/**
@dev Include token events so they can be parsed by Ethereum clients from the settlement transactions.
*/
// Holdable
event ExecutedHold(
address indexed token,
bytes32 indexed holdId,
bytes32 lockPreimage,
address recipient
);
// ERC20
event Transfer(address indexed from, address indexed to, uint256 tokens);
// ERC1400
event TransferByPartition(
bytes32 indexed fromPartition,
address operator,
address indexed from,
address indexed to,
uint256 value,
bytes data,
bytes operatorData
);
event CreateNote(
address indexed owner,
bytes32 indexed noteHash,
bytes metadata
);
event DestroyNote(address indexed owner, bytes32 indexed noteHash);
struct UserTradeData {
address tokenAddress;
uint256 tokenValue;
bytes32 tokenId;
Standard tokenStandard;
bool accepted;
bool approved;
TradeType tradeType;
address receiver;
}
/**
* @dev Input data for the requestTrade function
* @param holder1 Address of the first token holder.
* @param holder2 Address of the second token holder.
* @param executer Executer of the trade.
* @param expirationDate Expiration date of the trade.
* @param tokenAddress1 Address of the first token smart contract.
* @param tokenValue1 Amount of tokens to send for the first token.
* @param tokenId1 ERC721ID/holdId/partition of the first token.
* @param tokenStandard1 Standard of the first token (ETH | ERC20 | ERC721 | ERC1400).
* @param tokenAddress2 Address of the second token smart contract.
* @param tokenValue2 Amount of tokens to send for the second token.
* @param tokenId2 ERC721ID/holdId/partition of the second token.
* @param tokenStandard2 Standard of the second token (ETH | ERC20 | ERC721 | ERC1400).
* @param tradeType Indicates whether or not tokens shall be escrowed in the Swaps contract before the trade.
*/
struct TradeRequestInput {
address holder1;
address holder2;
address executer; // Set to address(0) if no executer is required for the trade
uint256 expirationDate;
address tokenAddress1;
uint256 tokenValue1;
bytes32 tokenId1;
Standard tokenStandard1;
address receiver1;
address tokenAddress2; // Set to address(0) if no token is expected in return (for example in case of an off-chain payment)
uint256 tokenValue2;
bytes32 tokenId2;
Standard tokenStandard2;
address receiver2;
TradeType tradeType1;
TradeType tradeType2;
uint256 settlementDate;
}
struct Trade {
address holder1;
address holder2;
address executer;
uint256 expirationDate;
uint256 settlementDate;
UserTradeData userTradeData1;
UserTradeData userTradeData2;
State state;
}
// Index of most recent trade request.
uint256 internal _index;
// Mapping from index to trade requests.
mapping(uint256 => Trade) internal _trades;
// Mapping from token to price oracles.
mapping(address => address[]) internal _priceOracles;
// Mapping from (token, operator) to price oracle status.
mapping(address => mapping(address => bool)) internal _isPriceOracle;
// Mapping from (token1, token2) to price ownership.
mapping(address => mapping(address => bool)) internal _priceOwnership;
// Mapping from (token1, token2, tokenId1, tokenId2) to price.
mapping(address => mapping (address => mapping (bytes32 => mapping (bytes32 => uint256)))) internal _tokenUnitPricesByPartition;
// Indicate whether Swaps smart contract is owned or not (for instance by an exchange, etc.).
bool internal _ownedContract;
// Array of trade execcuters.
address[] internal _tradeExecuters;
// Mapping from operator to trade executer status.
mapping(address => bool) internal _isTradeExecuter;
// Mapping from token to token controllers.
mapping(address => address[]) internal _tokenControllers;
// Mapping from (token, operator) to token controller status.
mapping(address => mapping(address => bool)) internal _isTokenController;
// Mapping from token to variable price start date.
mapping(address => uint256) internal _variablePriceStartDate;
/**
* @dev Modifier to verify if sender is a token controller.
*/
modifier onlyTokenController(address tokenAddress) {
require(
_msgSender() == Ownable(tokenAddress).owner() ||
_isTokenController[tokenAddress][_msgSender()],
Errors.SW_SENDER_NOT_TOKEN_CONTROLLER
);
_;
}
/**
* @dev Modifier to verify if sender is a price oracle.
*/
modifier onlyPriceOracle(address tokenAddress) {
require(_checkPriceOracle(tokenAddress, _msgSender()), Errors.SW_SENDER_NOT_PRICE_ORACLE);
_;
}
/**
* [Swaps CONSTRUCTOR]
* @dev Initialize Swaps + register
* the contract implementation in ERC1820Registry.
*/
constructor(bool owned) {
ERC1820Implementer._setInterface(DELIVERY_VS_PAYMENT);
ERC1820Implementer._setInterface(ERC1400_TOKENS_RECIPIENT);
setInterfaceImplementation(ERC1400_TOKENS_RECIPIENT, address(this));
_ownedContract = owned;
if(_ownedContract) {
address[] memory initialTradeExecuters = new address[] (1);
initialTradeExecuters[0] = _msgSender();
_setTradeExecuters(initialTradeExecuters);
}
}
/**
* [ERC1400TokensRecipient INTERFACE (1/2)]
* @dev Indicate whether or not the Swaps contract can receive the tokens or not. [USED FOR ERC1400 TOKENS ONLY]
* @param data Information attached to the token transfer.
* @param operatorData Information attached to the Swaps transfer, by the operator.
* @return 'true' if the Swaps contract can receive the tokens, 'false' if not.
*/
function canReceive(bytes calldata, bytes32, address, address, address, uint, bytes calldata data, bytes calldata operatorData) external override view returns(bool) {
return(_canReceive(data, operatorData));
}
/**
* [ERC1400TokensRecipient INTERFACE (2/2)]
* @dev Hook function executed when tokens are sent to the Swaps contract. [USED FOR ERC1400 TOKENS ONLY]
* @param partition Name of the partition.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the token transfer.
* @param operatorData Information attached to the Swaps transfer, by the operator.
*/
function tokensReceived(bytes calldata, bytes32 partition, address, address from, address to, uint value, bytes memory data, bytes calldata operatorData) external override {
require(interfaceAddr(_msgSender(), "ERC1400Token") == _msgSender(), Errors.TR_SENDER_NOT_ERC1400_TOKEN); // funds locked (lockup period)
require(to == address(this), Errors.TR_TO_ADDRESS_NOT_ME); // 0x50 transfer failure
require(_canReceive(data, operatorData), Errors.TR_INVALID_RECEIVER); // 0x57 invalid receiver
bytes32 flag = _getTradeFlag(data);
if(flag == TRADE_PROPOSAL_FLAG) {
address recipient;
address executor;
uint256 expirationDate;
uint256 settlementDate;
assembly {
recipient:= mload(add(data, 64))
executor:= mload(add(data, 96))
expirationDate:= mload(add(data, 128))
settlementDate:= mload(add(data, 160))
}
// Token data: < 1: address > < 2: amount > < 3: id/partition > < 4: standard > < 5: accepted > < 6: approved >
UserTradeData memory _tradeData1 = UserTradeData(_msgSender(), value, partition, Standard.ERC1400, true, false, TradeType.Escrow, address(0));
UserTradeData memory _tokenData2 = _getTradeTokenData(data);
_requestTrade(
from,
recipient,
executor,
expirationDate,
settlementDate,
_tradeData1,
_tokenData2
);
} else if (flag == TRADE_ACCEPTANCE_FLAG) {
uint256 index;
bytes32 preimage = bytes32(0);
assembly {
index:= mload(add(data, 64))
}
if (data.length == 96) {
//This field is optional
//If the data's length does not include the preimage
//then return an empty preimage
//canReceive accepts both data lengths
assembly {
preimage:= mload(add(data, 96))
}
}
Trade storage trade = _trades[index];
UserTradeData memory selectedUserTradeData = (from == trade.holder1) ? trade.userTradeData1 : trade.userTradeData2;
require(_msgSender() == selectedUserTradeData.tokenAddress, Errors.SW_WRONG_TOKEN_SENT);
require(partition == selectedUserTradeData.tokenId, Errors.SW_TOKENS_IN_WRONG_PARTITION);
require(Standard.ERC1400 == selectedUserTradeData.tokenStandard, Errors.SW_TOKEN_INCORRECT_STANDARD);
_acceptTrade(index, from, 0, value, preimage);
}
}
/**
* @dev Create a new trade request in the Swaps smart contract.
* @param inputData The input for this function
*/
function requestTrade(TradeRequestInput calldata inputData, bytes32 preimage)
external
payable
{
_requestTrade(
inputData.holder1,
inputData.holder2,
inputData.executer,
inputData.expirationDate,
inputData.settlementDate,
UserTradeData(inputData.tokenAddress1, inputData.tokenValue1, inputData.tokenId1, inputData.tokenStandard1, false, false, inputData.tradeType1, inputData.receiver1),
UserTradeData(inputData.tokenAddress2, inputData.tokenValue2, inputData.tokenId2, inputData.tokenStandard2, false, false, inputData.tradeType2, inputData.receiver2)
);
if(_msgSender() == inputData.holder1 || _msgSender() == inputData.holder2) {
_acceptTrade(_index, _msgSender(), msg.value, 0, preimage);
}
}
/**
* @dev Create a new trade request in the Swaps smart contract.
* @param holder1 Address of the first token holder.
* @param holder2 Address of the second token holder.
* @param executer Executer of the trade.
* @param expirationDate Expiration date of the trade.
* @param userTradeData1 Encoded pack of variables for token1 (address, amount, id/partition, standard, accepted, approved).
* @param userTradeData2 Encoded pack of variables for token2 (address, amount, id/partition, standard, accepted, approved).
*/
function _requestTrade(
address holder1,
address holder2,
address executer, // Set to address(0) if no executer is required for the trade
uint256 expirationDate,
uint256 settlementDate,
UserTradeData memory userTradeData1,
UserTradeData memory userTradeData2
)
internal
{
if(userTradeData1.tokenStandard == Standard.ETH) {
require(userTradeData1.tradeType == TradeType.Escrow, Errors.SW_ETH_TRADE_REQUIRES_ESCROW);
}
if(userTradeData2.tokenStandard == Standard.ETH) {
require(userTradeData2.tradeType == TradeType.Escrow, Errors.SW_ETH_TRADE_REQUIRES_ESCROW);
}
if (userTradeData1.tradeType == TradeType.Hold) {
require(userTradeData1.tokenStandard == Standard.ERC20 || userTradeData1.tokenStandard == Standard.ERC1400, Errors.SW_TOKEN_STANDARD_NOT_SUPPORTED);
require(userTradeData1.tokenId != bytes32(0), Errors.SW_NO_HOLDID_GIVEN);
}
if (userTradeData2.tradeType == TradeType.Hold) {
require(userTradeData2.tokenStandard == Standard.ERC20 || userTradeData2.tokenStandard == Standard.ERC1400, Errors.SW_TOKEN_STANDARD_NOT_SUPPORTED);
require(userTradeData2.tokenId != bytes32(0), Errors.SW_NO_HOLDID_GIVEN);
}
if(_ownedContract) {
require(_isTradeExecuter[executer], Errors.SW_TRADE_EXECUTER_NOT_ALLOWED);
}
require(holder1 != address(0), Errors.ZERO_ADDRESS_NOT_ALLOWED);
_index++;
uint256 _expirationDate = (expirationDate > block.timestamp) ? expirationDate : (block.timestamp + SECONDS_IN_MONTH);
_trades[_index] = Trade({
holder1: holder1,
holder2: holder2,
executer: executer,
expirationDate: _expirationDate,
settlementDate: settlementDate,
userTradeData1: userTradeData1,
userTradeData2: userTradeData2,
state: State.Pending
});
}
/**
* @dev Accept a given trade (+ potentially escrow tokens).
* @param index Index of the trade to be accepted.
*/
function acceptTrade(uint256 index, bytes32 preimage) external payable {
_acceptTrade(index, _msgSender(), msg.value, 0, preimage);
}
/**
* @dev Accept a given trade (+ potentially escrow tokens).
* @param index Index of the trade to be accepted.
* @param sender Message sender
* @param ethValue Value sent (only used for ETH)
* @param erc1400TokenValue Value sent (only used for ERC1400)
*/
function _acceptTrade(uint256 index, address sender, uint256 ethValue, uint256 erc1400TokenValue, bytes32 preimage) internal {
Trade storage trade = _trades[index];
require(trade.state == State.Pending, Errors.SW_TRADE_NOT_PENDING);
address recipientHolder;
if(sender == trade.holder1) {
recipientHolder = trade.holder2;
} else if(sender == trade.holder2) {
recipientHolder = trade.holder1;
} else if(trade.holder2 == address(0)) {
trade.holder2 = sender;
recipientHolder = trade.holder1;
} else {
revert(Errors.SW_ONLY_REGISTERED_HOLDERS);
}
UserTradeData memory selectedUserTradeData = (sender == trade.holder1) ? trade.userTradeData1 : trade.userTradeData2;
require(!selectedUserTradeData.accepted, Errors.SW_TRADE_ALREADY_ACCEPTED);
if(selectedUserTradeData.tradeType == TradeType.Escrow) {
if(selectedUserTradeData.tokenStandard == Standard.ETH) {
require(ethValue == selectedUserTradeData.tokenValue, Errors.SW_ETH_AMOUNT_INCORRECT);
} else if(selectedUserTradeData.tokenStandard == Standard.ERC20) {
IERC20(selectedUserTradeData.tokenAddress).transferFrom(sender, address(this), selectedUserTradeData.tokenValue);
} else if(selectedUserTradeData.tokenStandard == Standard.ERC721) {
IERC721(selectedUserTradeData.tokenAddress).transferFrom(sender, address(this), uint256(selectedUserTradeData.tokenId));
} else if((selectedUserTradeData.tokenStandard == Standard.ERC1400) && erc1400TokenValue == 0){
IERC1400(selectedUserTradeData.tokenAddress).operatorTransferByPartition(selectedUserTradeData.tokenId, sender, address(this), selectedUserTradeData.tokenValue, abi.encodePacked(BYPASS_ACTION_FLAG), abi.encodePacked(BYPASS_ACTION_FLAG));
} else if((selectedUserTradeData.tokenStandard == Standard.ERC1400) && erc1400TokenValue != 0){
require(erc1400TokenValue == selectedUserTradeData.tokenValue, Errors.SW_TOKEN_AMOUNT_INCORRECT);
}
} else if (selectedUserTradeData.tradeType == TradeType.Hold) {
require(_holdExists(sender, recipientHolder, selectedUserTradeData), Errors.SW_HOLD_DOESNT_EXIST);
} else { // trade.tradeType == TradeType.Allowance
require(_allowanceIsProvided(sender, selectedUserTradeData), Errors.SW_ALLOWANCE_NOT_GIVEN);
}
if(sender == trade.holder1) {
trade.userTradeData1.accepted = true;
} else {
trade.userTradeData2.accepted = true;
}
bool settlementDatePassed = block.timestamp >= trade.settlementDate;
bool tradeApproved = getTradeApprovalStatus(index);
//Execute both holds of a trade if the following conditions are met
//* There is no executer set. Only the executer should execute transactions if one is defined
//* Both trade types are holds
//* The trade is approved. Token controllers must pre-approve this trade. This is also true if the token has no token controllers
//* If both holds exist according to _holdExists
//* If the current block timestamp is after the settlement date
if (settlementDatePassed && trade.executer == address(0) && trade.userTradeData1.tradeType == TradeType.Hold && trade.userTradeData2.tradeType == TradeType.Hold && tradeApproved) {
//we know selectedUserTradeData has a hold that exists, so check the other one
UserTradeData memory otherUserTradeData = (sender == trade.holder1) ? trade.userTradeData2 : trade.userTradeData1;
if (_holdExists(recipientHolder, sender, otherUserTradeData)) {
//If both holds exist, then mark both sides of trade as accepted
//Next if will execute trade
trade.userTradeData1.accepted = true;
trade.userTradeData2.accepted = true;
}
}
if(
trade.executer == address(0) && getTradeAcceptanceStatus(index) && tradeApproved && settlementDatePassed) {
_executeTrade(index, preimage);
}
}
/**
* @dev Verify if a trade has been accepted by the token holders.
*
* The trade needs to be accepted by both parties (token holders) before it gets executed.
*
* @param index Index of the trade to be accepted.
*/
function getTradeAcceptanceStatus(uint256 index) public view returns(bool) {
Trade storage trade = _trades[index];
if(trade.state == State.Pending) {
if(trade.userTradeData1.tradeType == TradeType.Allowance && !_allowanceIsProvided(trade.holder1, trade.userTradeData1)) {
return false;
}
if(trade.userTradeData2.tradeType == TradeType.Allowance && !_allowanceIsProvided(trade.holder2, trade.userTradeData2)) {
return false;
}
}
return(trade.userTradeData1.accepted && trade.userTradeData2.accepted);
}
/**
* @dev Verify if a token allowance has been provided in token smart contract.
*
* @param sender Address of the sender.
* @param userTradeData Encoded pack of variables for the token (address, amount, id/partition, standard, accepted, approved).
*/
function _allowanceIsProvided(address sender, UserTradeData memory userTradeData) internal view returns(bool) {
address tokenAddress = userTradeData.tokenAddress;
uint256 tokenValue = userTradeData.tokenValue;
bytes32 tokenId = userTradeData.tokenId;
Standard tokenStandard = userTradeData.tokenStandard;
if(tokenStandard == Standard.ERC20) {
return(IERC20(tokenAddress).allowance(sender, address(this)) >= tokenValue);
} else if(tokenStandard == Standard.ERC721) {
return(IERC721(tokenAddress).getApproved(uint256(tokenId)) == address(this));
} else if(tokenStandard == Standard.ERC1400){
return(IERC1400(tokenAddress).allowanceByPartition(tokenId, sender, address(this)) >= tokenValue);
}
return true;
}
function approveTrade(uint256 index, bool approved) external {
approveTradeWithPreimage(index, approved, 0);
}
/**
* @dev Approve a trade (if the tokens involved in the trade are controlled)
*
* This function can only be called by a token controller of one of the tokens involved in the trade.
*
* Indeed, when a token smart contract is controlled by an owner, the owner can decide to open the
* secondary market by:
* - Allowlisting the Swaps smart contract
* - Setting "token controllers" in the Swaps smart contract, in order to approve all the trades made with his token
*
* @param index Index of the trade to be executed.
* @param approved 'true' if trade is approved, 'false' if not.
*/
function approveTradeWithPreimage(uint256 index, bool approved, bytes32 preimage) public {
Trade storage trade = _trades[index];
require(trade.state == State.Pending, Errors.SW_TRADE_ALREADY_ACCEPTED);
require(_isTokenController[trade.userTradeData1.tokenAddress][_msgSender()] || _isTokenController[trade.userTradeData2.tokenAddress][_msgSender()], Errors.SW_SENDER_NOT_TOKEN_CONTROLLER);
if(_isTokenController[trade.userTradeData1.tokenAddress][_msgSender()]) {
trade.userTradeData1.approved = approved;
}
if(_isTokenController[trade.userTradeData2.tokenAddress][_msgSender()]) {
trade.userTradeData2.approved = approved;
}
if(trade.executer == address(0) && getTradeAcceptanceStatus(index) && getTradeApprovalStatus(index)) {
_executeTrade(index, preimage);
}
}
/**
* @dev Verify if a trade has been approved by the token controllers.
*
* In case a given token has token controllers, those need to validate the trade before it gets executed.
*
* @param index Index of the trade to be approved.
*/
function getTradeApprovalStatus(uint256 index) public view returns(bool) {
Trade storage trade = _trades[index];
if(_tokenControllers[trade.userTradeData1.tokenAddress].length != 0 && !trade.userTradeData1.approved) {
return false;
}
if(_tokenControllers[trade.userTradeData2.tokenAddress].length != 0 && !trade.userTradeData2.approved) {
return false;
}
return true;
}
function executeTrade(uint256 index) external {
executeTradeWithPreimage(index, 0);
}
/**
* @dev Execute a trade in the Swaps contract if possible (e.g. if tokens have been esccrowed, in case it is required).
*
* This function can only be called by the executer specified at trade creation.
* If no executer is specified, the trade can be launched by anyone.
*
* @param index Index of the trade to be executed.
*/
function executeTradeWithPreimage(uint256 index, bytes32 preimage) public {
Trade storage trade = _trades[index];
require(trade.state == State.Pending, Errors.SW_TRADE_NOT_PENDING);
if(trade.executer != address(0)) {
require(_msgSender() == trade.executer, Errors.SW_SENDER_NOT_EXECUTER);
}
require(block.timestamp >= trade.settlementDate, Errors.SW_BEFORE_SETTLEMENT_DATE);
require(getTradeAcceptanceStatus(index), Errors.SW_TRADE_NOT_FULLY_ACCEPTED);
require(getTradeApprovalStatus(index), Errors.SW_TRADE_NOT_FULLY_APPROVED);
_executeTrade(index, preimage);
}
/**
* @dev Execute a trade in the Swaps contract if possible (e.g. if tokens have been esccrowed, in case it is required).
* @param index Index of the trade to be executed.
*/
function _executeTrade(uint256 index, bytes32 preimage) internal {
Trade storage trade = _trades[index];
uint256 price = getPrice(index);
uint256 tokenValue1 = trade.userTradeData1.tokenValue;
uint256 tokenValue2 = trade.userTradeData2.tokenValue;
if(price == tokenValue2) {
_transferUsersTokens(index, Holder.Holder1, tokenValue1, false, preimage);
_transferUsersTokens(index, Holder.Holder2, tokenValue2, false, preimage);
} else {
//Holds cannot move a specific amount of tokens
//So require that if the price is less than the value
//that the trade is not a hold trade
require(price <= tokenValue2 && trade.userTradeData2.tradeType != TradeType.Hold, Errors.SW_PRICE_HIGHER_THAN_AMOUNT);
_transferUsersTokens(index, Holder.Holder1, tokenValue1, false, preimage);
_transferUsersTokens(index, Holder.Holder2, price, false, preimage);
if(trade.userTradeData2.tradeType == TradeType.Escrow) {
_transferUsersTokens(index, Holder.Holder2, tokenValue2 - price, true, preimage);
}
}
trade.state = State.Executed;
}
function forceTrade(uint256 index) external {
forceTradeWithPreimage(index, 0);
}
/**
* @dev Force a trade execution in the Swaps contract by transferring tokens back to their target recipients.
* @param index Index of the trade to be forced.
*/
function forceTradeWithPreimage(uint256 index, bytes32 preimage) public {
Trade storage trade = _trades[index];
require(trade.state == State.Pending, Errors.SW_TRADE_NOT_PENDING);
address tokenAddress1 = trade.userTradeData1.tokenAddress;
uint256 tokenValue1 = trade.userTradeData1.tokenValue;
bool accepted1 = trade.userTradeData1.accepted;
address tokenAddress2 = trade.userTradeData2.tokenAddress;
uint256 tokenValue2 = trade.userTradeData2.tokenValue;
bool accepted2 = trade.userTradeData2.accepted;
require(!(accepted1 && accepted2), Errors.SW_EXECUTE_TRADE_POSSIBLE);
require(_tokenControllers[tokenAddress1].length == 0 && _tokenControllers[tokenAddress2].length == 0, "Trade can not be forced if tokens have controllers");
if(trade.executer != address(0)) {
require(_msgSender() == trade.executer, Errors.SW_ONLY_EXECUTER_CAN_FORCE_TRADE);
} else if(accepted1) {
require(_msgSender() == trade.holder1, Errors.SW_SENDER_CANT_FORCE_TRADE);
} else if(accepted2) {
require(_msgSender() == trade.holder2, Errors.SW_SENDER_CANT_FORCE_TRADE);
} else {
revert(Errors.SW_FORCE_TRADE_NOT_POSSIBLE_NO_TOKENS);
}
if(accepted1) {
_transferUsersTokens(index, Holder.Holder1, tokenValue1, false, preimage);
}
if(accepted2) {
_transferUsersTokens(index, Holder.Holder2, tokenValue2, false, preimage);
}
trade.state = State.Forced;
}
/**
* @dev Cancel a trade execution in the Swaps contract by transferring tokens back to their initial owners.
* @param index Index of the trade to be cancelled.
*/
function cancelTrade(uint256 index) external {
Trade storage trade = _trades[index];
require(trade.state == State.Pending, Errors.SW_TRADE_NOT_PENDING);
uint256 tokenValue1 = trade.userTradeData1.tokenValue;
bool accepted1 = trade.userTradeData1.accepted;
uint256 tokenValue2 = trade.userTradeData2.tokenValue;
bool accepted2 = trade.userTradeData2.accepted;
if(accepted1 && accepted2) {
require(_msgSender() == trade.executer || (block.timestamp >= trade.expirationDate && (_msgSender() == trade.holder1 || _msgSender() == trade.holder2) ), Errors.SW_SENDER_CANT_CANCEL_TRADE_0);
if(trade.userTradeData1.tradeType == TradeType.Escrow) {
_transferUsersTokens(index, Holder.Holder1, tokenValue1, true, bytes32(0));
}
if(trade.userTradeData2.tradeType == TradeType.Escrow) {
_transferUsersTokens(index, Holder.Holder2, tokenValue2, true, bytes32(0));
}
} else if(accepted1) {
require(_msgSender() == trade.executer || (block.timestamp >= trade.expirationDate && _msgSender() == trade.holder1), Errors.SW_SENDER_CANT_CANCEL_TRADE_1);
if(trade.userTradeData1.tradeType == TradeType.Escrow) {
_transferUsersTokens(index, Holder.Holder1, tokenValue1, true, bytes32(0));
}
} else if(accepted2) {
require(_msgSender() == trade.executer || (block.timestamp >= trade.expirationDate && _msgSender() == trade.holder2), Errors.SW_SENDER_CANT_CANCEL_TRADE_2);
if(trade.userTradeData2.tradeType == TradeType.Escrow) {
_transferUsersTokens(index, Holder.Holder2, tokenValue2, true, bytes32(0));
}
} else {
require(_msgSender() == trade.executer || _msgSender() == trade.holder1 || _msgSender() == trade.holder2, Errors.SW_SENDER_CANT_CANCEL_TRADE_3);
}
trade.state = State.Cancelled;
}
function _transferUsersTokens(uint256 index, Holder holder, uint256 value, bool revertTransfer, bytes32 preimage) internal {
Trade storage trade = _trades[index];
UserTradeData memory senderUserTradeData = (holder == Holder.Holder1) ? trade.userTradeData1 : trade.userTradeData2;
TradeType tokenTradeType = senderUserTradeData.tradeType;
if (tokenTradeType == TradeType.Hold) {
_executeHoldOnUsersTokens(index, holder, value, revertTransfer, preimage);
} else {
_executeTransferOnUsersTokens(index, holder, value, revertTransfer);
}
}
function _executeHoldOnUsersTokens(uint256 index, Holder holder, uint256, bool, bytes32 preimage) internal {
Trade storage trade = _trades[index];
address sender = (holder == Holder.Holder1) ? trade.holder1 : trade.holder2;
address recipient = (holder == Holder.Holder1) ? trade.holder2 : trade.holder1;
UserTradeData memory senderUserTradeData = (holder == Holder.Holder1) ? trade.userTradeData1 : trade.userTradeData2;
require(block.timestamp <= trade.expirationDate, Errors.SW_TRADE_EXPIRED);
address tokenAddress = senderUserTradeData.tokenAddress;
bytes32 tokenId = senderUserTradeData.tokenId;
Standard tokenStandard = senderUserTradeData.tokenStandard;
require(tokenStandard == Standard.ERC20 || tokenStandard == Standard.ERC1400, Errors.SW_TOKEN_STANDARD_NOT_SUPPORTED);
require(_holdExists(sender, recipient, senderUserTradeData), Errors.SW_HOLD_DOESNT_EXIST);
_executeHold(tokenAddress, tokenId, tokenStandard, preimage, recipient);
}
/**
* @dev Internal function to transfer tokens to their recipient by taking the token standard into account.
* @param index Index of the trade the token transfer is execcuted for.
* @param holder Sender of the tokens (currently owning the tokens).
* @param value Amount of tokens to send.
* @param revertTransfer If set to true + trade has been accepted, tokens need to be sent back to their initial owners instead of sent to the target recipient.
*/
function _executeTransferOnUsersTokens(uint256 index, Holder holder, uint256 value, bool revertTransfer) internal {
Trade storage trade = _trades[index];
UserTradeData storage senderUserTradeData = (holder == Holder.Holder1) ? trade.userTradeData1 : trade.userTradeData2;
UserTradeData storage recipientUserTradeData = (holder == Holder.Holder1) ? trade.userTradeData2 : trade.userTradeData1;
address sender = (holder == Holder.Holder1) ? trade.holder1 : trade.holder2;
address recipient = recipientUserTradeData.receiver;
if (recipient == address(0)) {
recipient = (holder == Holder.Holder1) ? trade.holder2 : trade.holder1;
}
address tokenAddress = senderUserTradeData.tokenAddress;
bytes32 tokenId = senderUserTradeData.tokenId;
Standard tokenStandard = senderUserTradeData.tokenStandard;
address currentHolder = sender;
if(senderUserTradeData.tradeType == TradeType.Escrow) {
currentHolder = address(this);
}
if(revertTransfer) {
recipient = sender;
} else {
require(block.timestamp <= trade.expirationDate, Errors.SW_TRADE_EXPIRED);
}
if(tokenStandard == Standard.ETH) {
address payable payableRecipient = payable(recipient);
payableRecipient.transfer(value);
} else if(tokenStandard == Standard.ERC20) {
if(currentHolder == address(this)) {
IERC20(tokenAddress).transfer(recipient, value);
} else {
IERC20(tokenAddress).transferFrom(currentHolder, recipient, value);
}
} else if(tokenStandard == Standard.ERC721) {
IERC721(tokenAddress).transferFrom(currentHolder, recipient, uint256(tokenId));
} else if(tokenStandard == Standard.ERC1400) {
IERC1400(tokenAddress).operatorTransferByPartition(tokenId, currentHolder, recipient, value, "", "");
}
}
function _executeHold(
address token,
bytes32 tokenHoldId,
Standard tokenStandard,
bytes32 preimage,
address tokenRecipient
) internal {
// Token 1
if (tokenStandard == Standard.ERC20) {
require(token != address(0), Errors.ZERO_ADDRESS_NOT_ALLOWED);
IERC20HoldableToken(token).executeHold(tokenHoldId, preimage);
} else if (tokenStandard == Standard.ERC1400) {
require(token != address(0), Errors.ZERO_ADDRESS_NOT_ALLOWED);
address tokenExtension = interfaceAddr(token, ERC1400_TOKENS_VALIDATOR);
require(
tokenExtension != address(0),
Errors.SW_HOLD_TOKEN_EXTENSION_MISSING
);
uint256 holdValue;
(,,,,holdValue,,,,) = IHoldableERC1400TokenExtension(tokenExtension).retrieveHoldData(token, tokenHoldId);
IHoldableERC1400TokenExtension(tokenExtension).executeHold(
token,
tokenHoldId,
holdValue,
preimage
);
} else {
revert(Errors.SW_TOKEN_STANDARD_NOT_SUPPORTED);
}
emit ExecutedHold(
token,
tokenHoldId,
preimage,
tokenRecipient
);
}
function _holdExists(address sender, address recipient, UserTradeData memory userTradeData) internal view returns(bool) {
address tokenAddress = userTradeData.tokenAddress;
bytes32 holdId = userTradeData.tokenId;
Standard tokenStandard = userTradeData.tokenStandard;
if(tokenStandard == Standard.ERC1400) {
address tokenExtension = interfaceAddr(tokenAddress, ERC1400_TOKENS_VALIDATOR);
require(
tokenExtension != address(0),
Errors.SW_HOLD_TOKEN_EXTENSION_MISSING
);
HoldStatusCode holdStatus;
address holdSender;
address holdRecipient;
uint256 holdValue;
address notary;
bytes32 secretHash;
(,holdSender,holdRecipient,notary,holdValue,,secretHash,,holdStatus) = IHoldableERC1400TokenExtension(tokenExtension).retrieveHoldData(tokenAddress, holdId);
return holdStatus == HoldStatusCode.Ordered && holdValue == userTradeData.tokenValue && (holdSender == sender || holdSender == address(0)) && holdRecipient == recipient && (secretHash != bytes32(0) || notary == address(this));
} else if (tokenStandard == Standard.ERC20) {
ERC20HoldData memory data = IERC20HoldableToken(tokenAddress).retrieveHoldData(holdId);
return (data.sender == sender || data.sender == address(0)) && data.recipient == recipient && data.amount == userTradeData.tokenValue && data.status == HoldStatusCode.Ordered && (data.secretHash != bytes32(0) || data.notary == address(this));
} else {
revert(Errors.SW_TOKEN_INCORRECT_STANDARD);
}
}
/**
* @dev Indicate whether or not the Swaps contract can receive the tokens or not.
*
* By convention, the 32 first bytes of a token transfer to the Swaps smart contract contain a flag.
*
* - When tokens are transferred to Swaps contract to propose a new trade. The 'data' field starts with the
* following flag: 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
* In this case the data structure is the the following:
* <tradeFlag (32 bytes)><recipient address (32 bytes)><executer address (32 bytes)><expiration date (32 bytes)><requested token data (4 * 32 bytes)>
*
* - When tokens are transferred to Swaps contract to accept an existing trade. The 'data' field starts with the
* following flag: 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
* In this case the data structure is the the following:
* <tradeFlag (32 bytes)><request index (32 bytes)>
*
* If the 'data' doesn't start with one of those flags, the Swaps contract won't accept the token transfer.
*
* @param data Information attached to the Swaps transfer.
* @param operatorData Information attached to the Swaps transfer, by the operator.
* @return 'true' if the Swaps contract can receive the tokens, 'false' if not.
*/
function _canReceive(bytes memory data, bytes memory operatorData) internal pure returns(bool) {
if(operatorData.length == 0) { // The reason for this check is to avoid a certificate gets interpreted as a flag by mistake
return false;
}
bytes32 flag = _getTradeFlag(data);
if(data.length == 320 && flag == TRADE_PROPOSAL_FLAG) {
return true;
} else if ((data.length == 64 || data.length == 96) && flag == TRADE_ACCEPTANCE_FLAG) {
return true;
} else if (data.length == 32 && flag == BYPASS_ACTION_FLAG) {
return true;
} else {
return false;
}
}
/**
* @dev Retrieve the trade flag from the 'data' field.
*
* By convention, the 32 first bytes of a token transfer to the Swaps smart contract contain a flag.
* - When tokens are transferred to Swaps contract to propose a new trade. The 'data' field starts with the
* following flag: 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
* - When tokens are transferred to Swaps contract to accept an existing trade. The 'data' field starts with the
* following flag: 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
*
* @param data Concatenated information about the trade proposal.
* @return flag Trade flag.
*/
function _getTradeFlag(bytes memory data) internal pure returns(bytes32 flag) {
assembly {
flag:= mload(add(data, 32))
}
}
/**
* By convention, when tokens are transferred to Swaps contract to propose a new trade, the 'data' of a token transfer has the following structure:
* <tradeFlag (32 bytes)><recipient address (32 bytes)><executer address (32 bytes)><expiration date (32 bytes)><requested token data (5 * 32 bytes)>
*
* The first 32 bytes are the flag 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
*
* The next 32 bytes contain the trade recipient address (or the zero address if the recipient is not chosen).
*
* The next 32 bytes contain the trade executer address (or zero if the executer is not chosen).
*
* The next 32 bytes contain the trade expiration date (or zero if the expiration date is not chosen).
*
* The next 32 bytes contain the trade requested token address (or the zero address if the recipient is not chosen).
* The next 32 bytes contain the trade requested token amount.
* The next 32 bytes contain the trade requested token id/partition (used when token standard is ERC721 or ERC1400).
* The next 32 bytes contain the trade requested token standard (OffChain, ERC20, ERC721, ERC1400, ETH).
* The next 32 bytes contain a boolean precising wether trade has been accepted by token holder or not.
* The next 32 bytes contain a boolean precising wether trade has been approved by token controller or not.
*
* Example input for recipient address '0xb5747835141b46f7C472393B31F8F5A57F74A44f', expiration date '1576348418',
* trade executer address '0x32F54098916ceb5f57a117dA9554175Fe25611bA', requested token address '0xC6F0410A667a5BEA528d6bc9efBe10270089Bb11',
* requested token amount '5', requested token id/partition '37252', and requested token type 'ERC1400', accepted and approved:
* 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc000000000000000000000000b5747835141b46f7C472393B31F8F5A57F74A44f
* 000000000000000000000000000000000000000000000000000000157634841800000000000000000000000032F54098916ceb5f57a117dA9554175Fe25611bA
* 000000000000000000000000C6F0410A667a5BEA528d6bc9efBe10270089Bb110000000000000000000000000000000000000000000000000000000000000005
* 000000000000000000000000000000000000000000000000000000000037252000000000000000000000000000000000000000000000000000000000000002
* 000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000001
*/
/**
* @dev Retrieve the tokenData from the 'data' field.
*
* @param data Concatenated information about the trade proposal.
* @return tokenData Trade token data < 1: address > < 2: amount > < 3: id/partition > < 4: standard > < 5: accepted > < 6: approved >.
*/
function _getTradeTokenData(bytes memory data) internal pure returns(UserTradeData memory tokenData) {
address tokenAddress;
uint256 tokenAmount;
bytes32 tokenId;
Standard tokenStandard;
TradeType tradeType;
assembly {
tokenAddress:= mload(add(data, 192))
tokenAmount:= mload(add(data, 224))
tokenId:= mload(add(data, 256))
tokenStandard:= mload(add(data, 288))
tradeType:= mload(add(data, 320))
}
tokenData = UserTradeData(
tokenAddress,
tokenAmount,
tokenId,
tokenStandard,
false,
false,
tradeType,
address(0) //TODO Should this be included in data?
);
}
/**
* @dev Retrieve the trade index from the 'data' field.
*
* By convention, when tokens are transferred to Swaps contract to accept an existing trade, the 'data' of a token transfer has the following structure:
* <tradeFlag (32 bytes)><index uint256 (32 bytes)>
*
* The first 32 bytes are the flag 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
*
* The next 32 bytes contain the trade index.
*
* Example input for trade index #2985:
* 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd0000000000000000000000000000000000000000000000000000000000002985
*
* @param data Concatenated information about the trade validation.
* @return index Trade index.
*/
/**************************** TRADE EXECUTERS *******************************/
/**
* @dev Renounce ownership of the contract.
*/
function renounceOwnership() public override onlyOwner {
Ownable.renounceOwnership();
_ownedContract = false;
}
/**
* @dev Get the list of trade executers as defined by the Swaps contract.
* @return List of addresses of all the trade executers.
*/
function tradeExecuters() external view returns (address[] memory) {
return _tradeExecuters;
}
/**
* @dev Set list of trade executers for the Swaps contract.
* @param operators Trade executers addresses.
*/
function setTradeExecuters(address[] calldata operators) external onlyOwner {
require(_ownedContract, Errors.NO_CONTRACT_OWNER);
_setTradeExecuters(operators);
}
/**
* @dev Set list of trade executers for the Swaps contract.
* @param operators Trade executers addresses.
*/
function _setTradeExecuters(address[] memory operators) internal {
for (uint i = 0; i<_tradeExecuters.length; i++){
_isTradeExecuter[_tradeExecuters[i]] = false;
}
for (uint j = 0; j<operators.length; j++){
_isTradeExecuter[operators[j]] = true;
}
_tradeExecuters = operators;
}
/************************** TOKEN CONTROLLERS *******************************/
/**
* @dev Get the list of token controllers for a given token.
* @param tokenAddress Token address.
* @return List of addresses of all the token controllers for a given token.
*/
function tokenControllers(address tokenAddress) external view returns (address[] memory) {
return _tokenControllers[tokenAddress];
}
/**
* @dev Set list of token controllers for a given token.
* @param tokenAddress Token address.
* @param operators Operators addresses.
*/
function setTokenControllers(address tokenAddress, address[] calldata operators) external onlyTokenController(tokenAddress) {
for (uint i = 0; i<_tokenControllers[tokenAddress].length; i++){
_isTokenController[tokenAddress][_tokenControllers[tokenAddress][i]] = false;
}
for (uint j = 0; j<operators.length; j++){
_isTokenController[tokenAddress][operators[j]] = true;
}
_tokenControllers[tokenAddress] = operators;
}
/************************** TOKEN PRICE ORACLES *******************************/
/**
* @dev Get the list of price oracles for a given token.
* @param tokenAddress Token address.
* @return List of addresses of all the price oracles for a given token.
*/
function priceOracles(address tokenAddress) external view returns (address[] memory) {
return _priceOracles[tokenAddress];
}
/**
* @dev Set list of price oracles for a given token.
* @param tokenAddress Token address.
* @param oracles Oracles addresses.
*/
function setPriceOracles(address tokenAddress, address[] calldata oracles) external onlyPriceOracle(tokenAddress) {
for (uint i = 0; i<_priceOracles[tokenAddress].length; i++){
_isPriceOracle[tokenAddress][_priceOracles[tokenAddress][i]] = false;
}
for (uint j = 0; j<oracles.length; j++){
_isPriceOracle[tokenAddress][oracles[j]] = true;
}
_priceOracles[tokenAddress] = oracles;
}
/**
* @dev Check if address is oracle of a given token.
* @param tokenAddress Token address.
* @param oracle Oracle address.
* @return 'true' if the address is oracle of the given token.
*/
function _checkPriceOracle(address tokenAddress, address oracle) internal view returns(bool) {
return(_isPriceOracle[tokenAddress][oracle] || oracle == Ownable(tokenAddress).owner());
}
/****************************** Swaps PRICES *********************************/
/**
* @dev Get price of the token.
* @param tokenAddress1 Address of the token to be priced.
* @param tokenAddress2 Address of the token to pay for token1.
*/
function getPriceOwnership(address tokenAddress1, address tokenAddress2) external view returns(bool) {
return _priceOwnership[tokenAddress1][tokenAddress2];
}
/**
* @dev Take ownership for setting the price of a token.
* @param tokenAddress1 Address of the token to be priced.
* @param tokenAddress2 Address of the token to pay for token1.
*/
function setPriceOwnership(address tokenAddress1, address tokenAddress2, bool priceOwnership) external onlyPriceOracle(tokenAddress1) {
_priceOwnership[tokenAddress1][tokenAddress2] = priceOwnership;
}
/**
* @dev Get date after which the token price can potentially be set by an oracle (0 if price can not be set by an oracle).
* @param tokenAddress Token address.
*/
function variablePriceStartDate(address tokenAddress) external view returns(uint256) {
return _variablePriceStartDate[tokenAddress];
}
/**
* @dev Set date after which the token price can potentially be set by an oracle (0 if price can not be set by an oracle).
* @param tokenAddress Token address.
* @param startDate Date after which token price can potentially be set by an oracle (0 if price can not be set by an oracle).
*/
function setVariablePriceStartDate(address tokenAddress, uint256 startDate) external onlyPriceOracle(tokenAddress) {
require((startDate > block.timestamp + SECONDS_IN_WEEK) || startDate == 0, Errors.SW_START_DATE_MUST_BE_ONE_WEEK_BEFORE);
_variablePriceStartDate[tokenAddress] = startDate;
}
/**
* @dev Get price of the token.
* @param tokenAddress1 Address of the token to be priced.
* @param tokenAddress2 Address of the token to pay for token1.
* @param tokenId1 ID/partition of the token1 (set to 0 bytes32 if price is set for all IDs/partitions).
* @param tokenId1 ID/partition of the token2 (set to 0 bytes32 if price is set for all IDs/partitions).
*/
function getTokenPrice(address tokenAddress1, address tokenAddress2, bytes32 tokenId1, bytes32 tokenId2) external view returns(uint256) {
return _tokenUnitPricesByPartition[tokenAddress1][tokenAddress2][tokenId1][tokenId2];
}
/**
* @dev Set price of a token.
* @param tokenAddress1 Address of the token to be priced.
* @param tokenAddress2 Address of the token to pay for token1.
* @param tokenId1 ID/partition of the token1 (set to 0 bytes32 if price is set for all IDs/partitions).
* @param tokenId2 ID/partition of the token2 (set to 0 bytes32 if price is set for all IDs/partitions).
* @param newPrice New price of the token.
*/
function setTokenPrice(address tokenAddress1, address tokenAddress2, bytes32 tokenId1, bytes32 tokenId2, uint256 newPrice) external {
require(!(_priceOwnership[tokenAddress1][tokenAddress2] && _priceOwnership[tokenAddress2][tokenAddress1]), Errors.SW_COMPETITION_ON_PRICE_OWNERSHIP);
if(_priceOwnership[tokenAddress1][tokenAddress2]) {
require(_checkPriceOracle(tokenAddress1, _msgSender()), Errors.SW_PRICE_SETTER_NOT_TOKEN_ORACLE_1);
} else if(_priceOwnership[tokenAddress2][tokenAddress1]) {
require(_checkPriceOracle(tokenAddress2, _msgSender()), Errors.SW_PRICE_SETTER_NOT_TOKEN_ORACLE_2);
} else {
revert(Errors.SW_NO_PRICE_OWNERSHIP);
}
_tokenUnitPricesByPartition[tokenAddress1][tokenAddress2][tokenId1][tokenId2] = newPrice;
}
/**
* @dev Get amount of token2 to pay to acquire the token1.
* @param index Index of the Swaps request.
*/
function getPrice(uint256 index) public view returns(uint256) {
Trade storage trade = _trades[index];
address tokenAddress1 = trade.userTradeData1.tokenAddress;
uint256 tokenValue1 = trade.userTradeData1.tokenValue;
bytes32 tokenId1 = trade.userTradeData1.tokenId;
address tokenAddress2 = trade.userTradeData2.tokenAddress;
uint256 tokenValue2 = trade.userTradeData2.tokenValue;
bytes32 tokenId2 = trade.userTradeData2.tokenId;
require(!(_priceOwnership[tokenAddress1][tokenAddress2] && _priceOwnership[tokenAddress2][tokenAddress1]), Errors.SW_COMPETITION_ON_PRICE_OWNERSHIP);
if(_variablePriceStartDate[tokenAddress1] == 0 || block.timestamp < _variablePriceStartDate[tokenAddress1]) {
return tokenValue2;
}
if(_priceOwnership[tokenAddress1][tokenAddress2] || _priceOwnership[tokenAddress2][tokenAddress1]) {
if(_tokenUnitPricesByPartition[tokenAddress1][tokenAddress2][tokenId1][tokenId2] != 0) {
return tokenValue1 * (_tokenUnitPricesByPartition[tokenAddress1][tokenAddress2][tokenId1][tokenId2]);
} else if(_tokenUnitPricesByPartition[tokenAddress2][tokenAddress1][tokenId2][tokenId1] != 0) {
return tokenValue1 / (_tokenUnitPricesByPartition[tokenAddress2][tokenAddress1][tokenId2][tokenId1]);
} else if(_tokenUnitPricesByPartition[tokenAddress1][tokenAddress2][tokenId1][ALL_PARTITIONS] != 0) {
return tokenValue1 * (_tokenUnitPricesByPartition[tokenAddress1][tokenAddress2][tokenId1][ALL_PARTITIONS]);
} else if(_tokenUnitPricesByPartition[tokenAddress2][tokenAddress1][ALL_PARTITIONS][tokenId1] != 0) {
return tokenValue1 / (_tokenUnitPricesByPartition[tokenAddress2][tokenAddress1][ALL_PARTITIONS][tokenId1]);
} else if(_tokenUnitPricesByPartition[tokenAddress1][tokenAddress2][ALL_PARTITIONS][tokenId2] != 0) {
return tokenValue1 * (_tokenUnitPricesByPartition[tokenAddress1][tokenAddress2][ALL_PARTITIONS][tokenId2]);
} else if(_tokenUnitPricesByPartition[tokenAddress2][tokenAddress1][tokenId2][ALL_PARTITIONS] != 0) {
return tokenValue1 / (_tokenUnitPricesByPartition[tokenAddress2][tokenAddress1][tokenId2][ALL_PARTITIONS]);
} else if(_tokenUnitPricesByPartition[tokenAddress1][tokenAddress2][ALL_PARTITIONS][ALL_PARTITIONS] != 0) {
return tokenValue1 * (_tokenUnitPricesByPartition[tokenAddress1][tokenAddress2][ALL_PARTITIONS][ALL_PARTITIONS]);
} else if(_tokenUnitPricesByPartition[tokenAddress2][tokenAddress1][ALL_PARTITIONS][ALL_PARTITIONS] != 0) {
return tokenValue1 / (_tokenUnitPricesByPartition[tokenAddress2][tokenAddress1][ALL_PARTITIONS][ALL_PARTITIONS]);
} else {
return tokenValue2;
}
} else {
return tokenValue2;
}
}
/**************************** VIEW FUNCTIONS *******************************/
/**
* @dev Get the trade.
* @param index Index of the trade.
* @return Trade.
*/
function getTrade(uint256 index) external view returns(Trade memory) {
Trade storage trade = _trades[index];
return trade;
}
/**
* @dev Get the total number of requests in the Swaps contract.
* @return Total number of requests in the Swaps contract.
*/
function getNbTrades() external view returns(uint256) {
return _index;
}
}
| * @dev Create a new trade request in the Swaps smart contract. @param holder1 Address of the first token holder. @param holder2 Address of the second token holder. @param executer Executer of the trade. @param expirationDate Expiration date of the trade. @param userTradeData1 Encoded pack of variables for token1 (address, amount, id/partition, standard, accepted, approved). @param userTradeData2 Encoded pack of variables for token2 (address, amount, id/partition, standard, accepted, approved)./ | function _requestTrade(
address holder1,
address holder2,
uint256 expirationDate,
uint256 settlementDate,
UserTradeData memory userTradeData1,
UserTradeData memory userTradeData2
)
internal
{
if(userTradeData1.tokenStandard == Standard.ETH) {
require(userTradeData1.tradeType == TradeType.Escrow, Errors.SW_ETH_TRADE_REQUIRES_ESCROW);
}
if(userTradeData2.tokenStandard == Standard.ETH) {
require(userTradeData2.tradeType == TradeType.Escrow, Errors.SW_ETH_TRADE_REQUIRES_ESCROW);
}
if (userTradeData1.tradeType == TradeType.Hold) {
require(userTradeData1.tokenStandard == Standard.ERC20 || userTradeData1.tokenStandard == Standard.ERC1400, Errors.SW_TOKEN_STANDARD_NOT_SUPPORTED);
require(userTradeData1.tokenId != bytes32(0), Errors.SW_NO_HOLDID_GIVEN);
}
if (userTradeData2.tradeType == TradeType.Hold) {
require(userTradeData2.tokenStandard == Standard.ERC20 || userTradeData2.tokenStandard == Standard.ERC1400, Errors.SW_TOKEN_STANDARD_NOT_SUPPORTED);
require(userTradeData2.tokenId != bytes32(0), Errors.SW_NO_HOLDID_GIVEN);
}
if(_ownedContract) {
require(_isTradeExecuter[executer], Errors.SW_TRADE_EXECUTER_NOT_ALLOWED);
}
require(holder1 != address(0), Errors.ZERO_ADDRESS_NOT_ALLOWED);
_index++;
uint256 _expirationDate = (expirationDate > block.timestamp) ? expirationDate : (block.timestamp + SECONDS_IN_MONTH);
_trades[_index] = Trade({
holder1: holder1,
holder2: holder2,
executer: executer,
expirationDate: _expirationDate,
settlementDate: settlementDate,
userTradeData1: userTradeData1,
userTradeData2: userTradeData2,
state: State.Pending
});
}
| 12,733,441 | [
1,
1684,
279,
394,
18542,
590,
316,
326,
5434,
6679,
13706,
6835,
18,
225,
10438,
21,
5267,
434,
326,
1122,
1147,
10438,
18,
225,
10438,
22,
5267,
434,
326,
2205,
1147,
10438,
18,
225,
1196,
26812,
3889,
26812,
434,
326,
18542,
18,
225,
7686,
1626,
31017,
1509,
434,
326,
18542,
18,
225,
729,
22583,
751,
21,
23306,
2298,
434,
3152,
364,
1147,
21,
261,
2867,
16,
3844,
16,
612,
19,
10534,
16,
4529,
16,
8494,
16,
20412,
2934,
225,
729,
22583,
751,
22,
23306,
2298,
434,
3152,
364,
1147,
22,
261,
2867,
16,
3844,
16,
612,
19,
10534,
16,
4529,
16,
8494,
16,
20412,
2934,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
225,
445,
389,
2293,
22583,
12,
203,
565,
1758,
10438,
21,
16,
203,
565,
1758,
10438,
22,
16,
203,
565,
2254,
5034,
7686,
1626,
16,
203,
565,
2254,
5034,
26319,
806,
1626,
16,
203,
565,
2177,
22583,
751,
3778,
729,
22583,
751,
21,
16,
203,
565,
2177,
22583,
751,
3778,
729,
22583,
751,
22,
203,
225,
262,
7010,
565,
2713,
203,
225,
288,
203,
565,
309,
12,
1355,
22583,
751,
21,
18,
2316,
8336,
422,
8263,
18,
1584,
44,
13,
288,
203,
1377,
2583,
12,
1355,
22583,
751,
21,
18,
20077,
559,
422,
2197,
323,
559,
18,
6412,
492,
16,
9372,
18,
18746,
67,
1584,
44,
67,
20060,
1639,
67,
862,
8627,
7031,
67,
41,
2312,
11226,
1769,
203,
565,
289,
203,
203,
565,
309,
12,
1355,
22583,
751,
22,
18,
2316,
8336,
422,
8263,
18,
1584,
44,
13,
288,
203,
1377,
2583,
12,
1355,
22583,
751,
22,
18,
20077,
559,
422,
2197,
323,
559,
18,
6412,
492,
16,
9372,
18,
18746,
67,
1584,
44,
67,
20060,
1639,
67,
862,
8627,
7031,
67,
41,
2312,
11226,
1769,
203,
565,
289,
203,
203,
565,
309,
261,
1355,
22583,
751,
21,
18,
20077,
559,
422,
2197,
323,
559,
18,
20586,
13,
288,
203,
1377,
2583,
12,
1355,
22583,
751,
21,
18,
2316,
8336,
422,
8263,
18,
654,
39,
3462,
747,
729,
22583,
751,
21,
18,
2316,
8336,
422,
8263,
18,
654,
39,
3461,
713,
16,
9372,
18,
18746,
67,
8412,
67,
882,
18264,
67,
4400,
67,
21134,
1769,
203,
1377,
2583,
12,
1355,
22583,
751,
21,
2
]
|
pragma solidity ^0.4.23;
import "openzeppelin-zos/contracts/ownership/Ownable.sol";
import "./User.sol";
/**
* @title Mkt is a tool for Self Sovereign Social Networking
*/
contract Mkt is Ownable {
// Accounts indexed into structs
struct Account {
address user;
address owner;
}
// Registry of all users
mapping (bytes32 => Account) public register;
// Logs Withdrawals and User Creations
event Withdrawal(address indexed wallet, uint256 value);
event CreateUser(bytes32 indexed id, address indexed user);
/**
* @dev Constructor in zOS
* Creates and stores a reference to the user register
*/
function initialize(address _admin) isInitializer("Mkt", "0.0.1") public {
Ownable.initialize(_admin);
}
/**
* @dev Insert a new user into the user registry, owned by sender
*/
function newUser(bytes32 _id, bytes32 _pka, bytes32 _pkb) public payable returns (address) {
// require(msg.value > 5 finney);
User user = new User();
user.initialize(_id, _pka, _pkb, msg.sender);
insert(_id, address(user), msg.sender);
emit CreateUser(_id, address(user));
return address(user);
}
/**
* @dev Transfer funds from contract to owner's wallet
*/
function withdraw(address _wallet) public onlyOwner {
require(address(this).balance > 0);
require(_wallet != address(0));
uint256 value = address(this).balance;
_wallet.transfer(value);
emit Withdrawal(_wallet, value);
}
/**
* @dev Insert a new user into the registry
*/
function insert(bytes32 handle, address user, address owner) public {
require(!contains(handle));
require(user != address(0));
require(owner != address(0));
register[handle] = Account(user, owner);
}
/**
* @dev Update the user that the hande points to
*/
function update(bytes32 handle, address user) public {
require(contains(handle));
require(user != address(0));
require(msg.sender == register[handle].owner);
register[handle].user = user;
}
/**
* @dev Transfer a new user into the registry
*/
function transfer(bytes32 handle, address owner) public {
require(contains(handle));
require(owner != address(0));
require(msg.sender == register[handle].owner);
register[handle].owner = owner;
}
/**
* @dev Remove a new user from the registry
*/
function remove(bytes32 handle) public {
require(contains(handle));
require(msg.sender == register[handle].owner);
delete register[handle];
}
/**
* @dev Get user contract address from the registry
*/
function getUser(bytes32 handle) public view returns (address) {
require(contains(handle));
return register[handle].user;
}
/**
* @dev Get owner of a particular handle
*/
function getOwner(bytes32 handle) public view returns (address) {
require(contains(handle));
return register[handle].owner;
}
/**
* @dev Get public key for a particular handle
*/
function getKey(bytes32 handle) public view returns (bytes32, bytes32) {
require(contains(handle));
User user = User(register[handle].user);
return (user.getPK());
}
/**
* @dev Check if user is in registry
*/
function contains(bytes32 handle) public view returns (bool) {
return register[handle].user != 0;
}
}
| Registry of all users | mapping (bytes32 => Account) public register;
| 12,673,685 | [
1,
4243,
434,
777,
3677,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
261,
3890,
1578,
516,
6590,
13,
1071,
1744,
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
]
|
contract MultiAccess {
address public multiAccessRecipient;
/**
* Confirmation event.
* event
* @param owner - The owner address.
* @param operation - The operation name.
* @param completed - If teh operation is completed or not.
*/
event Confirmation(address indexed owner, bytes32 indexed operation, bool completed);
/**
* Revoke event.
* event
* @param owner - The owner address.
* @param operation - The operation name.
*/
event Revoke(address owner, bytes32 operation);
/**
* Owner change event.
* event
* @param oldOwner - The old owner address.
* @param newOwner - The new owner address.
*/
event OwnerChanged(address oldOwner, address newOwner);
/**
* Owner addedd event.
* event
* @param newOwner - The new owner address.
*/
event OwnerAdded(address newOwner);
/**
* Owner removed event.
* event
* @param oldOwner - The old owner address.
*/
event OwnerRemoved(address oldOwner);
/**
* Requirement change event.
* event
* @param newRequirement - The uint of the new requirement.
*/
event RequirementChanged(uint newRequirement);
/**
* Recipient contract requirement change event.
* event
* @param newRecipientRequirement - The uint of the new recipient requirement.
*/
event RecipientRequirementChanged(uint newRecipientRequirement);
struct PendingState {
bool[] ownersDone;
uint yetNeeded;
bytes32 op;
}
mapping(bytes32 => uint) pendingIndex;
PendingState[] pending;
uint public multiAccessRequired;
uint public multiAccessRecipientRequired;
mapping(address => uint) ownerIndex;
address[] public multiAccessOwners;
/**
* Allow only the owner on msg.sender to exec the function.
* modifier
*/
modifier onlyowner {
if (multiAccessIsOwner(msg.sender)) {
_;
}
}
/**
* Allow only if many owners has agreed to exec the function.
* modifier
*/
modifier onlymanyowners(bool _isSelfFunction) {
if (_confirmAndCheck(_isSelfFunction)) {
_;
}
}
/**
* Construct of MultiAccess with the msg.sender and only multiAccessOwner and multiAccessRequired as one.
* constructor
*/
function MultiAccess() {
multiAccessOwners.length = 2;
multiAccessOwners[1] = msg.sender;
ownerIndex[msg.sender] = 1;
multiAccessRequired = 1;
multiAccessRecipientRequired = 1;
pending.length = 1;
}
/**
* Know if an owner has confirmed an operation.
* public_function
* @param _owner - The caller of the function.
* @param _operation - The data array.
*/
function multiAccessHasConfirmed(bytes32 _operation, address _owner) constant returns (bool) {
uint pos = pendingIndex[_operation];
if (pos == 0) {
return false;
}
uint index = ownerIndex[_owner];
var pendingOp = pending[pos];
if (index >= pendingOp.ownersDone.length) {
return false;
}
return pendingOp.ownersDone[index];
}
/**
* Confirm an operation.
* internalfunction
* @param _isSelfFunction - Is this a self or recipient function call.
*/
function _confirmAndCheck(bool _isSelfFunction) onlyowner() internal returns (bool) {
bytes32 operation = sha3(msg.data);
uint index = ownerIndex[msg.sender];
if (multiAccessHasConfirmed(operation, msg.sender)) {
return false;
}
var pos = pendingIndex[operation];
if (pos == 0) {
pos = pending.length++;
pending[pos].yetNeeded = _isSelfFunction ? multiAccessRequired : multiAccessRecipientRequired;
pending[pos].op = operation;
pendingIndex[operation] = pos;
}
var pendingOp = pending[pos];
if (pendingOp.yetNeeded <= 1) {
Confirmation(msg.sender, operation, true);
if (pos < pending.length-1) {
PendingState last = pending[pending.length-1];
pending[pos] = last;
pendingIndex[last.op] = pos;
}
pending.length--;
delete pendingIndex[operation];
return true;
} else {
Confirmation(msg.sender, operation, false);
pendingOp.yetNeeded--;
if (index >= pendingOp.ownersDone.length) {
pendingOp.ownersDone.length = index+1;
}
pendingOp.ownersDone[index] = true;
}
return false;
}
/**
* Remove all the pending operations.
* internalfunction
*/
function _clearPending() internal {
uint length = pending.length;
for (uint i = length-1; i > 0; --i) {
delete pendingIndex[pending[i].op];
pending.length--;
}
}
/**
* Know if an address is an multiAccessOwner.
* public_function
* @param _addr - The operation name.
*/
function multiAccessIsOwner(address _addr) constant returns (bool) {
return ownerIndex[_addr] > 0;
}
/**
* Revoke a vote from an operation.
* public_function
* @param _operation -The operation name.
*/
function multiAccessRevoke(bytes32 _operation) onlyowner() external {
uint index = ownerIndex[msg.sender];
if (!multiAccessHasConfirmed(_operation, msg.sender)) {
return;
}
var pendingOp = pending[pendingIndex[_operation]];
pendingOp.ownersDone[index] = false;
pendingOp.yetNeeded++;
Revoke(msg.sender, _operation);
}
/**
* Change the address of one owner.
* external_function
* @param _from - The old address.
* @param _to - The new address.
*/
function multiAccessChangeOwner(address _from, address _to) onlymanyowners(true) external {
if (multiAccessIsOwner(_to)) {
return;
}
uint index = ownerIndex[_from];
if (index == 0) {
return;
}
_clearPending();
multiAccessOwners[index] = _to;
delete ownerIndex[_from];
ownerIndex[_to] = index;
OwnerChanged(_from, _to);
}
/**
* Add a owner.
* external_function
* @param _owner - The address to add.
*/
function multiAccessAddOwner(address _owner) onlymanyowners(true) external {
if (multiAccessIsOwner(_owner)) {
return;
}
uint pos = multiAccessOwners.length++;
multiAccessOwners[pos] = _owner;
ownerIndex[_owner] = pos;
OwnerAdded(_owner);
}
/**
* Remove a owner.
* external_function
* @param _owner - The address to remove.
*/
function multiAccessRemoveOwner(address _owner) onlymanyowners(true) external {
uint index = ownerIndex[_owner];
if (index == 0) {
return;
}
if (multiAccessRequired >= multiAccessOwners.length-1) {
return;
}
if (index < multiAccessOwners.length-1) {
address last = multiAccessOwners[multiAccessOwners.length-1];
multiAccessOwners[index] = last;
ownerIndex[last] = index;
}
multiAccessOwners.length--;
delete ownerIndex[_owner];
_clearPending();
OwnerRemoved(_owner);
}
/**
* Change the requirement.
* external_function
* @param _newRequired - The new amount of required signatures.
*/
function multiAccessChangeRequirement(uint _newRequired) onlymanyowners(true) external {
if (_newRequired == 0 || _newRequired > multiAccessOwners.length-1) {
return;
}
multiAccessRequired = _newRequired;
_clearPending();
RequirementChanged(_newRequired);
}
/**
* Change the recipient requirement.
* external_function
* @param _newRecipientRequired - The new amount of recipient required signatures.
*/
function multiAccessChangeRecipientRequirement(uint _newRecipientRequired) onlymanyowners(true) {
if (_newRecipientRequired == 0) {
return;
}
multiAccessRecipientRequired = _newRecipientRequired;
_clearPending();
RecipientRequirementChanged(_newRecipientRequired);
}
/**
* Set the recipient.
* public_function
* @param _address - The multiAccessRecipient address.
*/
function multiAccessSetRecipient(address _address) onlymanyowners(true) returns(bool _success) {
if (multiAccessRecipient == _address) {
return true;
}
multiAccessRecipient = _address;
_clearPending();
return true;
}
/**
* Call arbitrary address.
* public_function
* @param _to - The address to call.
* @param _value - The value of wei to send with the call.
* @param _data - Message data to send with the call.
*/
function multiAccessCall(address _to, uint _value, bytes _data) onlymanyowners(true) returns(bool _success) {
return _to.call.value(_value)(_data);
}
function() onlymanyowners(false) /*returns(bool _success)*/ {
if (msg.data.length > 0) {
/*return*/
multiAccessRecipient.call(msg.data);
}
/*return false;*/
}
}
| * Remove all the pending operations. internalfunction/ | function _clearPending() internal {
uint length = pending.length;
for (uint i = length-1; i > 0; --i) {
delete pendingIndex[pending[i].op];
pending.length--;
}
}
| 2,491,692 | [
1,
3288,
777,
326,
4634,
5295,
18,
2713,
915,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
8507,
8579,
1435,
2713,
288,
203,
3639,
2254,
769,
273,
4634,
18,
2469,
31,
203,
3639,
364,
261,
11890,
277,
273,
769,
17,
21,
31,
277,
405,
374,
31,
1493,
77,
13,
288,
203,
5411,
1430,
4634,
1016,
63,
9561,
63,
77,
8009,
556,
15533,
203,
5411,
4634,
18,
2469,
413,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xC5d8f92aa55aF137337297E4Ff0e45e0D3C87371/sources/contracts/LemonoPresale.sol | * @dev Withdraw all available native tokens sent by accident to contract. Only the owner can call this function./ | function withdrawNative() external onlyOwner {
uint256 contractBalance = address(this).balance;
require(contractBalance > 0, "No NATIVE balance to withdraw");
payable(owner()).transfer(contractBalance);
emit NATIVEWithdrawn(owner(), contractBalance);
}
| 15,950,288 | [
1,
1190,
9446,
777,
2319,
6448,
2430,
3271,
635,
25961,
358,
6835,
18,
5098,
326,
3410,
848,
745,
333,
445,
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
]
| [
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,
598,
9446,
9220,
1435,
3903,
1338,
5541,
288,
203,
3639,
2254,
5034,
6835,
13937,
273,
1758,
12,
2211,
2934,
12296,
31,
203,
3639,
2583,
12,
16351,
13937,
405,
374,
16,
315,
2279,
423,
12992,
11013,
358,
598,
9446,
8863,
203,
3639,
8843,
429,
12,
8443,
1435,
2934,
13866,
12,
16351,
13937,
1769,
203,
3639,
3626,
423,
12992,
1190,
9446,
82,
12,
8443,
9334,
6835,
13937,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x904F1B26ddBd7ed3Bc6b7A8a55ff22BeBa2279c3/sources/RTNDAO.sol | change the minimum amount of tokens to sell from fees | function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner {
require(
newAmount >= (totalSupply() * 1) / 100000,
"Swap amount cannot be lower than 0.001% total supply."
);
require(
newAmount <= (totalSupply() * 1) / 100,
"Swap amount cannot be higher than 1% total supply."
);
swapTokensAtAmount = newAmount;
}
| 4,062,837 | [
1,
3427,
326,
5224,
3844,
434,
2430,
358,
357,
80,
628,
1656,
281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
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,
1089,
12521,
5157,
861,
6275,
12,
11890,
5034,
394,
6275,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
203,
5411,
394,
6275,
1545,
261,
4963,
3088,
1283,
1435,
380,
404,
13,
342,
25259,
16,
203,
5411,
315,
12521,
3844,
2780,
506,
2612,
2353,
374,
18,
11664,
9,
2078,
14467,
1199,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
394,
6275,
1648,
261,
4963,
3088,
1283,
1435,
380,
404,
13,
342,
2130,
16,
203,
5411,
315,
12521,
3844,
2780,
506,
10478,
2353,
404,
9,
2078,
14467,
1199,
203,
3639,
11272,
203,
3639,
7720,
5157,
861,
6275,
273,
394,
6275,
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
]
|
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken {
using SafeMath for uint256;
mapping (address => mapping (address => uint256)) allowed;
mapping(address => uint256) balances;
mapping(address => bool) preICO_address;
uint256 public totalSupply;
uint256 public endDate;
/**
* @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) {
if( preICO_address[msg.sender] ) require( now > endDate + 120 days ); //Lock coin
else require( now > endDate ); //Lock coin
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant public returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
var _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);
if( preICO_address[_from] ) require( now > endDate + 120 days ); //Lock coin
else require( now > endDate ); //Lock coin
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @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) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
if( preICO_address[msg.sender] ) require( now > endDate + 120 days ); //Lock coin
else require( now > endDate ); //Lock coin
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract TBCoin is StandardToken, Ownable {
using SafeMath for uint256;
// Token Info.
string public constant name = "TimeBox Coin";
string public constant symbol = "TB";
uint8 public constant decimals = 18;
// Sale period.
uint256 public startDate;
// uint256 public endDate;
// Token Cap for each rounds
uint256 public saleCap;
// Address where funds are collected.
address public wallet;
// Amount of raised money in wei.
uint256 public weiRaised;
// Event
event TokenPurchase(address indexed purchaser, uint256 value,
uint256 amount);
event PreICOTokenPushed(address indexed buyer, uint256 amount);
// Modifiers
modifier uninitialized() {
require(wallet == 0x0);
_;
}
function TBCoin() public{
}
//
function initialize(address _wallet, uint256 _start, uint256 _end,
uint256 _saleCap, uint256 _totalSupply)
public onlyOwner uninitialized {
require(_start >= getCurrentTimestamp());
require(_start < _end);
require(_wallet != 0x0);
require(_totalSupply > _saleCap);
startDate = _start;
endDate = _end;
saleCap = _saleCap;
wallet = _wallet;
totalSupply = _totalSupply;
balances[wallet] = _totalSupply.sub(saleCap);
balances[0xb1] = saleCap;
}
function supply() internal view returns (uint256) {
return balances[0xb1];
}
function getCurrentTimestamp() internal view returns (uint256) {
return now;
}
function getRateAt(uint256 at) public constant returns (uint256) {
if (at < startDate) {
return 0;
} else if (at < (startDate + 3 days)) {
return 1500;
} else if (at < (startDate + 9 days)) {
return 1440;
} else if (at < (startDate + 15 days)) {
return 1380;
} else if (at < (startDate + 21 days)) {
return 1320;
} else if (at < (startDate + 27 days)) {
return 1260;
} else if (at <= endDate) {
return 1200;
} else {
return 0;
}
}
// Fallback function can be used to buy tokens
function () public payable {
buyTokens(msg.sender, msg.value);
}
// For pushing pre-ICO records
function push(address buyer, uint256 amount) public onlyOwner { //b753a98c
require(balances[wallet] >= amount);
require(now < startDate);
require(buyer != wallet);
preICO_address[ buyer ] = true;
// Transfer
balances[wallet] = balances[wallet].sub(amount);
balances[buyer] = balances[buyer].add(amount);
PreICOTokenPushed(buyer, amount);
}
function buyTokens(address sender, uint256 value) internal {
require(saleActive());
uint256 weiAmount = value;
uint256 updatedWeiRaised = weiRaised.add(weiAmount);
// Calculate token amount to be purchased
uint256 actualRate = getRateAt(getCurrentTimestamp());
uint256 amount = weiAmount.mul(actualRate);
// We have enough token to sale
require(supply() >= amount);
// Transfer
balances[0xb1] = balances[0xb1].sub(amount);
balances[sender] = balances[sender].add(amount);
TokenPurchase(sender, weiAmount, amount);
// Update state.
weiRaised = updatedWeiRaised;
// Forward the fund to fund collection wallet.
wallet.transfer(msg.value);
}
function finalize() public onlyOwner {
require(!saleActive());
// Transfer the rest of token to TB team
balances[wallet] = balances[wallet].add(balances[0xb1]);
balances[0xb1] = 0;
}
function saleActive() public constant returns (bool) {
return (getCurrentTimestamp() >= startDate &&
getCurrentTimestamp() < endDate && supply() > 0);
}
} | Transfer the rest of token to TB team | function finalize() public onlyOwner {
require(!saleActive());
balances[wallet] = balances[wallet].add(balances[0xb1]);
balances[0xb1] = 0;
}
| 2,232,555 | [
1,
5912,
326,
3127,
434,
1147,
358,
399,
38,
5927,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
12409,
1435,
1071,
1338,
5541,
288,
203,
3639,
2583,
12,
5,
87,
5349,
3896,
10663,
203,
203,
3639,
324,
26488,
63,
19177,
65,
273,
324,
26488,
63,
19177,
8009,
1289,
12,
70,
26488,
63,
20,
6114,
21,
19226,
203,
3639,
324,
26488,
63,
20,
6114,
21,
65,
273,
374,
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
]
|
pragma solidity 0.5.17;
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
library EthAddressLib {
/**
* @dev returns the address used within the protocol to identify ETH
* @return the address assigned to ETH
*/
function ethAddress() internal pure returns(address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // Represents ETH: https://docs.aave.com/developers/developing-on-aave/deployed-contract-instances#reserves-assets
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IFlashLoanReceiver {
function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external;
}
interface ILendingPool {
function addressesProvider () external view returns ( address );
function deposit ( address _reserve, uint256 _amount, uint16 _referralCode ) external payable;
function redeemUnderlying ( address _reserve, address _user, uint256 _amount ) external;
function borrow ( address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode ) external;
function repay ( address _reserve, uint256 _amount, address _onBehalfOf ) external payable;
function swapBorrowRateMode ( address _reserve ) external;
function rebalanceFixedBorrowRate ( address _reserve, address _user ) external;
function setUserUseReserveAsCollateral ( address _reserve, bool _useAsCollateral ) external;
function liquidationCall ( address _collateral, address _reserve, address _user, uint256 _purchaseAmount, bool _receiveAToken ) external payable;
function flashLoan ( address _receiver, address _reserve, uint256 _amount, bytes calldata _params ) external;
function getReserveConfigurationData ( address _reserve ) external view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationDiscount, address interestRateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool fixedBorrowRateEnabled, bool isActive );
function getReserveData ( address _reserve ) external view returns ( uint256 totalLiquidity, uint256 availableLiquidity, uint256 totalBorrowsFixed, uint256 totalBorrowsVariable, uint256 liquidityRate, uint256 variableBorrowRate, uint256 fixedBorrowRate, uint256 averageFixedBorrowRate, uint256 utilizationRate, uint256 liquidityIndex, uint256 variableBorrowIndex, address aTokenAddress, uint40 lastUpdateTimestamp );
function getUserAccountData ( address _user ) external view returns ( uint256 totalLiquidityETH, uint256 totalCollateralETH, uint256 totalBorrowsETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor );
function getUserReserveData ( address _reserve, address _user ) external view returns ( uint256 currentATokenBalance, uint256 currentUnderlyingBalance, uint256 currentBorrowBalance, uint256 principalBorrowBalance, uint256 borrowRateMode, uint256 borrowRate, uint256 liquidityRate, uint256 originationFee, uint256 variableBorrowIndex, uint256 lastUpdateTimestamp, bool usageAsCollateralEnabled );
function getReserves () external view;
}
contract ILendingPoolAddressesProvider {
function getLendingPool() public view returns (address);
function setLendingPoolImpl(address _pool) public;
function getLendingPoolCore() public view returns (address payable);
function setLendingPoolCoreImpl(address _lendingPoolCore) public;
function getLendingPoolConfigurator() public view returns (address);
function setLendingPoolConfiguratorImpl(address _configurator) public;
function getLendingPoolDataProvider() public view returns (address);
function setLendingPoolDataProviderImpl(address _provider) public;
function getLendingPoolParametersProvider() public view returns (address);
function setLendingPoolParametersProviderImpl(address _parametersProvider) public;
function getTokenDistributor() public view returns (address);
function setTokenDistributor(address _tokenDistributor) public;
function getFeeProvider() public view returns (address);
function setFeeProviderImpl(address _feeProvider) public;
function getLendingPoolLiquidationManager() public view returns (address);
function setLendingPoolLiquidationManager(address _manager) public;
function getLendingPoolManager() public view returns (address);
function setLendingPoolManager(address _lendingPoolManager) public;
function getPriceOracle() public view returns (address);
function setPriceOracle(address _priceOracle) public;
function getLendingRateOracle() public view returns (address);
function setLendingRateOracle(address _lendingRateOracle) public;
}
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
contract IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
library UniversalERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 private constant ZERO_ADDRESS = IERC20(0x0000000000000000000000000000000000000000);
IERC20 private constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
function universalTransfer(IERC20 token, address to, uint256 amount) internal returns(bool) {
if (amount == 0) {
return true;
}
if (isETH(token)) {
address(uint160(to)).transfer(amount);
} else {
token.safeTransfer(to, amount);
return true;
}
}
function universalTransferFrom(IERC20 token, address from, address to, uint256 amount) internal {
if (amount == 0) {
return;
}
if (isETH(token)) {
require(from == msg.sender && msg.value >= amount, "Wrong useage of ETH.universalTransferFrom()");
if (to != address(this)) {
address(uint160(to)).transfer(amount);
}
if (msg.value > amount) {
msg.sender.transfer(msg.value.sub(amount));
}
} else {
token.safeTransferFrom(from, to, amount);
}
}
function universalTransferFromSenderToThis(IERC20 token, uint256 amount) internal {
if (amount == 0) {
return;
}
if (isETH(token)) {
if (msg.value > amount) {
// Return remainder if exist
msg.sender.transfer(msg.value.sub(amount));
}
} else {
token.safeTransferFrom(msg.sender, address(this), amount);
}
}
function universalApprove(IERC20 token, address to, uint256 amount) internal {
if (!isETH(token)) {
if (amount == 0) {
token.safeApprove(to, 0);
return;
}
uint256 allowance = token.allowance(address(this), to);
if (allowance < amount) {
if (allowance > 0) {
token.safeApprove(to, 0);
}
token.safeApprove(to, amount);
}
}
}
function universalBalanceOf(IERC20 token, address who) internal view returns (uint256) {
if (isETH(token)) {
return who.balance;
} else {
return token.balanceOf(who);
}
}
function universalDecimals(IERC20 token) internal view returns (uint256) {
if (isETH(token)) {
return 18;
}
(bool success, bytes memory data) = address(token).staticcall.gas(10000)(
abi.encodeWithSignature("decimals()")
);
if (!success || data.length == 0) {
(success, data) = address(token).staticcall.gas(10000)(
abi.encodeWithSignature("DECIMALS()")
);
}
return (success && data.length > 0) ? abi.decode(data, (uint256)) : 18;
}
function isETH(IERC20 token) internal pure returns(bool) {
return (address(token) == address(ZERO_ADDRESS) || address(token) == address(ETH_ADDRESS));
}
function notExist(IERC20 token) internal pure returns(bool) {
return (address(token) == address(-1));
}
}
interface IUniswapV2Exchange {
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
}
library UniswapV2ExchangeLib {
using SafeMath for uint256;
using UniversalERC20 for IERC20;
function getReturn(
IUniswapV2Exchange exchange,
IERC20 fromToken,
IERC20 destToken,
uint amountIn
) internal view returns (uint256) {
uint256 reserveIn = fromToken.universalBalanceOf(address(exchange));
uint256 reserveOut = destToken.universalBalanceOf(address(exchange));
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
return (denominator == 0) ? 0 : numerator.div(denominator);
}
}
contract IOneSplitConsts {
// flags = FLAG_DISABLE_UNISWAP + FLAG_DISABLE_BANCOR + ...
uint256 internal constant FLAG_DISABLE_UNISWAP = 0x01;
uint256 internal constant DEPRECATED_FLAG_DISABLE_KYBER = 0x02; // Deprecated
uint256 internal constant FLAG_DISABLE_BANCOR = 0x04;
uint256 internal constant FLAG_DISABLE_OASIS = 0x08;
uint256 internal constant FLAG_DISABLE_COMPOUND = 0x10;
uint256 internal constant FLAG_DISABLE_FULCRUM = 0x20;
uint256 internal constant FLAG_DISABLE_CHAI = 0x40;
uint256 internal constant FLAG_DISABLE_AAVE = 0x80;
uint256 internal constant FLAG_DISABLE_SMART_TOKEN = 0x100;
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_ETH = 0x200; // Deprecated, Turned off by default
uint256 internal constant FLAG_DISABLE_BDAI = 0x400;
uint256 internal constant FLAG_DISABLE_IEARN = 0x800;
uint256 internal constant FLAG_DISABLE_CURVE_COMPOUND = 0x1000;
uint256 internal constant FLAG_DISABLE_CURVE_USDT = 0x2000;
uint256 internal constant FLAG_DISABLE_CURVE_Y = 0x4000;
uint256 internal constant FLAG_DISABLE_CURVE_BINANCE = 0x8000;
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_DAI = 0x10000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDC = 0x20000; // Deprecated, Turned off by default
uint256 internal constant FLAG_DISABLE_CURVE_SYNTHETIX = 0x40000;
uint256 internal constant FLAG_DISABLE_WETH = 0x80000;
uint256 internal constant FLAG_DISABLE_UNISWAP_COMPOUND = 0x100000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
uint256 internal constant FLAG_DISABLE_UNISWAP_CHAI = 0x200000; // Works only when ETH<>DAI or FLAG_ENABLE_MULTI_PATH_ETH
uint256 internal constant FLAG_DISABLE_UNISWAP_AAVE = 0x400000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
uint256 internal constant FLAG_DISABLE_IDLE = 0x800000;
uint256 internal constant FLAG_DISABLE_MOONISWAP = 0x1000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2 = 0x2000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ETH = 0x4000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_DAI = 0x8000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_USDC = 0x10000000;
uint256 internal constant FLAG_DISABLE_ALL_SPLIT_SOURCES = 0x20000000;
uint256 internal constant FLAG_DISABLE_ALL_WRAP_SOURCES = 0x40000000;
uint256 internal constant FLAG_DISABLE_CURVE_PAX = 0x80000000;
uint256 internal constant FLAG_DISABLE_CURVE_RENBTC = 0x100000000;
uint256 internal constant FLAG_DISABLE_CURVE_TBTC = 0x200000000;
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDT = 0x400000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_WBTC = 0x800000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_TBTC = 0x1000000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_RENBTC = 0x2000000000; // Deprecated, Turned off by default
uint256 internal constant FLAG_DISABLE_DFORCE_SWAP = 0x4000000000;
uint256 internal constant FLAG_DISABLE_SHELL = 0x8000000000;
uint256 internal constant FLAG_ENABLE_CHI_BURN = 0x10000000000;
uint256 internal constant FLAG_DISABLE_MSTABLE_MUSD = 0x20000000000;
uint256 internal constant FLAG_DISABLE_CURVE_SBTC = 0x40000000000;
uint256 internal constant FLAG_DISABLE_DMM = 0x80000000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_ALL = 0x100000000000;
uint256 internal constant FLAG_DISABLE_CURVE_ALL = 0x200000000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ALL = 0x400000000000;
uint256 internal constant FLAG_DISABLE_SPLIT_RECALCULATION = 0x800000000000;
uint256 internal constant FLAG_DISABLE_BALANCER_ALL = 0x1000000000000;
uint256 internal constant FLAG_DISABLE_BALANCER_1 = 0x2000000000000;
uint256 internal constant FLAG_DISABLE_BALANCER_2 = 0x4000000000000;
uint256 internal constant FLAG_DISABLE_BALANCER_3 = 0x8000000000000;
uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_UNISWAP_RESERVE = 0x10000000000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_OASIS_RESERVE = 0x20000000000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_BANCOR_RESERVE = 0x40000000000000; // Deprecated, Turned off by default
uint256 internal constant FLAG_ENABLE_REFERRAL_GAS_SPONSORSHIP = 0x80000000000000; // Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_COMP = 0x100000000000000; // Deprecated, Turned off by default
uint256 internal constant FLAG_DISABLE_KYBER_ALL = 0x200000000000000;
uint256 internal constant FLAG_DISABLE_KYBER_1 = 0x400000000000000;
uint256 internal constant FLAG_DISABLE_KYBER_2 = 0x800000000000000;
uint256 internal constant FLAG_DISABLE_KYBER_3 = 0x1000000000000000;
uint256 internal constant FLAG_DISABLE_KYBER_4 = 0x2000000000000000;
uint256 internal constant FLAG_ENABLE_CHI_BURN_BY_ORIGIN = 0x4000000000000000;
}
contract IOneSplit is IOneSplitConsts {
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
);
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
);
function swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags
)
public
payable
returns(uint256 returnAmount);
}
contract IOneSplitMulti is IOneSplit {
function getExpectedReturnWithGasMulti(
IERC20[] memory tokens,
uint256 amount,
uint256[] memory parts,
uint256[] memory flags,
uint256[] memory destTokenEthPriceTimesGasPrices
)
public
view
returns(
uint256[] memory returnAmounts,
uint256 estimateGasAmount,
uint256[] memory distribution
);
function swapMulti(
IERC20[] memory tokens,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256[] memory flags
)
public
payable
returns(uint256 returnAmount);
}
contract IFreeFromUpTo is IERC20 {
function freeFromUpTo(address from, uint256 value) external returns(uint256 freed);
}
interface IReferralGasSponsor {
function makeGasDiscount(
uint256 gasSpent,
uint256 returnAmount,
bytes calldata msgSenderCalldata
) external;
}
library Array {
function first(IERC20[] memory arr) internal pure returns(IERC20) {
return arr[0];
}
function last(IERC20[] memory arr) internal pure returns(IERC20) {
return arr[arr.length - 1];
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract Withdrawable is Ownable {
using SafeERC20 for ERC20;
address constant ETHER = address(0);
event LogWithdraw(
address indexed _from,
address indexed _assetAddress,
uint amount
);
/**
* @dev Withdraw asset.
* @param _assetAddress Asset to be withdrawn.
*/
function withdraw(address _assetAddress) public onlyOwner {
uint assetBalance;
if (_assetAddress == ETHER) {
address self = address(this); // workaround for a possible solidity bug
assetBalance = self.balance;
msg.sender.transfer(assetBalance);
} else {
assetBalance = ERC20(_assetAddress).balanceOf(address(this));
ERC20(_assetAddress).safeTransfer(msg.sender, assetBalance);
}
emit LogWithdraw(msg.sender, _assetAddress, assetBalance);
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract FlashLoanReceiverBase is IFlashLoanReceiver, Withdrawable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
ILendingPoolAddressesProvider public addressesProvider;
constructor(address _addressProvider) public {
addressesProvider = ILendingPoolAddressesProvider(_addressProvider);
}
function() external payable { }
function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal {
address payable core = addressesProvider.getLendingPoolCore();
transferInternal(core, _reserve, _amount);
}
function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal {
if(_reserve == EthAddressLib.ethAddress()) {
//solium-disable-next-line
_destination.call.value(_amount)("");
return;
}
IERC20(_reserve).safeTransfer(_destination, _amount);
}
function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) {
if(_reserve == EthAddressLib.ethAddress()) {
return _target.balance;
}
return IERC20(_reserve).balanceOf(_target);
}
}
contract OneSplitAudit is IOneSplit, Ownable {
using SafeMath for uint256;
using UniversalERC20 for IERC20;
using Array for IERC20[];
IWETH constant internal weth = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IFreeFromUpTo public constant chi = IFreeFromUpTo(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c);
IOneSplitMulti public oneSplitImpl;
event ImplementationUpdated(address indexed newImpl);
event Swapped(
IERC20 indexed fromToken,
IERC20 indexed destToken,
uint256 fromTokenAmount,
uint256 destTokenAmount,
uint256 minReturn,
uint256[] distribution,
uint256[] flags,
address referral,
uint256 feePercent
);
constructor(IOneSplitMulti impl) public {
setNewImpl(impl);
}
function() external payable {
// solium-disable-next-line security/no-tx-origin
require(msg.sender != tx.origin, "OneSplit: do not send ETH directly");
}
function setNewImpl(IOneSplitMulti impl) public onlyOwner {
oneSplitImpl = impl;
emit ImplementationUpdated(address(impl));
}
/// @notice Calculate expected returning amount of `destToken`
/// @param fromToken (IERC20) Address of token or `address(0)` for Ether
/// @param destToken (IERC20) Address of token or `address(0)` for Ether
/// @param amount (uint256) Amount for `fromToken`
/// @param parts (uint256) Number of pieces source volume could be splitted,
/// works like granularity, higly affects gas usage. Should be called offchain,
/// but could be called onchain if user swaps not his own funds, but this is still considered as not safe.
/// @param flags (uint256) Flags for enabling and disabling some features, default 0
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags // See contants in IOneSplit.sol
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
(returnAmount, , distribution) = getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
0
);
}
/// @notice Calculate expected returning amount of `destToken`
/// @param fromToken (IERC20) Address of token or `address(0)` for Ether
/// @param destToken (IERC20) Address of token or `address(0)` for Ether
/// @param amount (uint256) Amount for `fromToken`
/// @param parts (uint256) Number of pieces source volume could be splitted,
/// works like granularity, higly affects gas usage. Should be called offchain,
/// but could be called onchain if user swaps not his own funds, but this is still considered as not safe.
/// @param flags (uint256) Flags for enabling and disabling some features, default 0
/// @param destTokenEthPriceTimesGasPrice (uint256) destToken price to ETH multiplied by gas price
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return oneSplitImpl.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
/// @notice Calculate expected returning amount of first `tokens` element to
/// last `tokens` element through ann the middle tokens with corresponding
/// `parts`, `flags` and `destTokenEthPriceTimesGasPrices` array values of each step
/// @param tokens (IERC20[]) Address of token or `address(0)` for Ether
/// @param amount (uint256) Amount for `fromToken`
/// @param parts (uint256[]) Number of pieces source volume could be splitted
/// @param flags (uint256[]) Flags for enabling and disabling some features, default 0
/// @param destTokenEthPriceTimesGasPrices (uint256[]) destToken price to ETH multiplied by gas price
function getExpectedReturnWithGasMulti(
IERC20[] memory tokens,
uint256 amount,
uint256[] memory parts,
uint256[] memory flags,
uint256[] memory destTokenEthPriceTimesGasPrices
)
public
view
returns(
uint256[] memory returnAmounts,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return oneSplitImpl.getExpectedReturnWithGasMulti(
tokens,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrices
);
}
/// @notice Swap `amount` of `fromToken` to `destToken`
/// @param fromToken (IERC20) Address of token or `address(0)` for Ether
/// @param destToken (IERC20) Address of token or `address(0)` for Ether
/// @param amount (uint256) Amount for `fromToken`
/// @param minReturn (uint256) Minimum expected return, else revert
/// @param distribution (uint256[]) Array of weights for volume distribution returned by `getExpectedReturn`
/// @param flags (uint256) Flags for enabling and disabling some features, default 0
function swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags // See contants in IOneSplit.sol
) public payable returns(uint256) {
return swapWithReferral(
fromToken,
destToken,
amount,
minReturn,
distribution,
flags,
address(0),
0
);
}
/// @notice Swap `amount` of `fromToken` to `destToken`
/// param fromToken (IERC20) Address of token or `address(0)` for Ether
/// param destToken (IERC20) Address of token or `address(0)` for Ether
/// @param amount (uint256) Amount for `fromToken`
/// @param minReturn (uint256) Minimum expected return, else revert
/// @param distribution (uint256[]) Array of weights for volume distribution returned by `getExpectedReturn`
/// @param flags (uint256) Flags for enabling and disabling some features, default 0
/// @param referral (address) Address of referral
/// @param feePercent (uint256) Fees percents normalized to 1e18, limited to 0.03e18 (3%)
function swapWithReferral(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags, // See contants in IOneSplit.sol
address referral,
uint256 feePercent
) public payable returns(uint256) {
IERC20[] memory tokens = new IERC20[](2);
tokens[0] = fromToken;
tokens[1] = destToken;
uint256[] memory flagsArray = new uint256[](1);
flagsArray[0] = flags;
swapWithReferralMulti(
tokens,
amount,
minReturn,
distribution,
flagsArray,
referral,
feePercent
);
}
/// @notice Swap `amount` of first element of `tokens` to the latest element of `destToken`
/// @param tokens (IERC20[]) Addresses of token or `address(0)` for Ether
/// @param amount (uint256) Amount for `fromToken`
/// @param minReturn (uint256) Minimum expected return, else revert
/// @param distribution (uint256[]) Array of weights for volume distribution returned by `getExpectedReturn`
/// @param flags (uint256[]) Flags for enabling and disabling some features, default 0
function swapMulti(
IERC20[] memory tokens,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256[] memory flags
) public payable returns(uint256) {
swapWithReferralMulti(
tokens,
amount,
minReturn,
distribution,
flags,
address(0),
0
);
}
/// @notice Swap `amount` of first element of `tokens` to the latest element of `destToken`
/// @param tokens (IERC20[]) Addresses of token or `address(0)` for Ether
/// @param amount (uint256) Amount for `fromToken`
/// @param minReturn (uint256) Minimum expected return, else revert
/// @param distribution (uint256[]) Array of weights for volume distribution returned by `getExpectedReturn`
/// @param flags (uint256[]) Flags for enabling and disabling some features, default 0
/// @param referral (address) Address of referral
/// @param feePercent (uint256) Fees percents normalized to 1e18, limited to 0.03e18 (3%)
function swapWithReferralMulti(
IERC20[] memory tokens,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256[] memory flags,
address referral,
uint256 feePercent
) public payable returns(uint256 returnAmount) {
require(tokens.length >= 2 && amount > 0, "OneSplit: swap makes no sense");
require(flags.length == tokens.length - 1, "OneSplit: flags array length is invalid");
require((msg.value != 0) == tokens.first().isETH(), "OneSplit: msg.value should be used only for ETH swap");
require(feePercent <= 0.03e18, "OneSplit: feePercent out of range");
uint256 gasStart = gasleft();
Balances memory beforeBalances = _getFirstAndLastBalances(tokens, true);
// Transfer From
tokens.first().universalTransferFromSenderToThis(amount);
uint256 confirmed = tokens.first().universalBalanceOf(address(this)).sub(beforeBalances.ofFromToken);
// Swap
tokens.first().universalApprove(address(oneSplitImpl), confirmed);
oneSplitImpl.swapMulti.value(tokens.first().isETH() ? confirmed : 0)(
tokens,
confirmed,
minReturn,
distribution,
flags
);
Balances memory afterBalances = _getFirstAndLastBalances(tokens, false);
// Return
returnAmount = afterBalances.ofDestToken.sub(beforeBalances.ofDestToken);
require(returnAmount >= minReturn, "OneSplit: actual return amount is less than minReturn");
tokens.last().universalTransfer(referral, returnAmount.mul(feePercent).div(1e18));
tokens.last().universalTransfer(msg.sender, returnAmount.sub(returnAmount.mul(feePercent).div(1e18)));
emit Swapped(
tokens.first(),
tokens.last(),
amount,
returnAmount,
minReturn,
distribution,
flags,
referral,
feePercent
);
// Return remainder
if (afterBalances.ofFromToken > beforeBalances.ofFromToken) {
tokens.first().universalTransfer(msg.sender, afterBalances.ofFromToken.sub(beforeBalances.ofFromToken));
}
if ((flags[0] & (FLAG_ENABLE_CHI_BURN | FLAG_ENABLE_CHI_BURN_BY_ORIGIN)) > 0) {
uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length;
_chiBurnOrSell(
((flags[0] & FLAG_ENABLE_CHI_BURN_BY_ORIGIN) > 0) ? tx.origin : msg.sender,
(gasSpent + 14154) / 41947
);
}
else if ((flags[0] & FLAG_ENABLE_REFERRAL_GAS_SPONSORSHIP) > 0) {
uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length;
IReferralGasSponsor(referral).makeGasDiscount(gasSpent, returnAmount, msg.data);
}
}
function claimAsset(IERC20 asset, uint256 amount) public onlyOwner {
asset.universalTransfer(msg.sender, amount);
}
function _chiBurnOrSell(address payable sponsor, uint256 amount) internal {
IUniswapV2Exchange exchange = IUniswapV2Exchange(0xa6f3ef841d371a82ca757FaD08efc0DeE2F1f5e2);
uint256 sellRefund = UniswapV2ExchangeLib.getReturn(exchange, chi, weth, amount);
uint256 burnRefund = amount.mul(18_000).mul(tx.gasprice);
if (sellRefund < burnRefund.add(tx.gasprice.mul(36_000))) {
chi.freeFromUpTo(sponsor, amount);
}
else {
chi.transferFrom(sponsor, address(exchange), amount);
exchange.swap(0, sellRefund, address(this), "");
weth.withdraw(weth.balanceOf(address(this)));
sponsor.transfer(address(this).balance);
}
}
struct Balances {
uint256 ofFromToken;
uint256 ofDestToken;
}
function _getFirstAndLastBalances(IERC20[] memory tokens, bool subValue) internal view returns(Balances memory) {
return Balances({
ofFromToken: tokens.first().universalBalanceOf(address(this)).sub(subValue ? msg.value : 0),
ofDestToken: tokens.last().universalBalanceOf(address(this))
});
}
}
contract ArbitrageContract is FlashLoanReceiverBase(address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8)) {
IERC20[] tokens;
uint256 minReturn;
uint256[] distribution;
uint256[] flags;
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params
)
external
{
//do something
require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance, was the flashLoan successful?");
swapArbitrage(_amount);
// Time to transfer the funds back
uint totalDebt = _amount.add(_fee);
transferFundsBackToPoolInternal(_reserve, totalDebt);
}
function () external payable {
}
function flashloan(
IERC20[] memory _tokens,
uint256 _amountWei,
uint256 _minReturn,
uint256[] memory _distribution,
uint256[] memory _flags
) public onlyOwner {
tokens = _tokens;
minReturn = _minReturn;
distribution = _distribution;
flags = _flags;
bytes memory data = "";
uint amount = _amountWei;
address asset = address(_tokens[0]);
ILendingPool lendingPool = ILendingPool(addressesProvider.getLendingPool());
lendingPool.flashLoan(address(this), asset, amount, data);
}
function swapArbitrage(uint256 _amount) internal {
OneSplitAudit OneSplitAudit_Contract = OneSplitAudit(address(0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e));
require(tokens[0].approve(address(0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e), _amount), "Could not approve firstToken!");
OneSplitAudit_Contract.swapMulti(tokens, _amount, minReturn, distribution, flags);
}
}
| Transfer From Swap Return Return remainder | function swapWithReferralMulti(
IERC20[] memory tokens,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256[] memory flags,
address referral,
uint256 feePercent
) public payable returns(uint256 returnAmount) {
require(tokens.length >= 2 && amount > 0, "OneSplit: swap makes no sense");
require(flags.length == tokens.length - 1, "OneSplit: flags array length is invalid");
require((msg.value != 0) == tokens.first().isETH(), "OneSplit: msg.value should be used only for ETH swap");
require(feePercent <= 0.03e18, "OneSplit: feePercent out of range");
uint256 gasStart = gasleft();
Balances memory beforeBalances = _getFirstAndLastBalances(tokens, true);
tokens.first().universalTransferFromSenderToThis(amount);
uint256 confirmed = tokens.first().universalBalanceOf(address(this)).sub(beforeBalances.ofFromToken);
tokens.first().universalApprove(address(oneSplitImpl), confirmed);
oneSplitImpl.swapMulti.value(tokens.first().isETH() ? confirmed : 0)(
tokens,
confirmed,
minReturn,
distribution,
flags
);
Balances memory afterBalances = _getFirstAndLastBalances(tokens, false);
returnAmount = afterBalances.ofDestToken.sub(beforeBalances.ofDestToken);
require(returnAmount >= minReturn, "OneSplit: actual return amount is less than minReturn");
tokens.last().universalTransfer(referral, returnAmount.mul(feePercent).div(1e18));
tokens.last().universalTransfer(msg.sender, returnAmount.sub(returnAmount.mul(feePercent).div(1e18)));
emit Swapped(
tokens.first(),
tokens.last(),
amount,
returnAmount,
minReturn,
distribution,
flags,
referral,
feePercent
);
if (afterBalances.ofFromToken > beforeBalances.ofFromToken) {
tokens.first().universalTransfer(msg.sender, afterBalances.ofFromToken.sub(beforeBalances.ofFromToken));
}
if ((flags[0] & (FLAG_ENABLE_CHI_BURN | FLAG_ENABLE_CHI_BURN_BY_ORIGIN)) > 0) {
uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length;
_chiBurnOrSell(
((flags[0] & FLAG_ENABLE_CHI_BURN_BY_ORIGIN) > 0) ? tx.origin : msg.sender,
(gasSpent + 14154) / 41947
);
}
else if ((flags[0] & FLAG_ENABLE_REFERRAL_GAS_SPONSORSHIP) > 0) {
uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length;
IReferralGasSponsor(referral).makeGasDiscount(gasSpent, returnAmount, msg.data);
}
}
| 7,572,138 | [
1,
5912,
6338,
12738,
2000,
2000,
10022,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
7720,
1190,
1957,
29084,
5002,
12,
203,
203,
203,
3639,
467,
654,
39,
3462,
8526,
3778,
2430,
16,
203,
203,
203,
3639,
2254,
5034,
3844,
16,
203,
203,
203,
3639,
2254,
5034,
1131,
990,
16,
203,
203,
203,
3639,
2254,
5034,
8526,
3778,
7006,
16,
203,
203,
203,
3639,
2254,
5034,
8526,
3778,
2943,
16,
203,
203,
203,
3639,
1758,
1278,
29084,
16,
203,
203,
203,
3639,
2254,
5034,
14036,
8410,
203,
203,
203,
565,
262,
1071,
8843,
429,
1135,
12,
11890,
5034,
327,
6275,
13,
288,
203,
203,
203,
3639,
2583,
12,
7860,
18,
2469,
1545,
576,
597,
3844,
405,
374,
16,
315,
3335,
5521,
30,
7720,
7297,
1158,
12764,
8863,
203,
203,
203,
3639,
2583,
12,
7133,
18,
2469,
422,
2430,
18,
2469,
300,
404,
16,
315,
3335,
5521,
30,
2943,
526,
769,
353,
2057,
8863,
203,
203,
203,
3639,
2583,
12443,
3576,
18,
1132,
480,
374,
13,
422,
2430,
18,
3645,
7675,
291,
1584,
44,
9334,
315,
3335,
5521,
30,
1234,
18,
1132,
1410,
506,
1399,
1338,
364,
512,
2455,
7720,
8863,
203,
203,
203,
3639,
2583,
12,
21386,
8410,
1648,
374,
18,
4630,
73,
2643,
16,
315,
3335,
5521,
30,
14036,
8410,
596,
434,
1048,
8863,
203,
203,
203,
203,
203,
203,
3639,
2254,
5034,
16189,
1685,
273,
16189,
4482,
5621,
203,
203,
203,
203,
203,
203,
3639,
605,
26488,
3778,
1865,
38,
26488,
273,
389,
588,
3759,
1876,
3024,
38,
26488,
12,
7860,
16,
638,
1769,
203,
203,
203,
203,
203,
203,
203,
203,
3639,
2430,
18,
2
]
|
pragma solidity ^0.4.21;
import "./QuadrantToken.sol";
import "zeppelin-solidity/contracts/lifecycle/Pausable.sol";
import "zeppelin-solidity/contracts/ownership/Ownable.sol";
import "zeppelin-solidity/contracts/math/SafeMath.sol";
import "./Whitelister.sol";
/// @title Dutch auction contract - distribution of a fixed number of tokens using an auction.
/// The auction contract code is based on the Raiden auction contract code. Main differences are: we added rewards tiers to the auction;
/// we added country based rules to the auction; and we added an individual and full refund process.
contract DutchAuction is Pausable {
/*
* Auction for the Quadrant Token.
*
* Terminology:
* 1 token unit = QBI
* token_multiplier set from token's number of decimals (i.e. 10 ** decimals)
*/
using SafeMath for uint;
// Wait 7 days after the end of the auction, before anyone can claim tokens
uint constant private token_claim_waiting_period = 7 days;
uint constant private goal_plus_8 = 8 hours;
uint constant private auction_duration = 14 days;
//Bonus tiers and percentange bonus per tier
uint constant private tier1Time = 24 hours;
uint constant private tier2Time = 48 hours;
uint constant private tier1Bonus = 10;
uint constant private tier2Bonus = 5;
//we need multiplier to keep track of fractional tokens temporarily
uint constant private token_adjuster = 10**18;
//Storage
QuadrantToken public token;
//address public owner_address;
address public wallet_address;
bool public refundIsStopped = true;
bool public refundForIndividualsIsStopped = true;
// Price decay function parameters to be changed depending on the desired outcome
// Starting price in WEI; e.g. 2 * 10 ** 18
uint public price_start;
// Divisor constant; e.g. 524880000
uint public price_constant;
// Divisor exponent; e.g. 3
uint public price_exponent;
//Price adjustment to make sure price doesn't go below pre auction investor price
uint public price_adjustment = 0;
// For calculating elapsed time for price
uint public start_time;
uint public end_time;
uint public start_block;
uint public goal_time = now + 365 days;
// Keep track of all ETH received in the bids
uint public received_wei;
uint public wei_for_excedent;
uint public refundValueForIndividuals;
uint public refundValueForAll;
// Keep track of all ETH received during Tier 1 bonus duration
uint public recievedTier1BonusWei;
// Keep track of all ETH received during Tier 2 bonus duration
uint public recievedTier2BonusWei;
// Keep track of cumulative ETH funds for which the tokens have been claimed
uint public funds_claimed;
//uint public elapsed;
uint public token_multiplier;
// Once this goal (# tokens) is met, auction will close after 8 hours
uint public goal;
// Total number of QBI tokens that will be auctioned
uint public targetTokens;
// Price of QBI token at the end of the auction: Wei per QBI token
uint public final_price;
// Bidder address => bid value
mapping (address => uint) public bids;
//Bidder address => bid that are received during Tier 1 bonus duration
mapping (address => uint) public bidsWithTier1Bonus;
//Bidder address => bid that are received during Tier 2 bonus duration
mapping (address => uint) public bidsWithTier2Bonus;
// Whitelist of individual addresses that are allowed to get refund
mapping (address => bool) public refundForIndividualsWhitelist;
Stages public stage;
struct CountryLimit {
// minimum amount needed to place the bid
uint minAmount;
//max no of people who can bid from this country
uint maxBids;
//counter for no of bids for this country
uint bidCount;
}
mapping (uint => CountryLimit) public countryRulesList;
/*
* Enums
*/
enum Stages {
AuctionDeployed,
AuctionSetUp,
AuctionStarted,
AuctionEnded,
TokensDistributed
}
/*
* Modifiers
*/
modifier atStage(Stages _stage) {
require(stage == _stage);
_;
}
modifier refundIsRunning() {
assert(refundIsStopped == false);
_;
}
modifier refundForIndividualsIsRunning() {
assert(refundForIndividualsIsStopped == false);
_;
}
/*
* Events
*/
event Deployed(uint indexed _price_start,uint indexed _price_constant,uint32 indexed _price_exponent ,uint _price_adjustment);
event Setup();
event AuctionStarted(uint indexed _start_time, uint indexed _block_number);
event BidSubmission(address indexed _sender, uint _amount, uint _balanceFunds);
event ReturnedExcedent(address indexed _sender, uint _amount);
event ClaimedTokens(address indexed _recipient, uint _sent_amount);
event ClaimedBonusTokens(address indexed _recipient, uint _sent_amount);
event AuctionEnded(uint _final_price);
event TokensDistributed();
event Refunded(address indexed beneficiary, uint256 weiAmount);
/*
* Public functions
*/
/// @dev Contract constructor function sets the starting price, divisor constant and
/// divisor exponent for calculating the Dutch Auction price.
/// @param _wallet_address Wallet address to which all contributed ETH will be forwarded.
/// @param _price_start High price in WEI at which the auction starts.
/// @param _price_constant Auction price divisor constant.
/// @param _price_exponent Auction price divisor exponent.
function DutchAuction(
address _wallet_address,
uint _price_start,
uint _price_constant,
uint32 _price_exponent,
uint _price_adjustment,
uint _goal)
public
{
require(_wallet_address != 0x0);
wallet_address = _wallet_address;
//owner_address = msg.sender;
stage = Stages.AuctionDeployed;
changeSettings(_price_start, _price_constant, _price_exponent, _price_adjustment, _goal);
emit Deployed(_price_start, _price_constant, _price_exponent, _price_adjustment);
}
/// @dev Fallback function for the contract, which calls bid() if the auction has started.
function loadForExcedent() public payable whenNotPaused atStage(Stages.AuctionEnded) {
wei_for_excedent = wei_for_excedent.add(msg.value);
}
/// @dev Fallback function for the contract, which calls bid() if the auction has started.
function () public payable atStage(Stages.AuctionStarted) whenNotPaused {
bid();
}
/// @notice Set `tokenAddress` as the token address to be used in the auction.
/// @dev Setup function sets external contracts addresses.
/// @param tokenAddress Token address.
function setup(address tokenAddress) public onlyOwner atStage(Stages.AuctionDeployed) {
require(tokenAddress != 0x0);
token = QuadrantToken(tokenAddress);
// Get number of QBI to be auctioned from token auction balance
targetTokens = token.balanceOf(address(this));
// Set the number of the token multiplier for its decimals
token_multiplier = 10 ** uint(token.decimals());
stage = Stages.AuctionSetUp;
emit Setup();
}
/// @notice Set `_price_start`, `_price_constant` and `_price_exponent` as
/// the new starting price, price divisor constant and price divisor exponent.
/// @dev Changes auction price function parameters before auction is started.
/// @param _price_start Updated start price.
/// @param _price_constant Updated price divisor constant.
/// @param _price_exponent Updated price divisor exponent.
function changeSettings(
uint _price_start,
uint _price_constant,
uint32 _price_exponent,
uint _price_adjustment,
uint _goal
)
internal
{
require(stage == Stages.AuctionDeployed || stage == Stages.AuctionSetUp);
require(_price_start > 0);
require(_price_constant > 0);
price_start = _price_start;
price_constant = _price_constant;
price_exponent = _price_exponent;
price_adjustment = _price_adjustment;
goal = _goal;
}
/// @notice Start the auction.
/// @dev Starts auction and sets start_time.
function startAuction() public onlyOwner atStage(Stages.AuctionSetUp) {
stage = Stages.AuctionStarted;
start_time = now;
end_time = now + auction_duration;
start_block = block.number;
emit AuctionStarted(start_time, start_block);
}
/// @notice Finalize the auction - sets the final QBI token price and changes the auction
/// stage after no bids are allowed anymore.
/// @dev Finalize auction and set the final QBI token price.
function finalizeAuction() public onlyOwner whenNotPaused atStage(Stages.AuctionStarted) {
// Missing funds should be 0 at this point
uint balanceFunds;
uint tokensCommitted;
uint bonusTokensCommitted;
(balanceFunds, tokensCommitted, bonusTokensCommitted) = balanceFundsToEndAuction();
require(balanceFunds == 0 || tokensCommitted.add(bonusTokensCommitted) >= goal || end_time < now );
// Calculate the final price = WEI / QBI
// Reminder: targetTokens is the number of QBI that are auctioned
// we do not consider bonus tokens to calculate price
final_price = token_multiplier.mul(received_wei.add(getBonusWei())).div(targetTokens);
end_time = now;
stage = Stages.AuctionEnded;
emit AuctionEnded(final_price);
assert(final_price > 0);
}
/// --------------------------------- Auction Functions ------------------
/// @notice Send `msg.value` WEI to the auction from the `msg.sender` account.
/// @dev Allows to send a bid to the auction.
function bid() public payable atStage(Stages.AuctionStarted) whenNotPaused {
require(end_time >= now);
require((goal_time.add(goal_plus_8)) > now);
require(msg.value > 0);
require(token.isWhitelisted(msg.sender));
uint userCountryCode = token.getUserResidentCountryCode(msg.sender);
checkCountryRules(userCountryCode);
assert(bids[msg.sender].add(msg.value) >= msg.value);
uint weiAmount = msg.value;
// Missing funds, Tokens Committed, and Bonus Tokens Committed without the current bid value
uint balanceFunds;
uint tokensCommitted;
uint bonusTokensCommitted;
(balanceFunds, tokensCommitted, bonusTokensCommitted) = balanceFundsToEndAuction();
uint bidAmount = weiAmount;
uint returnExcedent = 0;
if (balanceFunds < weiAmount) {
returnExcedent = weiAmount.sub(balanceFunds);
bidAmount = balanceFunds;
}
bool bidBefore = (bids[msg.sender] > 0);
// We require bid values to be less than the funds missing to end the auction
// at the current price.
require((bidAmount <= balanceFunds) && bidAmount > 0);
bids[msg.sender] += bidAmount;
//if bid is recieved during bonus tier 1 duration
if (isInTier1BonusTime() == true) {
recievedTier1BonusWei = recievedTier1BonusWei.add(bidAmount);
bidsWithTier1Bonus[msg.sender] = bidsWithTier1Bonus[msg.sender].add(bidAmount);
//if bid is recieved during bonus tier 2 duration
} else if (isInTier2BonusTime() == true) {
recievedTier2BonusWei = recievedTier2BonusWei.add(bidAmount);
bidsWithTier2Bonus[msg.sender] = bidsWithTier2Bonus[msg.sender].add(bidAmount);
}
// increase the counter for no of bids from that country
if (userCountryCode > 0 && bidBefore == false) {
countryRulesList[userCountryCode].bidCount = countryRulesList[userCountryCode].bidCount.add(1);
}
received_wei = received_wei.add(bidAmount);
// Send bid amount to wallet
wallet_address.transfer(bidAmount);
emit BidSubmission(msg.sender, bidAmount, balanceFunds);
assert(received_wei >= bidAmount);
if (returnExcedent > 0) {
msg.sender.transfer(returnExcedent);
emit ReturnedExcedent(msg.sender, returnExcedent);
}
//Check if auction goal is met. Goal means 90% of total tokens to be auctioned.
hasGoalReached();
}
// This is refund if for any reason auction is cancelled and we refund everyone's money
function refund() public refundIsRunning whenPaused {
uint256 depositedValue = bids[msg.sender];
require(refundValueForAll >= depositedValue);
internalRefund(depositedValue);
refundValueForAll = refundValueForAll.sub(depositedValue);
}
// This is refund if for any reason, we refund particular individual's money
function refundForIndividuals() public refundForIndividualsIsRunning {
require(refundForIndividualsWhitelist[msg.sender]);
uint256 depositedValue = bids[msg.sender];
require(refundValueForIndividuals >= depositedValue);
internalRefund(depositedValue);
refundValueForIndividuals = refundValueForIndividuals.sub(depositedValue);
}
function internalRefund(uint256 depositedValue) private {
uint256 depositedTier1Value = bidsWithTier1Bonus[msg.sender];
uint256 depositedTier2Value = bidsWithTier2Bonus[msg.sender];
require(depositedValue > 0);
bids[msg.sender] = 0;
bidsWithTier1Bonus[msg.sender] = 0;
bidsWithTier2Bonus[msg.sender] = 0;
assert(bids[msg.sender] == 0);
assert(bidsWithTier1Bonus[msg.sender] == 0);
assert(bidsWithTier2Bonus[msg.sender] == 0);
received_wei = received_wei.sub(depositedValue);
recievedTier1BonusWei = recievedTier1BonusWei.sub(depositedTier1Value);
recievedTier2BonusWei = recievedTier2BonusWei.sub(depositedTier2Value);
msg.sender.transfer(depositedValue);
emit Refunded(msg.sender, depositedValue);
}
/// @notice Claim auction tokens for `msg.sender` after the auction has ended.
/// @dev Claims tokens for `msg.sender` after auction. To be used if tokens can
/// be claimed by beneficiaries, individually.
function claimTokens() public whenNotPaused atStage(Stages.AuctionEnded) returns (bool) {
// Waiting period after the end of the auction, before anyone can claim tokens
// Ensures enough time to check if auction was finalized correctly
// before users start transacting tokens
address receiver_address = msg.sender;
require(now > end_time + token_claim_waiting_period);
require(receiver_address != 0x0);
// Check if the wallet address of requestor is in the whitelist
require(token.isWhitelisted(address(this)));
require(token.isWhitelisted(receiver_address));
// Make sure there is enough wei for the excedent value of the bid
require(wei_for_excedent > final_price);
if (bids[receiver_address] == 0) {
return false;
}
// Number of QBI = bid_wei / final price
uint tokens = token_adjuster.mul(token_multiplier.mul(bids[receiver_address])).div(final_price);
// Calculate total tokens = tokens + bonus tokens
// Calculate total effective bid including bonus
uint totalBid;
uint totalTokens;
(totalBid, totalTokens) = calculateBonus(tokens);
totalTokens = totalTokens.div(token_adjuster);
uint returnExcedent = totalBid.sub(totalTokens.mul(final_price));
// Update the total amount of funds for which tokens have been claimed
funds_claimed += bids[receiver_address];
// Set receiver bid to 0 before assigning tokens
bids[receiver_address] = 0;
bidsWithTier1Bonus[receiver_address] = 0;
bidsWithTier2Bonus[receiver_address] = 0;
// After the last tokens are claimed, we change the auction stage
// Due to the above logic, rounding errors will not be an issue
if (funds_claimed == received_wei) {
stage = Stages.TokensDistributed;
emit TokensDistributed();
}
//assert(final_price > returnExcedent);
if (returnExcedent > 0) {
wei_for_excedent = wei_for_excedent.sub(returnExcedent);
msg.sender.transfer(returnExcedent);
emit ReturnedExcedent(msg.sender, returnExcedent);
}
assert(token.transfer(receiver_address, totalTokens));
emit ClaimedTokens(receiver_address, totalTokens);
assert(token.balanceOf(receiver_address) >= totalTokens);
assert(bids[receiver_address] == 0);
assert(bidsWithTier1Bonus[receiver_address] == 0);
assert(bidsWithTier2Bonus[receiver_address] == 0);
return true;
}
function calculateBonus(uint tokens) private constant returns (uint totalBid, uint totalTokens) {
// This function returns the total effective bid = bid + bonus bid
// This function returns the total number of tokens = tokens + bonus tokens
address receiver_address = msg.sender;
uint tier1bonusBid = (bidsWithTier1Bonus[receiver_address].mul(tier1Bonus)).div(100);
uint tier2bonusBid = (bidsWithTier2Bonus[receiver_address].mul(tier2Bonus)).div(100);
uint tier1bonusTokens = token_adjuster.mul(token_multiplier.mul(bidsWithTier1Bonus[receiver_address])).mul(tier1Bonus).div(final_price.mul(100));
uint tier2bonusTokens = token_adjuster.mul(token_multiplier.mul(bidsWithTier2Bonus[receiver_address])).mul(tier2Bonus).div(final_price.mul(100));
uint bonusBid = tier1bonusBid.add(tier2bonusBid);
uint bonusTokens = tier1bonusTokens.add(tier2bonusTokens);
totalBid = bids[receiver_address].add(bonusBid);
totalTokens = tokens.add(bonusTokens);
}
/// @notice Get the QBI price in WEI during the auction, at the time of
/// calling this function. Returns `0` if auction has ended.
/// Returns `price_start` before auction has started.
/// @dev Calculates the current QBI token price in WEI.
/// @return Returns WEI per QBI.
function price() public view returns (uint) {
if (stage == Stages.AuctionEnded ||
stage == Stages.TokensDistributed) {
return 0;
}
return calcTokenPrice();
}
/// @notice Get the missing funds needed to end the auction,
/// calculated at the current QBI price in WEI.
/// @dev The missing funds amount necessary to end the auction at the current QBI price in WEI.
/// @return Returns the missing funds amount in WEI.
function balanceFundsToEndAuction() public view returns (uint balanceFunds, uint tokensCommitted, uint bonusTokensCommitted) {
uint tokenPrice = 0;
// targetTokens = total number of Rei (QCOIN * token_multiplier) that is auctioned
//we need to consider bonus wei also in missing funds
uint bonusWeiSoFar = 0;
(tokenPrice, tokensCommitted, bonusTokensCommitted, bonusWeiSoFar) = tokenCommittedSoFar();
uint required_wei_at_price = targetTokens.mul(tokenPrice).div(token_multiplier);
if (required_wei_at_price <= received_wei.add(bonusWeiSoFar)) {
balanceFunds = 0;
} else {
balanceFunds = required_wei_at_price.sub(received_wei.add(bonusWeiSoFar));
if (isInTier1BonusTime() == true) {
// Missing Funds are effectively smaller
balanceFunds = (balanceFunds.mul(100)).div(tier1Bonus.add(100));
} else if (isInTier2BonusTime()) {
//Missing Funds are effectively smaller
balanceFunds = (balanceFunds.mul(100)).div(tier2Bonus.add(100));
}
}
// assert(required_wei_at_price - received_wei > 0);
// return (required_wei_at_price - received_wei, received_wei/tokenPrice);
}
function tokenCommittedSoFar() public view returns (uint tokenPrice, uint tokensCommitted, uint bonusTokensCommitted, uint bonusWeiSoFar) {
tokenPrice = price();
tokensCommitted = received_wei.div(tokenPrice);
//amount comitted in bonus
bonusWeiSoFar = getBonusWei();
bonusTokensCommitted = bonusWeiSoFar.div(tokenPrice);
}
function loadRefundForIndividuals() public payable refundForIndividualsIsRunning onlyOwner {
require (msg.value > 0);
refundValueForIndividuals = refundValueForIndividuals.add(msg.value);
}
function loadRefundForAll() public payable refundIsRunning whenPaused onlyOwner {
require (msg.value > 0);
refundValueForAll = refundValueForAll.add(msg.value);
}
/// @notice Adds account addresses to individual refund whitelist.
/// @dev Adds account addresses to individual refund whitelist.
/// @param _bidder_addresses Array of addresses.
function addToRefundForIndividualsWhitelist(address[] _bidder_addresses) public onlyOwner {
for (uint32 i = 0; i < _bidder_addresses.length; i++) {
refundForIndividualsWhitelist[_bidder_addresses[i]] = true;
}
}
/// @notice Removes account addresses from individual refund whitelist.
/// @dev Removes account addresses from individual refund whitelist.
/// @param _bidder_addresses Array of addresses.
function removeFromToRefundForIndividualsWhitelist(address[] _bidder_addresses) public onlyOwner {
for (uint32 i = 0; i < _bidder_addresses.length; i++) {
refundForIndividualsWhitelist[_bidder_addresses[i]] = false;
}
}
///change white lister
function changeWalletAddress(address walletAddress) public onlyOwner {
require(walletAddress != 0);
wallet_address = walletAddress;
}
///change Start Price
function changeStartPrice(uint priceStart) public onlyOwner {
require(priceStart != 0);
require(stage == Stages.AuctionDeployed || stage == Stages.AuctionSetUp);
price_start = priceStart;
}
///change Price Constant
function changePriceConstant(uint priceConstant) public onlyOwner {
require(priceConstant != 0);
require(stage == Stages.AuctionDeployed || stage == Stages.AuctionSetUp);
price_constant = priceConstant;
}
///change Price Exponent
function changePriceExponent(uint32 priceExponent) public onlyOwner {
require(priceExponent != 0);
require(stage == Stages.AuctionDeployed || stage == Stages.AuctionSetUp);
price_exponent = priceExponent;
}
///change Price Exponent
function changePriceAdjustment(uint32 priceAdjustment) public onlyOwner {
require(priceAdjustment != 0);
require(stage == Stages.AuctionDeployed || stage == Stages.AuctionSetUp);
price_adjustment = priceAdjustment;
}
///change Token Multiplier
function changeTokenMultiplier(uint32 tokenMultiplier) public onlyOwner {
require(tokenMultiplier != 0);
require(stage == Stages.AuctionDeployed || stage == Stages.AuctionSetUp);
token_multiplier = tokenMultiplier;
}
// start stop refund to everyone
function refundToggle() public onlyOwner {
refundIsStopped = !refundIsStopped;
}
// start stop refund to particular individuals
function refundForIndividualsToggle() public onlyOwner {
refundForIndividualsIsStopped = !refundForIndividualsIsStopped;
}
function transferContractBalanceToWallet() public onlyOwner {
wallet_address.transfer(address(this).balance);
}
function transferTokenBalanceToWallet() public onlyOwner {
assert(token.transfer(wallet_address, token.balanceOf(this)));
}
function getBonusWei() private view returns (uint) {
// Returns effective Wei amount that gives the bidder bonus tokens
uint tier1bonusWeiSoFar = (recievedTier1BonusWei.mul(tier1Bonus)).div(100);
uint tier2bonusWeiSoFar = (recievedTier2BonusWei.mul(tier2Bonus)).div(100);
return tier1bonusWeiSoFar.add(tier2bonusWeiSoFar);
}
function isInTier1BonusTime() public view returns(bool) {
return (now <= start_time.add(tier1Time));
}
function isInTier2BonusTime() public view returns(bool) {
return (now <= start_time.add(tier2Time));
}
function hasGoalReached() public returns (bool) {
if( goal_time > now) {
uint tokensCommitted;
uint bonusTokensCommitted;
uint tokenPrice = 0;
uint bonusWeiSoFar = 0;
(tokenPrice, tokensCommitted, bonusTokensCommitted, bonusWeiSoFar) = tokenCommittedSoFar();
//We consider bonus tokens while checking if goal is met
if (tokensCommitted.add(bonusTokensCommitted) >= goal){
goal_time = now;
}
}
return (goal_time < now);
}
function getAuctionInfo() public view returns (uint receivedWei, uint startPrice, uint currentPrice, uint finalPrice, uint tokenSupply, uint auctionStartTime, uint auctionEndTime) {
receivedWei = received_wei;
startPrice = price_start;
currentPrice = price();
tokenSupply = targetTokens;
auctionStartTime = start_time;
auctionEndTime = end_time;
finalPrice = final_price;
}
function addUpdateCountriesRules(uint[] countries, uint[] minAmounts, uint[] maxBids) public onlyOwner {
for (uint32 i = 0; i < countries.length; i++) {
addUpdateCountryRules(countries[i], minAmounts[i], maxBids[i]);
}
}
///add rules for a country
function addUpdateCountryRules(uint countryCode, uint minAmount, uint maxBids) public onlyOwner {
CountryLimit storage countryLimit = countryRulesList[countryCode];
if (countryLimit.minAmount != minAmount) {
countryLimit.minAmount = minAmount;
}
if (countryLimit.maxBids != maxBids) {
countryLimit.maxBids = maxBids;
}
}
function getCountryRule(uint countryCode) public view returns (uint, uint, uint) {
return (countryRulesList[countryCode].minAmount, countryRulesList[countryCode].maxBids, countryRulesList[countryCode].bidCount);
}
function checkCountryRules(uint countryCode) private view {
CountryLimit storage countryRule = countryRulesList[countryCode];
if (countryRule.minAmount > 0) {
require(countryRule.minAmount <= msg.value);
}
if (countryRule.maxBids > 0) {
require(countryRule.bidCount < countryRule.maxBids);
}
}
/*
* Private functions
*/
/// @dev Calculates the token price (WEI / QBI) at the current timestamp
/// during the auction; elapsed time = 0 before auction starts.
/// Based on the provided parameters, the price does not change in the first
/// `price_constant^(1/price_exponent)` seconds due to rounding.
/// Rounding in `decay_rate` also produces values that increase instead of decrease
/// in the beginning; these spikes decrease over time and are noticeable
/// only in first hours. This should be calculated before usage.
/// @return Returns the token price - Wei per QBI.
function calcTokenPrice() private view returns (uint) {
uint elapsed;
if (stage == Stages.AuctionStarted) {
elapsed = now.sub(start_time);
}
uint decay_rate = (elapsed ** price_exponent).div(price_constant);
return (price_start.mul(elapsed.add(1)).div(elapsed.add(1).add(decay_rate))).add(price_adjustment);
}
}
| @dev Fallback function for the contract, which calls bid() if the auction has started. | function loadForExcedent() public payable whenNotPaused atStage(Stages.AuctionEnded) {
wei_for_excedent = wei_for_excedent.add(msg.value);
}
| 12,907,221 | [
1,
12355,
445,
364,
326,
6835,
16,
1492,
4097,
9949,
1435,
309,
326,
279,
4062,
711,
5746,
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
]
| [
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,
1262,
1290,
424,
3263,
319,
1435,
1071,
8843,
429,
1347,
1248,
28590,
622,
8755,
12,
31359,
18,
37,
4062,
28362,
13,
288,
203,
4202,
732,
77,
67,
1884,
67,
338,
3263,
319,
273,
732,
77,
67,
1884,
67,
338,
3263,
319,
18,
1289,
12,
3576,
18,
1132,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/4/0x8C3C9cE4a10D6df1F74c8442A7c1c196b980A142/sources/contracts/BHT.sol | token metadata by id | mapping(uint256 => Token) tokens;
| 692,373 | [
1,
2316,
1982,
635,
612,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
12,
11890,
5034,
516,
3155,
13,
2430,
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
]
|
./partial_match/1/0xfC9268E8c699071C62f63711dE06097A4E9d4C36/sources/rewardpool.sol | for tracking of overall deposits
| uint256 private accountedBalance; | 15,687,187 | [
1,
1884,
11093,
434,
13914,
443,
917,
1282,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
3238,
2236,
329,
13937,
31,
565,
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/1/0x06e5bffEdA8383848Fd04D047c839ecec6329627/sources/contracts/Livestreambets.sol | A race must have at least 2 options and at most maxOptions. | function createGame(
uint256 expirationPeriod_,
uint256 options_,
uint256 minPositionSize_,
uint256 maxAmountPerOption_
) public onlyOwnerOrGameManager {
if (options_ < 2 || options_ > maxOptions) {
revert InvalidGameConfiguration();
}
Game(
)
);
}
| 9,709,522 | [
1,
37,
17996,
1297,
1240,
622,
4520,
576,
702,
471,
622,
4486,
943,
1320,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
752,
12496,
12,
203,
3639,
2254,
5034,
7686,
5027,
67,
16,
203,
3639,
2254,
5034,
702,
67,
16,
203,
3639,
2254,
5034,
1131,
2555,
1225,
67,
16,
203,
3639,
2254,
5034,
943,
6275,
2173,
1895,
67,
203,
565,
262,
1071,
1338,
5541,
1162,
12496,
1318,
288,
203,
3639,
309,
261,
2116,
67,
411,
576,
747,
702,
67,
405,
943,
1320,
13,
288,
203,
5411,
15226,
1962,
12496,
1750,
5621,
203,
3639,
289,
203,
203,
5411,
14121,
12,
203,
5411,
262,
203,
3639,
11272,
203,
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
]
|
./partial_match/1/0x1444fF79A0837D42A9Cef76B1c4618D0FCDc6a16/sources/JOJOINU.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("JoJo Inu", "JoJo") {
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 = 4;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 4;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1_000_000_000 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 4,006,353 | [
1,
10157,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
1435,
4232,
39,
3462,
2932,
46,
83,
46,
83,
657,
89,
3113,
315,
46,
83,
46,
83,
7923,
288,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
203,
5411,
374,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
203,
3639,
11272,
203,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
24899,
318,
291,
91,
438,
58,
22,
8259,
3631,
638,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
10756,
203,
5411,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
3639,
389,
542,
22932,
690,
3882,
278,
12373,
4154,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
203,
3639,
2254,
5034,
389,
70,
9835,
3882,
21747,
14667,
273,
1059,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
48,
18988,
24237,
14667,
273,
374,
31,
203,
3639,
2254,
5034,
2
]
|
pragma solidity 0.5.6;
// ---------------------------------------------------------------------------
// Message_Transport
// ---------------------------------------------------------------------------
//import './SafeMath.sol';
/*
Overflow protected math functions
*/
contract SafeMath {
/**
constructor
*/
constructor() public {
}
/**
@dev returns the sum of _x and _y, asserts if the calculation overflows
@param _x value 1
@param _y value 2
@return sum
*/
function safeAdd(uint256 _x, uint256 _y) pure internal returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
/**
@dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number
@param _x minuend
@param _y subtrahend
@return difference
*/
function safeSub(uint256 _x, uint256 _y) pure internal returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
/**
@dev returns the product of multiplying _x by _y, asserts if the calculation overflows
@param _x factor 1
@param _y factor 2
@return product
*/
function safeMul(uint256 _x, uint256 _y) pure internal returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
//import './Ownable.sol';
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract MessageTransport is SafeMath, Ownable {
// -------------------------------------------------------------------------
// events
// etherscan.io's Event Log API does not have an option to match multiple values
// in an individual topic. so in order to match any one of three message id's we
// duplicate the message id into 3 topic position.
// -------------------------------------------------------------------------
event InviteEvent(address indexed _toAddr, address indexed _fromAddr);
event MessageEvent(uint indexed _id1, uint indexed _id2, uint indexed _id3,
address _fromAddr, address _toAddr, address _via, uint _txCount, uint _rxCount, uint _attachmentIdx, uint _ref, bytes message);
event MessageTxEvent(address indexed _fromAddr, uint indexed _txCount, uint _id);
event MessageRxEvent(address indexed _toAddr, uint indexed _rxCount, uint _id);
// -------------------------------------------------------------------------
// Account structure
// there is a single account structure for all account types
// -------------------------------------------------------------------------
struct Account {
bool isValid;
uint messageFee; // pay this much for every non-spam message sent to this account
uint spamFee; // pay this much for every spam message sent to this account
uint feeBalance; // includes spam and non-spam fees
uint recvMessageCount; // total messages received
uint sentMessageCount; // total messages sent
bytes publicKey; // encryption parameter
bytes encryptedPrivateKey; // encryption parameter
mapping (address => uint256) peerRecvMessageCount;
mapping (uint256 => uint256) recvIds;
mapping (uint256 => uint256) sentIds;
}
// -------------------------------------------------------------------------
// data storage
// -------------------------------------------------------------------------
bool public isLocked;
address public tokenAddr;
uint public messageCount;
uint public retainedFeesBalance;
mapping (address => bool) public trusted;
mapping (address => Account) public accounts;
// -------------------------------------------------------------------------
// modifiers
// -------------------------------------------------------------------------
modifier trustedOnly {
require(trusted[msg.sender] == true, "trusted only");
_;
}
// -------------------------------------------------------------------------
// MessageTransport constructor
// -------------------------------------------------------------------------
constructor(address _tokenAddr) public {
tokenAddr = _tokenAddr;
}
function setTrust(address _trustedAddr, bool _trust) public onlyOwner {
trusted[_trustedAddr] = _trust;
}
// -------------------------------------------------------------------------
// register a message account
// the decryption key for the encryptedPrivateKey should be guarded with the
// same secrecy and caution as the ethereum private key. in fact the decryption
// key should never be tranmitted or stored at all -- but always derived from a
// message signature; that is, through metamask.
// -------------------------------------------------------------------------
function register(uint256 _messageFee, uint256 _spamFee, bytes memory _publicKey, bytes memory _encryptedPrivateKey) public {
Account storage _account = accounts[msg.sender];
require(_account.isValid == false, "account already registered");
_account.publicKey = _publicKey;
_account.encryptedPrivateKey = _encryptedPrivateKey;
_account.isValid = true;
_modifyAccount(_account, _messageFee, _spamFee);
}
function modifyAccount(uint256 _messageFee, uint256 _spamFee) public {
Account storage _account = accounts[msg.sender];
require(_account.isValid == true, "not registered");
_modifyAccount(_account, _messageFee, _spamFee);
}
function _modifyAccount(Account storage _account, uint256 _messageFee, uint256 _spamFee) internal {
_account.messageFee = _messageFee;
_account.spamFee = _spamFee;
}
// -------------------------------------------------------------------------
// get the number of messages that have been sent from one peer to another
// -------------------------------------------------------------------------
function getPeerMessageCount(address _from, address _to) public view returns(uint256 _messageCount) {
Account storage _account = accounts[_to];
_messageCount = _account.peerRecvMessageCount[_from];
}
// -------------------------------------------------------------------------
// get _maxResults message id's of received messages
// note that array will always have _maxResults entries. ignore messageID = 0
// -------------------------------------------------------------------------
function getRecvMsgs(address _to, uint256 _startIdx, uint256 _maxResults) public view returns(uint256 _idx, uint256[] memory _messageIds) {
uint _count = 0;
Account storage _recvAccount = accounts[_to];
uint256 _recvMessageCount = _recvAccount.recvMessageCount;
_messageIds = new uint256[](_maxResults);
mapping(uint256 => uint256) storage _recvIds = _recvAccount.recvIds;
//first messageID is at recvIds[0];
for (_idx = _startIdx; _idx < _recvMessageCount; ++_idx) {
_messageIds[_count] = _recvIds[_idx];
if (block.gaslimit >= _maxResults) //injected CONTRACT AFFECTED BY MINERS
break;
}
}
// -------------------------------------------------------------------------
// get _maxResults message id's of sent messages
// note that array will always have _maxResults entries. ignore messageID = 0
// -------------------------------------------------------------------------
function getSentMsgs(address _from, uint256 _startIdx, uint256 _maxResults) public view returns(uint256 _idx, uint256[] memory _messageIds) {
uint _count = 0;
Account storage _sentAccount = accounts[_from];
uint256 _sentMessageCount = _sentAccount.sentMessageCount;
_messageIds = new uint256[](_maxResults);
mapping(uint256 => uint256) storage _sentIds = _sentAccount.sentIds;
//note first messageID is at recvIds[0];
for (_idx = _startIdx; _idx < _sentMessageCount; ++_idx) {
_messageIds[_count] = _sentIds[_idx];
if (block.timestamp >= _maxResults) //injected CONTRACT AFFECTED BY MINERS
break;
}
}
// -------------------------------------------------------------------------
// get the required fee in order to send a message (or spam message)
// the second version is handy for calls from partner contract(s)
// -------------------------------------------------------------------------
function getFee(address _toAddr) public view returns(uint256 _fee) {
Account storage _sendAccount = accounts[msg.sender];
Account storage _recvAccount = accounts[_toAddr];
if (block.number == 0) //injected CONTRACT AFFECTED BY MINERS
_fee = _recvAccount.spamFee;
else
_fee = _recvAccount.messageFee;
}
function getFee(address _fromAddr, address _toAddr) public view trustedOnly returns(uint256 _fee) {
Account storage _sendAccount = accounts[_fromAddr];
Account storage _recvAccount = accounts[_toAddr];
if (block.gaslimit == 0) //injected CONTRACT AFFECTED BY MINERS
_fee = _recvAccount.spamFee;
else
_fee = _recvAccount.messageFee;
}
// -------------------------------------------------------------------------
// send message
// the via address is set to the address of the trusted contract (or zero in
// case the fromAddr is msg.sender). in this way a DApp can indicate the via
// address to the recipient when the message was not sent directly from the
// sender.
// -------------------------------------------------------------------------
function sendMessage(address _toAddr, uint attachmentIdx, uint _ref, bytes memory _message) public payable returns (uint _messageId) {
uint256 _noDataLength = 4 + 32 + 32 + 32 + 64;
_messageId = doSendMessage(_noDataLength, msg.sender, _toAddr, address(0), attachmentIdx, _ref, _message);
}
function sendMessage(address _fromAddr, address _toAddr, uint attachmentIdx, uint _ref, bytes memory _message) public payable trustedOnly returns (uint _messageId) {
uint256 _noDataLength = 4 + 32 + 32 + 32 + 32 + 64;
_messageId = doSendMessage(_noDataLength, _fromAddr, _toAddr, msg.sender, attachmentIdx, _ref, _message);
}
function doSendMessage(uint256 _noDataLength, address _fromAddr, address _toAddr, address _via, uint attachmentIdx, uint _ref, bytes memory _message) internal returns (uint _messageId) {
Account storage _sendAccount = accounts[_fromAddr];
Account storage _recvAccount = accounts[_toAddr];
require(_sendAccount.isValid == true, "sender not registered");
require(_recvAccount.isValid == true, "recipient not registered");
//if message text is empty then no fees are necessary, and we don't create a log entry.
//after you introduce yourself to someone this way their subsequent message to you won't
//incur your spamFee.
if (block.timestamp > _noDataLength) { //injected CONTRACT AFFECTED BY MINERS
if (block.number == 0) //injected CONTRACT AFFECTED BY MINERS
require(msg.value >= _recvAccount.spamFee, "spam fee is insufficient");
else
require(msg.value >= _recvAccount.messageFee, "fee is insufficient");
messageCount = safeAdd(messageCount, 1);
_recvAccount.recvIds[_recvAccount.recvMessageCount] = messageCount;
_sendAccount.sentIds[_sendAccount.sentMessageCount] = messageCount;
_recvAccount.recvMessageCount = safeAdd(_recvAccount.recvMessageCount, 1);
_sendAccount.sentMessageCount = safeAdd(_sendAccount.sentMessageCount, 1);
emit MessageEvent(messageCount, messageCount, messageCount, _fromAddr, _toAddr, _via, _sendAccount.sentMessageCount, _recvAccount.recvMessageCount, attachmentIdx, _ref, _message);
emit MessageTxEvent(_fromAddr, _sendAccount.sentMessageCount, messageCount);
emit MessageRxEvent(_toAddr, _recvAccount.recvMessageCount, messageCount);
//return message id, which a calling function might want to log
_messageId = messageCount;
} else {
emit InviteEvent(_toAddr, _fromAddr);
_messageId = 0;
}
uint _retainAmount = safeMul(msg.value, 30) / 100;
retainedFeesBalance = safeAdd(retainedFeesBalance, _retainAmount);
_recvAccount.feeBalance = safeAdd(_recvAccount.feeBalance, safeSub(msg.value, _retainAmount));
_recvAccount.peerRecvMessageCount[_fromAddr] = safeAdd(_recvAccount.peerRecvMessageCount[_fromAddr], 1);
}
// -------------------------------------------------------------------------
// withdraw accumulated message & spam fees
// -------------------------------------------------------------------------
function withdraw() public {
Account storage _account = accounts[msg.sender];
uint _amount = _account.feeBalance;
_account.feeBalance = 0;
msg.sender.transfer(_amount);
}
// -------------------------------------------------------------------------
// pay retained fees funds to token contract; burn half.
// -------------------------------------------------------------------------
function withdrawRetainedFees() public {
uint _amount = retainedFeesBalance / 2;
address(0).transfer(_amount);
_amount = safeSub(retainedFeesBalance, _amount);
retainedFeesBalance = 0;
(bool paySuccess, ) = tokenAddr.call.value(_amount)("");
require(paySuccess, "failed to transfer fees");
}
} | pay this much for every non-spam message sent to this account
| uint messageFee; | 14,043,775 | [
1,
10239,
333,
9816,
364,
3614,
1661,
17,
1752,
301,
883,
3271,
358,
333,
2236,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
883,
14667,
31,
5411,
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
]
|
pragma solidity ^0.4.21;
// zeppelin-solidity: 1.9.0
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev 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;
}
}
contract Membership is Ownable {
using SafeMath for uint;
mapping(address => bool) public isAdmin;
mapping(address => uint) public userToMemberIndex;
mapping(uint => uint[]) public tierToMemberIndexes;
struct Member {
address addr;
uint tier;
uint tierIndex;
uint memberIndex;
}
Member[] private members;
event NewMember(address user, uint tier);
event UpdatedMemberTier(address user, uint oldTier, uint newTier);
event RemovedMember(address user, uint tier);
modifier onlyAdmin() {
require(isAdmin[msg.sender]);
_;
}
modifier isValidTier(uint _tier) {
require(_tier >= 1 && _tier <= 4);
_;
}
modifier notTryingToChangeFromTier1(address _user, uint _tier) {
require(members[userToMemberIndex[_user]].tier != _tier);
_;
}
modifier isMember(address _user) {
require(userToMemberIndex[_user] != 0);
_;
}
modifier isValidAddr(address _trgt) {
require(_trgt != address(0));
_;
}
constructor() public {
Member memory member = Member(address(0), 0, 0, 0);
members.push(member);
}
function addAdmin(address _user)
external
onlyOwner
{
isAdmin[_user] = true;
}
function removeMember(address _user)
external
onlyAdmin
isValidAddr(_user)
isMember(_user)
{
uint index = userToMemberIndex[_user];
require(index != 0);
Member memory removingMember = members[index];
uint tier = removingMember.tier;
uint lastTierIndex = tierToMemberIndexes[removingMember.tier].length - 1;
uint lastTierMemberIndex = tierToMemberIndexes[removingMember.tier][lastTierIndex];
Member storage lastTierMember = members[lastTierMemberIndex];
lastTierMember.tierIndex = removingMember.tierIndex;
tierToMemberIndexes[removingMember.tier][removingMember.tierIndex] = lastTierMember.memberIndex;
tierToMemberIndexes[removingMember.tier].length--;
Member storage lastMember = members[members.length - 1];
if (lastMember.addr != removingMember.addr) {
userToMemberIndex[lastMember.addr] = removingMember.memberIndex;
tierToMemberIndexes[lastMember.tier][lastMember.tierIndex] = removingMember.memberIndex;
lastMember.memberIndex = removingMember.memberIndex;
members[removingMember.memberIndex] = lastMember;
}
userToMemberIndex[removingMember.addr] = 0;
members.length--;
emit RemovedMember(_user, tier);
}
function addNewMember(address _user, uint _tier)
internal
{
// it's a new member
uint memberIndex = members.length; // + 1; // add 1 to keep index 0 unoccupied
uint tierIndex = tierToMemberIndexes[_tier].length;
Member memory newMember = Member(_user, _tier, tierIndex, memberIndex);
members.push(newMember);
userToMemberIndex[_user] = memberIndex;
tierToMemberIndexes[_tier].push(memberIndex);
emit NewMember(_user, _tier);
}
function updateExistingMember(address _user, uint _newTier)
internal
{
// this user is a member in another tier, remove him from that tier,
// and add him to the new tier
Member storage existingMember = members[userToMemberIndex[_user]];
uint oldTier = existingMember.tier;
uint tierIndex = existingMember.tierIndex;
uint lastTierIndex = tierToMemberIndexes[oldTier].length - 1;
if (tierToMemberIndexes[oldTier].length > 1 && tierIndex != lastTierIndex) {
Member storage lastMember = members[tierToMemberIndexes[oldTier][lastTierIndex]];
tierToMemberIndexes[oldTier][tierIndex] = lastMember.memberIndex;
lastMember.tierIndex = tierIndex;
}
tierToMemberIndexes[oldTier].length--;
tierToMemberIndexes[_newTier].push(existingMember.memberIndex);
existingMember.tier = _newTier;
existingMember.tierIndex = tierToMemberIndexes[_newTier].length - 1;
emit UpdatedMemberTier(_user, oldTier, _newTier);
}
function setMemberTier(address _user, uint _tier)
external
onlyAdmin
isValidAddr(_user)
isValidTier(_tier)
{
if (userToMemberIndex[_user] == 0) {
addNewMember(_user, _tier);
} else {
uint currentTier = members[userToMemberIndex[_user]].tier;
if (currentTier != _tier) {
// user's in tier 1 are lifetime tier 1 users
require(currentTier != 1);
updateExistingMember(_user, _tier);
}
}
}
function getTierOfMember(address _user)
external
view
returns (uint)
{
return members[userToMemberIndex[_user]].tier;
}
function getMembersOfTier(uint _tier)
external
view
returns (address[])
{
address[] memory addressesOfTier = new address[](tierToMemberIndexes[_tier].length);
for (uint i = 0; i < tierToMemberIndexes[_tier].length; i++) {
addressesOfTier[i] = members[tierToMemberIndexes[_tier][i]].addr;
}
return addressesOfTier;
}
function getMembersOfTierCount(uint _tier)
external
view
returns (uint)
{
return tierToMemberIndexes[_tier].length;
}
function getMembersCount()
external
view
returns (uint)
{
if (members.length == 0) {
return 0;
} else {
// remove sentinel at index zero from count
return members.length - 1;
}
}
function getMemberByIdx(uint _idx)
external
view
returns (address, uint)
{
Member memory member = members[_idx];
return (member.addr, member.tier);
}
function isUserMember(address _user)
external
view
returns (bool)
{
return userToMemberIndex[_user] != 0;
}
function getMemberIdxOfUser(address _user)
external
view
returns (uint)
{
return userToMemberIndex[_user];
}
} | remove sentinel at index zero from count | function getMembersCount()
external
view
returns (uint)
{
if (members.length == 0) {
return 0;
return members.length - 1;
}
}
| 15,869,026 | [
1,
4479,
20285,
622,
770,
3634,
628,
1056,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
29106,
1380,
1435,
203,
565,
3903,
203,
565,
1476,
203,
565,
1135,
261,
11890,
13,
203,
225,
288,
203,
565,
309,
261,
7640,
18,
2469,
422,
374,
13,
288,
203,
1377,
327,
374,
31,
203,
1377,
327,
4833,
18,
2469,
300,
404,
31,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.4.23;
import "./Ownable.sol";
/** @title User
* @dev User is the base class for all'the users: Student, Professor and Admin
*/
contract User is Ownable {
bytes private name;
bytes private surname;
bytes private socialNumber;
uint private serial;
/** @dev Constructor of User
* @param _name user name
* @param _surname user surname
* @param _socialNumber user social number
* @param _serial user indentifier inside the university
*/
constructor( bytes _name, bytes _surname, bytes _socialNumber, uint _serial) public {
name = _name;
surname = _surname;
socialNumber = _socialNumber;
serial = _serial;
}
/** @dev get for user name
* @return bytes the string of the name
*/
function getName() public view returns(bytes) {
return name;
}
/** @dev get for user surname
* @return bytes the string of the surname
*/
function getSurname() public view returns(bytes) {
return surname;
}
/** @dev get for user social number
* @return bytes the string of the social number
*/
function getSocialNumber() public view returns(bytes) {
return socialNumber;
}
/** @dev get for user serial
* @return uint the string of the serial
*/
function getSerial() public view returns(uint) {
return serial;
}
}
| * @title User @dev User is the base class for all'the users: Student, Professor and Admin/ | contract User is Ownable {
bytes private name;
bytes private surname;
bytes private socialNumber;
uint private serial;
constructor( bytes _name, bytes _surname, bytes _socialNumber, uint _serial) public {
name = _name;
surname = _surname;
socialNumber = _socialNumber;
serial = _serial;
}
function getName() public view returns(bytes) {
return name;
}
function getSurname() public view returns(bytes) {
return surname;
}
function getSocialNumber() public view returns(bytes) {
return socialNumber;
}
function getSerial() public view returns(uint) {
return serial;
}
}
| 6,343,168 | [
1,
1299,
565,
2177,
353,
326,
1026,
667,
364,
777,
1404,
580,
3677,
30,
934,
1100,
319,
16,
1186,
74,
403,
280,
471,
7807,
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
]
| [
1,
1,
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
]
| [
1,
16351,
2177,
353,
14223,
6914,
288,
203,
565,
1731,
3238,
508,
31,
203,
565,
1731,
3238,
17007,
31,
203,
565,
1731,
3238,
16702,
1854,
31,
203,
565,
2254,
3238,
2734,
31,
203,
203,
565,
3885,
12,
1731,
389,
529,
16,
1731,
389,
87,
12866,
16,
1731,
389,
17582,
1854,
16,
2254,
389,
8818,
13,
1071,
288,
203,
3639,
508,
273,
389,
529,
31,
203,
3639,
17007,
273,
389,
87,
12866,
31,
203,
3639,
16702,
1854,
273,
389,
17582,
1854,
31,
203,
3639,
2734,
273,
389,
8818,
31,
203,
565,
289,
203,
203,
565,
445,
1723,
1435,
1071,
225,
1476,
1135,
12,
3890,
13,
288,
203,
3639,
327,
508,
31,
203,
565,
289,
203,
203,
565,
445,
1322,
12866,
1435,
1071,
1476,
1135,
12,
3890,
13,
288,
203,
3639,
327,
17007,
31,
203,
565,
289,
203,
203,
565,
445,
1322,
9306,
1854,
1435,
1071,
1476,
1135,
12,
3890,
13,
288,
203,
3639,
327,
16702,
1854,
31,
203,
565,
289,
203,
203,
565,
445,
336,
6342,
1435,
1071,
1476,
1135,
12,
11890,
13,
288,
203,
3639,
327,
2734,
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
]
|
pragma solidity >=0.5.0;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
mapping (address=>bool) private authorizedCallers;
uint number_of_airlines = 0;
uint number_of_flights;
uint public MAX_AUTO_REGISTERED_AIRLINES = 4;
struct Airline {
address airlineAddress;
string name;
bool isRegistered;
bool isFunded;
address[] voters;
uint256 minVotes;
}
Airline[] private airlinesList;
mapping(address => Airline) internal airlines;
mapping(address => bytes32[]) private insuredFlights;
mapping(address => mapping(bytes32 => uint256)) private insuredBalance;
struct Flight {
string code;
string from;
string to;
bool isRegistered;
bool isInsured;
uint8 statusCode;
uint256 departureDate;
address airline;
address[] insuredPassengers;
}
Flight[] private flightsList;
mapping(bytes32 => Flight) internal flights;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
(
)
public
{
contractOwner = msg.sender;
// Authorizing yourself to call own functions, that can be called
// externally and hence require authorization
authorizedCallers[address(this)] = true;
authorizedCallers[contractOwner] = true;
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
modifier verifyCallerIsAuthorized()
{
require(authorizedCallers[msg.sender] == true, "The caller is not authorized to call this operation");
_;
}
modifier requireAirline() {
if (number_of_airlines >= 1) {
require(isAirline(tx.origin), "Only airlines are permitted to use this function");
}
_;
}
modifier notAirline() {
require(!isAirline(msg.sender), "Airlines cannot access this function.");
_;
}
modifier requireAirlineFunding() {
if (number_of_airlines >= 1) {
require(isAirlineFunded(tx.origin), "Airlines need to be funded to access this feature");
}
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns(bool)
{
return operational;
}
function isAirline(address userAddress) public view returns(bool) {
return airlines[userAddress].isRegistered;
}
function isAirlineFunded(address userAddress) public view returns(bool) {
return airlines[userAddress].isFunded;
}
function getAirlineByIndex(uint airlineNum) external view returns(address, string memory, bool, bool, address[] memory) {
Airline memory airline = airlinesList[airlineNum];
return (airline.airlineAddress, airline.name, airline.isRegistered, airline.isFunded, airline.voters);
}
function getFlightByIndex(uint flightNum) external view returns(string memory, string memory, string memory,
bool, bool, uint8, uint256, address, address[] memory) {
Flight memory flight = flightsList[flightNum];
return (flight.code, flight.from, flight.to, flight.isRegistered, flight.isInsured, flight.statusCode, flight.departureDate, flight.airline, flight.insuredPassengers);
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
requireContractOwner
{
operational = mode;
}
function authorizeCaller(address contractAddress) external requireContractOwner requireIsOperational {
authorizedCallers[contractAddress] = true;
}
/**
* @dev
*
* Make a check to see if the flight is already insured
*/
function isInsured(address _airlineAddress, address _passengerAddress, string memory _flightCode,
uint departureDate) public view returns(bool) {
bool insured = false;
bytes32 flightHash = getFlightKey(_airlineAddress, _flightCode, departureDate);
for (uint counter = 0; counter < insuredFlights[_passengerAddress].length; counter++) {
if (insuredFlights[_passengerAddress][counter] == flightHash) {
insured = true;
break;
}
}
return insured;
}
// get the current insurance fund balance
function getContractBalance() external requireIsOperational view returns(uint) {
return address(this).balance;
}
function getInsuredKeysLength(address _passengerAddress) external view returns(uint256) {
return insuredFlights[_passengerAddress].length;
}
function getInsuredFlights(address _passengerAddress, uint _index) external view returns(bytes32) {
return insuredFlights[_passengerAddress][_index];
}
/**
* @dev
*
* Calculates insurance payout
*/
// function getInsurancePayoutValue(bytes32 flightKey) public view requireIsOperational returns(uint256){
// InsuranceInfo memory insurance = insurances[flightKey];
// uint256 insurancePayoutValue = insurance.value.div(2);
// return insurancePayoutValue.add(insurance.value);
// }
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
function AirlineCount() external view returns(uint) {
return airlinesList.length;
}
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline(address airlineAddress, string calldata airlineName)
external requireAirline requireIsOperational requireAirlineFunding
{
require(!airlines[airlineAddress].isRegistered, "Airline must not be already registered");
airlines[airlineAddress] = Airline({
airlineAddress: airlineAddress,
name: airlineName,
isRegistered: number_of_airlines < MAX_AUTO_REGISTERED_AIRLINES,
isFunded: false,
voters: new address[](0),
minVotes: number_of_airlines.add(1).div(2)
});
number_of_airlines = number_of_airlines.add(1);
airlinesList.push(airlines[airlineAddress]);
}
function AddVote(address _airlineAddress) public requireAirline requireAirlineFunding requireIsOperational verifyCallerIsAuthorized{
// check if the airline has already voted
require(!alreadyVoted(tx.origin, _airlineAddress), "This airline has already voted");
// check if the airline that is being voted on is not registered yet
require(!airlines[_airlineAddress].isRegistered, "This airline has not registered yet to be able to vote");
Airline storage airlineToUpdate = airlines[_airlineAddress];
airlineToUpdate.voters.push(tx.origin);
}
function numVotesCasted(address _airlineAddress) external view returns(uint) {
return airlines[_airlineAddress].voters.length;
}
function updateAirlineRegistration(address _airlineAddress) public requireAirline
requireAirlineFunding requireIsOperational verifyCallerIsAuthorized{
airlines[_airlineAddress].isRegistered = true;
}
function alreadyVoted(address _voter, address _airlineAddress) public view returns(bool) {
bool voted = false;
for (uint counter=0; counter<airlines[_airlineAddress].voters.length; counter++) {
if (airlines[_airlineAddress].voters[counter] == _voter) {
voted = true;
break;
}
}
return voted;
}
/**
* @dev Buy insurance for a flight
*
*/
function buy
(address _airlineAddress, uint departureDate, string calldata flightCode)
external
requireIsOperational
notAirline
payable
{
require(!isInsured(_airlineAddress, msg.sender, flightCode, departureDate),
"User has already bought insurance for this flight");
require(msg.value <= 1 ether && msg.value > 0 ether, "Invalid Insurance Amount");
bytes32 flightHash = getFlightKey(_airlineAddress, flightCode, departureDate);
insuredFlights[tx.origin].push(flightHash);
// store the paid premium
insuredBalance[tx.origin][flightHash] = msg.value;
// register the insured passenger
Flight storage flightToUpdate = flights[flightHash];
flightToUpdate.insuredPassengers.push(tx.origin);
}
function getInsuranceBalance(address _passengerAddress, bytes32 _flightHash) external view returns(uint) {
return insuredBalance[_passengerAddress][_flightHash];
}
function setInsuranceBalance(address _passengerAddress, bytes32 _flightHash, uint newVal) external {
insuredBalance[_passengerAddress][_flightHash] = newVal;
}
function updateFlightStatus(bytes32 _flightHash, uint8 newStatus) external requireIsOperational {
Flight storage flightToUpdate = flights[_flightHash];
flightToUpdate.statusCode = newStatus;
}
function updateInsuredBalance(bytes32 _flightHash) external requireIsOperational {
Flight storage flightToUpdate = flights[_flightHash];
for (uint c = 0; c < flightToUpdate.insuredPassengers.length; c++) {
address insured = flightToUpdate.insuredPassengers[c];
// update the insured balance
insuredBalance[insured][_flightHash] = insuredBalance[insured][_flightHash].mul(15);
insuredBalance[insured][_flightHash] = insuredBalance[insured][_flightHash].div(10);
}
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees
(bytes32 _flightHash, uint amount
)
external
requireIsOperational
requireAirlineFunding
{
require(insuredBalance[msg.sender][_flightHash] >= amount, "Not enough funds");
insuredBalance[msg.sender][_flightHash] = insuredBalance[msg.sender][_flightHash].sub(amount);
msg.sender.transfer(amount);
}
function fundAirline(address _airlineAddress) external payable requireAirline {
require(msg.value == 10 ether, "The initial airline fee is equal to 10 ether");
airlines[_airlineAddress].isFunded = true;
}
function registerFlight(string calldata _flightCode,
string calldata _origin, string calldata _destination, uint256 _departureDate)
external requireAirline requireIsOperational requireAirlineFunding {
bytes32 flightHash = getFlightKey(tx.origin, _flightCode, _departureDate);
require(!flights[flightHash].isRegistered, "The flight has already been registered");
flights[flightHash] = Flight({
code: _flightCode,
from: _origin,
to: _destination,
isRegistered: true,
isInsured: false,
statusCode: 0,
departureDate: _departureDate,
airline: tx.origin,
insuredPassengers: new address[](0)
});
flightsList.push(flights[flightHash]);
number_of_flights = number_of_flights.add(1);
}
function getFlightCount() external view returns(uint) {
return flightsList.length;
}
function getFlight(bytes32 _flightHash) external view returns(string memory,
string memory, string memory, bool, bool, uint8, uint256, address) {
Flight memory flight = flights[_flightHash];
return (flight.code, flight.from, flight.to,
flight.isRegistered, flight.isInsured, flight.statusCode, flight.departureDate, flight.airline);
}
function getFlightCode(bytes32 _flightHash) external view returns(uint8 ) {
Flight memory flight = flights[_flightHash];
return flight.statusCode;
}
function insureFlight(string calldata _flightCode, uint256 _departureDate) external requireAirline requireAirlineFunding
requireIsOperational {
bytes32 flightHash = getFlightKey(tx.origin, _flightCode, _departureDate);
require(flights[flightHash].airline == tx.origin);
Flight storage flightToUpdate = flights[flightHash];
flightToUpdate.isInsured = true;
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay(bytes32 _flightHash, uint amount) external payable requireIsOperational {
require(insuredBalance[tx.origin][_flightHash] >= amount, "Insufficient funds");
insuredBalance[tx.origin][_flightHash] = insuredBalance[tx.origin][_flightHash].sub(amount);
tx.origin.transfer(amount);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function getAirline(address _airlineAddress) external view returns(address, string memory, bool, bool, address[] memory) {
Airline memory airline = airlines[_airlineAddress];
return (airline.airlineAddress, airline.name, airline.isRegistered, airline.isFunded, airline.voters);
}
function fund(address _airlineAddress) external payable requireAirline {
require(msg.value == 10 ether, "The initial airline fee is equal to 10 ether");
airlines[_airlineAddress].isFunded = true;
}
// function fund
// (
// )
// public
// payable
// {
// }
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
// function()
// external
// payable
// {
// fund();
// }
}
| get the current insurance fund balance | function getContractBalance() external requireIsOperational view returns(uint) {
return address(this).balance;
}
| 5,499,437 | [
1,
588,
326,
783,
2763,
295,
1359,
284,
1074,
11013,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
336,
8924,
13937,
1435,
3903,
2583,
2520,
2988,
287,
1476,
1135,
12,
11890,
13,
288,
203,
3639,
327,
1758,
12,
2211,
2934,
12296,
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
]
|
/**
* Copyright (c) 2017-present, Parsec Labs (parseclabs.org)
*
* This source code is licensed under the Mozilla Public License, version 2,
* found in the LICENSE file in the root directory of this source tree.
*/
pragma solidity ^0.4.19;
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/math/Math.sol";
import "./PriorityQueue.sol";
import "./TxLib.sol";
contract ParsecBridge {
using SafeMath for uint256;
using TxLib for TxLib.Output;
using TxLib for TxLib.Tx;
using PriorityQueue for PriorityQueue.Token;
event Epoch(uint256 epoch);
event NewHeight(uint256 blockNumber, bytes32 indexed root);
event NewDeposit(uint32 indexed depositId, address indexed depositor, uint256 indexed color, uint256 amount);
event ExitStarted(bytes32 indexed txHash, uint256 indexed outIndex, uint256 indexed color, address exitor, uint256 amount);
event ValidatorJoin(address indexed signerAddr, uint256 indexed slotId, bytes32 indexed tenderAddr, uint256 eventCounter, uint256 epoch);
event ValidatorLogout(address indexed signerAddr, uint256 indexed slotId, bytes32 indexed tenderAddr, uint256 eventCounter, uint256 epoch);
event ValidatorLeave(address indexed signerAddr, uint256 indexed slotId, bytes32 indexed tenderAddr, uint256 epoch);
event ValidatorUpdate(address indexed signerAddr, uint256 indexed slotId, bytes32 indexed tenderAddr, uint256 eventCounter);
bytes32 constant genesis = 0x4920616d207665727920616e6772792c20627574206974207761732066756e21; // "I am very angry, but it was fun!" @victor
uint256 public epochLength; // length of epoch in periods (32 blocks)
uint256 public lastCompleteEpoch; // height at which last epoch was completed
uint256 lastEpochBlockHeight;
uint256 parentBlockInterval; // how often epochs can be submitted max
uint64 lastParentBlock; // last ethereum block when epoch was submitted
uint256 maxReward; // max reward per period
uint256 public averageGasPrice; // collected gas price for last submitted blocks
uint256 exitDuration;
bytes32 public tipHash; // hash of first period that has extended chain to some height
mapping(uint16 => PriorityQueue.Token) public tokens;
mapping(address => bool) tokenColors;
uint16 public tokenCount = 0;
struct Slot {
uint32 eventCounter;
address owner;
uint64 stake;
address signer;
bytes32 tendermint;
uint32 activationEpoch;
address newOwner;
uint64 newStake;
address newSigner;
bytes32 newTendermint;
}
mapping(uint256 => Slot) public slots;
struct Period {
bytes32 parent; // the id of the parent node
uint32 height; // the height of last block in period
uint32 parentIndex; // the position of this node in the Parent's children list
uint8 slot;
uint32 timestamp;
uint64 reward;
bytes32[] children; // unordered list of children below this node
}
mapping(bytes32 => Period) public periods;
struct Deposit {
uint64 height;
uint16 color;
address owner;
uint256 amount;
}
mapping(uint32 => Deposit) public deposits;
uint32 depositCount = 0;
struct Exit {
uint64 amount;
uint16 color;
address owner;
}
mapping(bytes32 => Exit) public exits;
uint256 constant inflightBond = 1; //todo define
uint256 constant exitFirstPeriodDuration = 0; //todo define
uint256 constant exitSecondPeriodDuration = 0; //todo define
struct InflightExit {
bytes32 txHash;
TxLib.Input[] inputs;
address txBond;
address[] outputBonds;
uint32 startedAt;
uint32 height;
uint256 priority;
}
mapping(bytes32 => InflightExit) inflightExits;
constructor(uint256 _epochLength, uint256 _maxReward, uint256 _parentBlockInterval, uint256 _exitDuration) public {
// init genesis period
Period memory genesisPeriod;
genesisPeriod.parent = genesis;
genesisPeriod.height = 32;
genesisPeriod.timestamp = uint32(block.timestamp);
tipHash = genesis;
periods[tipHash] = genesisPeriod;
// epochLength and at the same time number of validator slots
require(_epochLength < 256);
require(_epochLength >= 2);
epochLength = _epochLength;
// full period reward before taxes and adjustments
maxReward = _maxReward;
// parent block settings
parentBlockInterval = _parentBlockInterval;
lastParentBlock = uint64(block.number);
exitDuration = _exitDuration;
}
function registerToken(ERC20 _token) public {
require(_token != address(0));
require(!tokenColors[_token]);
uint256[] memory arr = new uint256[](1);
tokenColors[_token] = true;
tokens[tokenCount++] = PriorityQueue.Token({
addr: _token,
heapList: arr,
currentSize: 0
});
}
function getSlot(uint256 _slotId) constant public returns (uint32, address, uint64, address, bytes32, uint32, address, uint64, address, bytes32) {
require(_slotId < epochLength);
Slot memory slot = slots[_slotId];
return (slot.eventCounter, slot.owner, slot.stake, slot.signer, slot.tendermint, slot.activationEpoch, slot.newOwner, slot. newStake, slot.newSigner, slot.newTendermint);
}
// data = [winnerHash, claimCountTotal, operator, operator ...]
// operator: 1b claimCountByOperator - 10b 0x - 1b stake - 20b address
function dfs(bytes32[] _data, bytes32 _nodeHash) internal constant returns(bytes32[] data) {
Period memory node = periods[_nodeHash];
// visit this node
data = new bytes32[](_data.length);
for (uint256 i = 1; i < _data.length; i++) {
data[i] = _data[i];
}
// find the operator that mined this block
i = node.slot + 2;
// if operator can claim rewards, assign
if (uint256(data[i]) == 0) {
data[i] = bytes32(1);
data[1] = bytes32(uint256(data[1]) + (1 << 128));
data[0] = _nodeHash;
}
// more of tree to walk
if (node.children.length > 0) {
bytes32[][] memory options = new bytes32[][](data.length);
for (i = 0; i < node.children.length; i++) {
options[i] = dfs(data, node.children[i]);
}
for (i = 0; i < node.children.length; i++) {
// compare options, return the best
if (uint256(options[i][1]) > uint256(data[1])) {
data[0] = options[i][0];
data[1] = options[i][1];
}
}
}
else {
data[0] = _nodeHash;
data[1] = bytes32(uint256(data[1]) + 1);
}
// else - reached a tip
// return data
}
function getTip() public constant returns (bytes32, uint256) {
// find consensus horizon
bytes32 consensusHorizon = periods[tipHash].parent;
uint256 depth = (periods[tipHash].height < epochLength * 32) ? 1 : periods[tipHash].height - (epochLength * 32);
depth += 32;
while(periods[consensusHorizon].height > depth) {
consensusHorizon = periods[consensusHorizon].parent;
}
// create data structure for depth first search
bytes32[] memory data = new bytes32[](epochLength + 2);
// run search
bytes32[] memory rsp = dfs(data, consensusHorizon);
// return result
return (rsp[0], uint256(rsp[1]) >> 128);
}
function bet(uint256 _slotId, uint256 _value, address _signerAddr, bytes32 _tenderAddr, address _owner) public {
require(_slotId < epochLength);
Slot storage slot = slots[_slotId];
// take care of logout
if (_value == 0 && slot.newStake == 0 && slot.signer == _signerAddr) {
slot.activationEpoch = uint32(lastCompleteEpoch.add(3));
slot.eventCounter++;
emit ValidatorLogout(slot.signer, _slotId, _tenderAddr, slot.eventCounter, lastCompleteEpoch + 3);
return;
}
// check min stake
uint required = slot.stake;
if (slot.newStake > required) {
required = slot.newStake;
}
required = required.mul(105).div(100);
require(required < _value);
// new purchase or update
if (slot.stake == 0 || (slot.owner == _owner && slot.newStake == 0)) {
uint64 stake = slot.stake;
tokens[0].addr.transferFrom(_owner, this, _value - slot.stake);
slot.owner = _owner;
slot.signer = _signerAddr;
slot.tendermint = _tenderAddr;
slot.stake = uint64(_value);
slot.activationEpoch = 0;
slot.eventCounter++;
if (stake == 0) {
emit ValidatorJoin(slot.signer, _slotId, _tenderAddr, slot.eventCounter, lastCompleteEpoch + 1);
} else {
emit ValidatorUpdate(slot.signer, _slotId, _tenderAddr, slot.eventCounter);
}
}
// auction
else {
if (slot.newStake > 0) {
tokens[0].addr.transfer(slot.newOwner, slot.newStake);
}
tokens[0].addr.transferFrom(_owner, this, _value);
slot.newOwner = _owner;
slot.newSigner = _signerAddr;
slot.newTendermint = _tenderAddr;
slot.newStake = uint64(_value);
slot.activationEpoch = uint32(lastCompleteEpoch.add(3));
slot.eventCounter++;
emit ValidatorLogout(slot.signer, _slotId, _tenderAddr, slot.eventCounter, lastCompleteEpoch + 3);
}
}
function activate(uint256 _slotId) public {
require(_slotId < epochLength);
Slot storage slot = slots[_slotId];
require(lastCompleteEpoch + 1 >= slot.activationEpoch);
if (slot.stake > 0) {
tokens[0].addr.transfer(slot.owner, slot.stake);
emit ValidatorLeave(slot.signer, _slotId, slot.tendermint, lastCompleteEpoch + 1);
}
slot.owner = slot.newOwner;
slot.signer = slot.newSigner;
slot.tendermint = slot.newTendermint;
slot.stake = slot.newStake;
slot.activationEpoch = 0;
slot.newOwner = 0;
slot.newSigner = 0;
slot.newTendermint = 0x0;
slot.newStake = 0;
slot.eventCounter++;
emit ValidatorJoin(slot.signer, _slotId, slot.tendermint, slot.eventCounter, lastCompleteEpoch + 1);
}
function recordGas() internal {
averageGasPrice = averageGasPrice - (averageGasPrice / 15) + (tx.gasprice / 15);
}
function submitPeriod(uint256 _slotId, bytes32 _prevHash, bytes32 _root) public {
// check parent node exists
require(periods[_prevHash].parent > 0);
// check that same root not submitted yet
require(periods[_root].height == 0);
// check slot
require(_slotId < epochLength);
Slot storage slot = slots[_slotId];
require(slot.signer == msg.sender);
if (slot.activationEpoch > 0) {
// if slot not active, prevent submission
require(lastCompleteEpoch.add(2) < slot.activationEpoch);
}
// calculate height
uint256 newHeight = periods[_prevHash].height + 32;
// do some magic if chain extended
if (newHeight > periods[tipHash].height) {
// new periods can only be submitted every x Ethereum blocks
require(block.number >= lastParentBlock + parentBlockInterval);
tipHash = _root;
lastParentBlock = uint64(block.number);
// record gas
recordGas();
emit NewHeight(newHeight, _root);
}
// store the period
Period memory newPeriod;
newPeriod.parent = _prevHash;
newPeriod.height = uint32(newHeight);
newPeriod.slot = uint8(_slotId);
newPeriod.timestamp = uint32(block.timestamp);
newPeriod.parentIndex = uint32(periods[_prevHash].children.push(_root) - 1);
periods[_root] = newPeriod;
// distribute rewards
uint256 totalSupply = tokens[0].addr.totalSupply();
uint256 stakedSupply = tokens[0].addr.balanceOf(this);
uint256 reward = maxReward;
if (stakedSupply >= totalSupply.div(2)) {
// 4 x br x as x (ts - as)
// -----------------------
// ts x ts
reward = totalSupply.sub(stakedSupply).mul(stakedSupply).mul(maxReward).mul(4).div(totalSupply.mul(totalSupply));
}
slot.stake += uint64(reward);
// check if epoch completed
if (newHeight >= lastEpochBlockHeight.add(epochLength.mul(32))) {
lastCompleteEpoch++;
lastEpochBlockHeight = newHeight;
}
}
function deletePeriod(bytes32 hash) internal {
Period storage parent = periods[periods[hash].parent];
uint256 i = periods[hash].parentIndex;
if (i < parent.children.length - 1) {
// swap with last child
parent.children[i] = parent.children[parent.children.length - 1];
}
parent.children.length--;
if (hash == tipHash) {
tipHash = periods[hash].parent;
}
delete periods[hash];
}
function readInvalidDepositProof(
bytes32[] _txData
) public pure returns (
uint32 depositId,
uint64 value,
address signer
) {
depositId = uint32(_txData[2] >> 240);
value = uint64(_txData[2] >> 176);
signer = address(_txData[2]);
}
/*
* _txData = [ 32b periodHash, (1b Proofoffset, 8b pos, ..00.., 1b txData), 32b txData, 32b proof, 32b proof ]
*
* # 2 Deposit TX (33b)
* 1b type
* 4b depositId
* 8b value, 2b color, 20b address
*
*/
function reportInvalidDeposit(bytes32[] _txData) public {
Period memory p = periods[_txData[0]];
if (periods[tipHash].height > epochLength) {
require(p.height > periods[tipHash].height - epochLength);
}
// check transaction proof
TxLib.validateProof(0, _txData);
// check deposit values
uint32 depositId;
uint64 value;
address signer;
(depositId, value, signer) = readInvalidDepositProof(_txData);
Deposit memory dep = deposits[depositId];
require(value != dep.amount || signer != dep.owner);
// delete invalid period
deletePeriod(_txData[0]);
// EVENT
// slash operator
slash(p.slot, 10 * maxReward);
// reward 1 block reward
tokens[0].addr.transfer(msg.sender, maxReward);
}
function reportDoubleSpend(bytes32[] _proof, bytes32[] _prevProof) public {
Period memory p = periods[_proof[0]];
// validate proofs
uint256 offset = 32 * (_proof.length + 2);
uint64 txPos1;
(txPos1, , ) = TxLib.validateProof(offset, _prevProof);
uint64 txPos2;
(txPos2, , ) = TxLib.validateProof(32, _proof);
// make sure transactions are different
require(_proof[0] != _prevProof[0] || txPos1 != txPos2);
// get iputs and validate
bytes32 prevHash1;
bytes32 prevHash2;
uint8 outPos1;
uint8 outPos2;
assembly {
//TODO: allow other than first inputId
prevHash1 := calldataload(add(134, 32))
outPos1 := calldataload(add(166, 32))
prevHash2 := calldataload(add(134, offset))
outPos2 := calldataload(add(166, offset))
}
// check that spending same outputs
require(prevHash1 == prevHash2 && outPos1 == outPos2);
// delete invalid period
deletePeriod(_proof[0]);
// EVENT
// slash operator
slash(p.slot, 50);
}
function slash(uint256 _slotId, uint256 _value) public {
require(_slotId < epochLength);
Slot storage slot = slots[_slotId];
require(slot.stake > 0);
uint256 prevStake = slot.stake;
slot.stake = (_value >= slot.stake) ? 0 : slot.stake - uint64(_value);
// if slot became empty by slashing
if (prevStake > 0 && slot.stake == 0) {
emit ValidatorLeave(slot.signer, _slotId, slot.tendermint, lastCompleteEpoch + 1);
slot.activationEpoch = 0;
if (slot.newStake > 0) {
// someone in queue
activate(_slotId);
} else {
// clean out account
slot.owner = 0;
slot.signer = 0;
slot.tendermint = 0x0;
slot.stake = 0;
}
}
}
/*
* Add funds
*/
function deposit(address _owner, uint256 _amount, uint16 _color) public {
require(_color < tokenCount);
tokens[_color].addr.transferFrom(_owner, this, _amount);
depositCount++;
deposits[depositCount] = Deposit({
height: periods[tipHash].height,
owner: _owner,
color: _color,
amount: _amount
});
emit NewDeposit(depositCount, _owner, _color, _amount);
}
function startExit(bytes32[] _proof, uint256 _oindex) public {
// validate proof
bytes32 txHash;
bytes memory txData;
(, txHash, txData) = TxLib.validateProof(32, _proof);
// parse tx and use data
TxLib.Output memory out = TxLib.parseTx(txData).outs[_oindex];
uint256 exitable_at = Math.max256(periods[_proof[0]].timestamp + (2 * exitDuration), block.timestamp + exitDuration);
bytes32 utxoId = bytes32((_oindex << 120) | uint120(txHash));
uint256 priority = (exitable_at << 128) | uint128(utxoId);
require(out.value > 0);
require(exits[utxoId].amount == 0);
tokens[out.color].insert(priority);
exits[utxoId] = Exit({
owner: out.owner,
color: out.color,
amount: out.value
});
emit ExitStarted(txHash, _oindex, out.color, out.owner, out.value);
}
function challengeExit(bytes32[] _proof, bytes32[] _prevProof, uint256 _oIndex, uint256 _inputIndex) public {
// validate exiting tx
uint256 offset = 32 * (_proof.length + 2);
bytes32 txHash1;
( , txHash1, ) = TxLib.validateProof(offset + 64, _prevProof);
bytes32 utxoId = bytes32((_oIndex << 120) | uint120(txHash1));
require(exits[utxoId].amount > 0);
// validate spending tx
bytes memory txData;
(, , txData) = TxLib.validateProof(96, _proof);
TxLib.Input memory input = TxLib.parseTx(txData).ins[_inputIndex];
// make sure one is spending the other one
require(txHash1 == input.hash);
require(_oIndex == input.outPos);
// delete invalid exit
delete exits[utxoId].owner;
delete exits[utxoId].amount;
}
// @dev Loops through the priority queue of exits, settling the ones whose challenge
// @dev challenge period has ended
function finalizeExits(uint16 _color) public {
bytes32 utxoId;
uint256 exitable_at;
(utxoId, exitable_at) = getNextExit(_color);
Exit memory currentExit = exits[utxoId];
while (exitable_at <= block.timestamp && tokens[currentExit.color].currentSize > 0) {
currentExit = exits[utxoId];
if (currentExit.owner != 0 || currentExit.amount != 0) { // exit was removed
tokens[currentExit.color].addr.transfer(currentExit.owner, currentExit.amount);
}
tokens[currentExit.color].delMin();
delete exits[utxoId].owner;
delete exits[utxoId].amount;
if (tokens[currentExit.color].currentSize > 0) {
(utxoId, exitable_at) = getNextExit(_color);
} else {
return;
}
}
}
function getNextExit(uint16 _color) internal view returns (bytes32 utxoId, uint256 exitable_at) {
uint256 priority = tokens[_color].getMin();
utxoId = bytes32(uint128(priority));
exitable_at = priority >> 128;
}
function startInflightExit(bytes32[] _tx, bytes32[] _i1Proof, bytes32[] _i2Proof, uint16 _oindex) public {
// Honest owners of outputs to t “piggyback” on this exit and post a bond
// Users who do not piggyback will not be able to exit.
// In case of doublespending user couldn't post a bond due to possible challenge
//check that txHash has not been used in inflight exit
bytes32 txHash;
bytes memory txData;
// ( ,txHash, txData) = TxLib.validateProof(txData); //todo parse txData for inflight exit in parsec-lib
require(inflightExits[txHash].txHash == bytes32(0));
TxLib.Tx memory tx = TxLib.parseTx(txData);
_validateInputs(tx.ins, _i1Proof, _i2Proof);
// todo validate tx sig
//place bond for output
ERC20(tokens[0].addr).transferFrom(msg.sender, address(this), inflightBond); //currently set psc tokens
//create exit with bond
InflightExit storage exit = inflightExits[txHash];
exit.txHash = txHash;
exit.txBond = msg.sender;
exit.outputBonds = new address[](2);
exit.startedAt = uint32(block.timestamp);
exit.priority = _determineTxPriority(_i1Proof, _i2Proof);
exit.height = uint32(-1);
for (uint256 i = 0; i < tx.ins.length; i++) {
exit.inputs[i] = tx.ins[i];
}
}
function bondToOutput(bytes32 txHash, uint16 _oindex) public {
require((inflightExits[txHash].startedAt + exitFirstPeriodDuration) > block.timestamp);
InflightExit storage exit = inflightExits[txHash];
require(exit.outputBonds[_oindex] == address(0));
exit.outputBonds[_oindex] = msg.sender;
ERC20(tokens[0].addr).transferFrom(msg.sender, address(this), inflightBond);
}
function competitorToTx(bytes32[] _proof, bytes32[] _i1Proof, bytes32[] _i2Proof, uint16 _oindex, bytes32 target) public {
bytes32 txHash;
bytes memory txData;
(,txHash, txData) = TxLib.validateProof(32, _proof); //todo check offset
require(inflightExits[txHash].txHash != bytes32(0));
require((inflightExits[txHash].startedAt + exitFirstPeriodDuration) > block.timestamp);
TxLib.Tx memory tx = TxLib.parseTx(txData);
_validateInputs(tx.ins, _i1Proof, _i2Proof);
uint256 priority = _determineTxPriority(_i1Proof, _i2Proof);
require(inflightExits[txHash].height < inflightExits[target].height);
InflightExit storage exit = inflightExits[txHash];
exit.txHash = txHash;
exit.txBond = msg.sender;
exit.outputBonds = new address[](2);
exit.startedAt = uint32(block.timestamp);
exit.priority = _determineTxPriority(_i1Proof, _i2Proof);
exit.height = uint32(-1);
TxLib.Input[] memory inputs = new TxLib.Input[](tx.ins.length);
for (uint256 i = 0; i < inputs.length; i++) {
exit.inputs[i] = tx.ins[i];
}
_releaseOutputBonds(target);
delete inflightExits[target];
}
function _releaseOutputBonds(bytes32 _exitHash) {
address[] storage bonds = inflightExits[_exitHash].outputBonds;
for (uint256 j = 0; j < bonds.length; j++) {
if (bonds[j] != address(0)) {
ERC20(tokens[0].addr).transfer(bonds[j], inflightBond);
}
}
}
function _validateInputs(TxLib.Input[] _inputs, bytes32[] _i1Proof, bytes32[] _i2Proof) private {
bytes memory txData1;
uint256 offset1; //todo check offset
(, , txData1) = TxLib.validateProof(offset1, _i1Proof);
require(_inputs[0].hash == keccak256(txData1));
bytes memory txData2;
uint256 offset2; //todo check offset
(, , txData2) = TxLib.validateProof(offset2, _i2Proof);
require(_inputs[1].hash == keccak256(txData2));
}
function _determineTxPriority(bytes32[] _i1Proof, bytes32[] _i2Proof) private returns(uint256) {
uint256 youngest_i_exitable_at
= Math.max64(uint64(periods[_i1Proof[0]].timestamp), uint64(periods[_i2Proof[0]].timestamp));
uint256 tx_exitable_at = Math.max256(youngest_i_exitable_at + (2 * exitDuration), block.timestamp + exitDuration);
return tx_exitable_at;
}
// check that time of first period elapsed
//check that there are competitors to exited tx
// We define canonicity with respect to a single transaction - the set of competing transactions to t
// is the set of all transactions such that the transaction shares an input with t. The canonical transaction
// within that set is the transaction that’s included first.
// If competitors were presented, period 2 serves to determine whether t is canonical. Any user may present:
// t, included in the chain before all competitors presented in period 1.
// Spends of any “piggybacked” inputs or outputs (except t itself).
// That some input was not created by a canonical transaction.
// This means revealing both the transaction that created the input, as well as some competitor to that transaction
// such that the competitor came first.
function challengeCompetitorWithInclusion(bytes32 _exit, bytes32 _proof) public {
// check that the second period lasts
}
function challengeCompetitorWithSpending(bytes32 _exit, bytes32 _proof) public {
// check that the second period lasts
}
function challengeOutput(bytes32 _exit, uint256 _oindex, bytes32[] _proofTxData, uint256 _proofOindex) public {
// check that the second period lasts
// check that it is not the same tx as in exit
}
function finalizeInflightExit(bytes32 _exit) {
//check that second exit period elapsed
// bytes32 utxoId = bytes32((_oindex << 120) | uint120(txHash));
// create standard exits for piggybacked outputs
}
//todo add output pointed to input(itself) in parsec-lib
}
| find the operator that mined this block | i = node.slot + 2;
| 944,651 | [
1,
4720,
326,
3726,
716,
1131,
329,
333,
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,
277,
273,
756,
18,
14194,
397,
576,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// IFxMessageProcessor represents interface to process message
interface IFxMessageProcessor {
function processMessageFromRoot(uint256 stateId, address rootMessageSender, bytes calldata data) external;
}
/**
* @notice Mock child tunnel contract to receive and send message from L2
*/
abstract contract FxBaseChildTunnel is IFxMessageProcessor{
// MessageTunnel on L1 will get data from this event
event MessageSent(bytes message);
// fx child
address public fxChild;
// fx root tunnel
address public fxRootTunnel;
constructor(address _fxChild) {
fxChild = _fxChild;
}
// Sender must be fxRootTunnel in case of ERC20 tunnel
modifier validateSender(address sender) {
require(sender == fxRootTunnel, "FxBaseChildTunnel: INVALID_SENDER_FROM_ROOT");
_;
}
// set fxRootTunnel if not set already
function setFxRootTunnel(address _fxRootTunnel) external {
require(fxRootTunnel == address(0x0), "FxBaseChildTunnel: ROOT_TUNNEL_ALREADY_SET");
fxRootTunnel = _fxRootTunnel;
}
function processMessageFromRoot(uint256 stateId, address rootMessageSender, bytes calldata data) external override {
require(msg.sender == fxChild, "FxBaseChildTunnel: INVALID_SENDER");
_processMessageFromRoot(stateId, rootMessageSender, data);
}
/**
* @notice Emit message that can be received on Root Tunnel
* @dev Call the internal function when need to emit message
* @param message bytes message that will be sent to Root Tunnel
* some message examples -
* abi.encode(tokenId);
* abi.encode(tokenId, tokenMetadata);
* abi.encode(messageType, messageData);
*/
function _sendMessageToRoot(bytes memory message) internal {
emit MessageSent(message);
}
/**
* @notice Process message received from Root Tunnel
* @dev function needs to be implemented to handle message as per requirement
* This is called by onStateReceive function.
* Since it is called via a system call, any event will not be emitted during its execution.
* @param stateId unique state id
* @param sender root message sender
* @param message bytes message that was sent from Root Tunnel
*/
function _processMessageFromRoot(uint256 stateId, address sender, bytes memory message) virtual internal;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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
pragma solidity ^0.8.0;
import "./Utilities.sol";
contract Adminable is Utilities {
mapping(address => bool) private admins;
function addAdmin(address _address) external onlyOwner {
require(_address.code.length > 0, "must be a contract");
admins[_address] = true;
}
function addAdmins(address[] calldata _addresses) external onlyOwner {
uint256 len = _addresses.length;
for(uint256 i = 0; i < len; i++) {
require(_addresses[i].code.length > 0, "must be a contract");
admins[_addresses[i]] = true;
}
}
function removeAdmin(address _address) external onlyOwner {
admins[_address] = false;
}
function removeAdmins(address[] calldata _addresses) external onlyOwner {
uint256 len = _addresses.length;
for(uint256 i = 0; i < len; i++) {
admins[_addresses[i]] = false;
}
}
function setPause(bool _shouldPause) external onlyAdminOrOwner {
if(_shouldPause) {
_pause();
} else {
_unpause();
}
}
function isAdmin(address _address) public view returns(bool) {
return admins[_address];
}
modifier onlyAdmin() {
require(admins[msg.sender], "Not admin");
_;
}
modifier onlyAdminOrOwner() {
require(admins[msg.sender] || isOwner(), "Not admin or owner");
_;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
contract Utilities is Ownable, Pausable {
modifier nonZeroAddress(address _address) {
require(address(0) != _address, "0 address");
_;
}
modifier nonZeroLength(uint[] memory _array) {
require(_array.length > 0, "Empty array");
_;
}
modifier lengthsAreEqual(uint[] memory _array1, uint[] memory _array2) {
require(_array1.length == _array2.length, "Unequal lengths");
_;
}
modifier onlyEOA() {
/* solhint-disable avoid-tx-origin */
require(msg.sender == tx.origin, "No contracts");
_;
}
function isOwner() internal view returns(bool) {
return owner() == msg.sender;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@maticnetwork/fx-portal/contracts/tunnel/FxBaseChildTunnel.sol";
import "../../shared/Adminable.sol";
import "./IMessageHandler.sol";
import "./IChildTunnel.sol";
contract ChildTunnel is IChildTunnel, FxBaseChildTunnel, Adminable {
IMessageHandler public messageHandler;
constructor(
address _fxChild
) FxBaseChildTunnel(_fxChild) {
_pause();
}
function setMessageHandler(address _messageHandlerAddress) external onlyAdminOrOwner {
require(_messageHandlerAddress != address(0), "invalid message handler");
messageHandler = IMessageHandler(_messageHandlerAddress);
}
function sendMessageToRoot(bytes calldata _message) external override onlyAdminOrOwner {
require(address(messageHandler) != address(0), "Message handler not set");
_sendMessageToRoot(_message);
}
// Purposefully exclude the first argument as it is not needed.
function _processMessageFromRoot(
uint256,
address sender,
bytes memory data
) internal override validateSender(sender) {
messageHandler.handleMessage(data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IChildTunnel {
// Sends the bytes to the root (L1).
// Admin only.
function sendMessageToRoot(bytes calldata _data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IMessageHandler {
// Handles the given message from the other bridge
// Admin only.
function handleMessage(bytes calldata _data) external;
} | * @dev Initializes the contract setting the deployer as the initial owner./ | function _processMessageFromRoot(uint256 stateId, address sender, bytes memory message) virtual internal;
}
pragma solidity ^0.8.0;
import "../utils/Context.sol";
constructor() {
_transferOwnership(_msgSender());
}
| 168,886 | [
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,
2567,
1079,
1265,
2375,
12,
11890,
5034,
919,
548,
16,
1758,
5793,
16,
1731,
3778,
883,
13,
5024,
2713,
31,
203,
97,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x14e39aDc79A7610c685143c4cd891F94dB3B40cD/sources/@aragon/osx/framework/utils/ens/ENSSubdomainRegistrar.sol | @title ENSSubdomainRegistrar @author Aragon Association - 2022-2023 @notice This contract registers ENS subdomains under a parent domain specified in the initialization process and maintains ownership of the subdomain since only the resolver address is set. This contract must either be the domain node owner or an approved operator of the node owner. The default resolver being used is the one specified in the parent domain. | contract ENSSubdomainRegistrar is UUPSUpgradeable, DaoAuthorizableUpgradeable {
bytes32 public constant UPGRADE_REGISTRAR_PERMISSION_ID =
keccak256("UPGRADE_REGISTRAR_PERMISSION");
bytes32 public constant REGISTER_ENS_SUBDOMAIN_PERMISSION_ID =
keccak256("REGISTER_ENS_SUBDOMAIN_PERMISSION");
ENS public ens;
bytes32 public node;
address public resolver;
error AlreadyRegistered(bytes32 subnode, address nodeOwner);
error InvalidResolver(bytes32 node, address resolver);
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {DaoAuthorizableUpgradeable} from "../../../core/plugin/dao-authorizable/DaoAuthorizableUpgradeable.sol";
import {IDAO} from "../../../core/dao/IDAO.sol";
constructor() {
_disableInitializers();
}
function initialize(IDAO _managingDao, ENS _ens, bytes32 _node) external initializer {
__DaoAuthorizableUpgradeable_init(_managingDao);
ens = _ens;
node = _node;
address nodeResolver = ens.resolver(_node);
if (nodeResolver == address(0)) {
}
resolver = nodeResolver;
}
function initialize(IDAO _managingDao, ENS _ens, bytes32 _node) external initializer {
__DaoAuthorizableUpgradeable_init(_managingDao);
ens = _ens;
node = _node;
address nodeResolver = ens.resolver(_node);
if (nodeResolver == address(0)) {
}
resolver = nodeResolver;
}
revert InvalidResolver({node: _node, resolver: nodeResolver});
) internal virtual override auth(UPGRADE_REGISTRAR_PERMISSION_ID) {}
function _authorizeUpgrade(
address
function registerSubnode(
bytes32 _label,
address _targetAddress
) external auth(REGISTER_ENS_SUBDOMAIN_PERMISSION_ID) {
bytes32 subnode = keccak256(abi.encodePacked(node, _label));
address currentOwner = ens.owner(subnode);
if (currentOwner != address(0)) {
revert AlreadyRegistered(subnode, currentOwner);
}
ens.setSubnodeOwner(node, _label, address(this));
ens.setResolver(subnode, resolver);
Resolver(resolver).setAddr(subnode, _targetAddress);
}
function _authorizeUpgrade(
address
function registerSubnode(
bytes32 _label,
address _targetAddress
) external auth(REGISTER_ENS_SUBDOMAIN_PERMISSION_ID) {
bytes32 subnode = keccak256(abi.encodePacked(node, _label));
address currentOwner = ens.owner(subnode);
if (currentOwner != address(0)) {
revert AlreadyRegistered(subnode, currentOwner);
}
ens.setSubnodeOwner(node, _label, address(this));
ens.setResolver(subnode, resolver);
Resolver(resolver).setAddr(subnode, _targetAddress);
}
function setDefaultResolver(
address _resolver
) external auth(REGISTER_ENS_SUBDOMAIN_PERMISSION_ID) {
if (_resolver == address(0)) {
}
resolver = _resolver;
}
function setDefaultResolver(
address _resolver
) external auth(REGISTER_ENS_SUBDOMAIN_PERMISSION_ID) {
if (_resolver == address(0)) {
}
resolver = _resolver;
}
revert InvalidResolver({node: node, resolver: _resolver});
uint256[47] private __gap;
}
| 5,569,499 | [
1,
1157,
1260,
373,
4308,
30855,
225,
1201,
346,
265,
18400,
300,
26599,
22,
17,
18212,
23,
225,
1220,
6835,
10285,
512,
3156,
720,
14180,
3613,
279,
982,
2461,
1269,
316,
326,
10313,
1207,
471,
11566,
4167,
23178,
434,
326,
16242,
3241,
1338,
326,
5039,
1758,
353,
444,
18,
1220,
6835,
1297,
3344,
506,
326,
2461,
756,
3410,
578,
392,
20412,
3726,
434,
326,
756,
3410,
18,
1021,
805,
5039,
3832,
1399,
353,
326,
1245,
1269,
316,
326,
982,
2461,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
6693,
1260,
373,
4308,
30855,
353,
587,
3079,
55,
10784,
429,
16,
463,
6033,
3594,
6934,
10784,
429,
288,
203,
565,
1731,
1578,
1071,
5381,
7376,
24554,
1639,
67,
5937,
18643,
985,
67,
23330,
67,
734,
273,
203,
3639,
417,
24410,
581,
5034,
2932,
3079,
24554,
1639,
67,
5937,
18643,
985,
67,
23330,
8863,
203,
203,
565,
1731,
1578,
1071,
5381,
11980,
19957,
67,
21951,
67,
8362,
18192,
67,
23330,
67,
734,
273,
203,
3639,
417,
24410,
581,
5034,
2932,
27511,
67,
21951,
67,
8362,
18192,
67,
23330,
8863,
203,
203,
565,
512,
3156,
1071,
19670,
31,
203,
203,
565,
1731,
1578,
1071,
756,
31,
203,
203,
565,
1758,
1071,
5039,
31,
203,
203,
565,
555,
17009,
10868,
12,
3890,
1578,
28300,
16,
1758,
756,
5541,
1769,
203,
203,
565,
555,
1962,
4301,
12,
3890,
1578,
756,
16,
1758,
5039,
1769,
203,
203,
203,
5666,
288,
57,
3079,
55,
10784,
429,
97,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
17,
15097,
429,
19,
5656,
19,
5471,
19,
57,
3079,
55,
10784,
429,
18,
18281,
14432,
203,
5666,
288,
11412,
3594,
6934,
10784,
429,
97,
628,
315,
16644,
6216,
3644,
19,
4094,
19,
2414,
83,
17,
4161,
6934,
19,
11412,
3594,
6934,
10784,
429,
18,
18281,
14432,
203,
5666,
288,
734,
20463,
97,
628,
315,
16644,
6216,
3644,
19,
2414,
83,
19,
734,
20463,
18,
18281,
14432,
203,
565,
3885,
1435,
288,
203,
3639,
389,
8394,
4435,
8426,
5621,
203,
565,
289,
203,
203,
565,
445,
4046,
12,
734,
20463,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.4;
/**
@author Tellor Inc.
@title TellorVariables
@dev Helper contract to store hashes of variables
*/
contract TellorVariables {
bytes32 constant _BLOCK_NUMBER =
0x4b4cefd5ced7569ef0d091282b4bca9c52a034c56471a6061afd1bf307a2de7c; //keccak256("_BLOCK_NUMBER");
bytes32 constant _CURRENT_CHALLENGE =
0xd54702836c9d21d0727ffacc3e39f57c92b5ae0f50177e593bfb5ec66e3de280; //keccak256("_CURRENT_CHALLENGE");
bytes32 constant _CURRENT_REQUESTID =
0xf5126bb0ac211fbeeac2c0e89d4c02ac8cadb2da1cfb27b53c6c1f4587b48020; //keccak256("_CURRENT_REQUESTID");
bytes32 constant _CURRENT_REWARD =
0xd415862fd27fb74541e0f6f725b0c0d5b5fa1f22367d9b78ec6f61d97d05d5f8; //keccak256("_CURRENT_REWARD");
bytes32 constant _CURRENT_TOTAL_TIPS =
0x09659d32f99e50ac728058418d38174fe83a137c455ff1847e6fb8e15f78f77a; //keccak256("_CURRENT_TOTAL_TIPS");
bytes32 constant _DEITY =
0x5fc094d10c65bc33cc842217b2eccca0191ff24148319da094e540a559898961; //keccak256("_DEITY");
bytes32 constant _DIFFICULTY =
0xf758978fc1647996a3d9992f611883adc442931dc49488312360acc90601759b; //keccak256("_DIFFICULTY");
bytes32 constant _DISPUTE_COUNT =
0x310199159a20c50879ffb440b45802138b5b162ec9426720e9dd3ee8bbcdb9d7; //keccak256("_DISPUTE_COUNT");
bytes32 constant _DISPUTE_FEE =
0x675d2171f68d6f5545d54fb9b1fb61a0e6897e6188ca1cd664e7c9530d91ecfc; //keccak256("_DISPUTE_FEE");
bytes32 constant _DISPUTE_ROUNDS =
0x6ab2b18aafe78fd59c6a4092015bddd9fcacb8170f72b299074f74d76a91a923; //keccak256("_DISPUTE_ROUNDS");
bytes32 constant _EXTENSION =
0x2b2a1c876f73e67ebc4f1b08d10d54d62d62216382e0f4fd16c29155818207a4; //keccak256("_EXTENSION");
bytes32 constant _FEE =
0x1da95f11543c9b03927178e07951795dfc95c7501a9d1cf00e13414ca33bc409; //keccak256("_FEE");
bytes32 constant _FORK_EXECUTED =
0xda571dfc0b95cdc4a3835f5982cfdf36f73258bee7cb8eb797b4af8b17329875; //keccak256("_FORK_EXECUTED");
bytes32 constant _LOCK =
0xd051321aa26ce60d202f153d0c0e67687e975532ab88ce92d84f18e39895d907;
bytes32 constant _MIGRATOR =
0xc6b005d45c4c789dfe9e2895b51df4336782c5ff6bd59a5c5c9513955aa06307; //keccak256("_MIGRATOR");
bytes32 constant _MIN_EXECUTION_DATE =
0x46f7d53798d31923f6952572c6a19ad2d1a8238d26649c2f3493a6d69e425d28; //keccak256("_MIN_EXECUTION_DATE");
bytes32 constant _MINER_SLOT =
0x6de96ee4d33a0617f40a846309c8759048857f51b9d59a12d3c3786d4778883d; //keccak256("_MINER_SLOT");
bytes32 constant _NUM_OF_VOTES =
0x1da378694063870452ce03b189f48e04c1aa026348e74e6c86e10738514ad2c4; //keccak256("_NUM_OF_VOTES");
bytes32 constant _OLD_TELLOR =
0x56e0987db9eaec01ed9e0af003a0fd5c062371f9d23722eb4a3ebc74f16ea371; //keccak256("_OLD_TELLOR");
bytes32 constant _ORIGINAL_ID =
0xed92b4c1e0a9e559a31171d487ecbec963526662038ecfa3a71160bd62fb8733; //keccak256("_ORIGINAL_ID");
bytes32 constant _OWNER =
0x7a39905194de50bde334d18b76bbb36dddd11641d4d50b470cb837cf3bae5def; //keccak256("_OWNER");
bytes32 constant _PAID =
0x29169706298d2b6df50a532e958b56426de1465348b93650fca42d456eaec5fc; //keccak256("_PAID");
bytes32 constant _PENDING_OWNER =
0x7ec081f029b8ac7e2321f6ae8c6a6a517fda8fcbf63cabd63dfffaeaafa56cc0; //keccak256("_PENDING_OWNER");
bytes32 constant _REQUEST_COUNT =
0x3f8b5616fa9e7f2ce4a868fde15c58b92e77bc1acd6769bf1567629a3dc4c865; //keccak256("_REQUEST_COUNT");
bytes32 constant _REQUEST_ID =
0x9f47a2659c3d32b749ae717d975e7962959890862423c4318cf86e4ec220291f; //keccak256("_REQUEST_ID");
bytes32 constant _REQUEST_Q_POSITION =
0xf68d680ab3160f1aa5d9c3a1383c49e3e60bf3c0c031245cbb036f5ce99afaa1; //keccak256("_REQUEST_Q_POSITION");
bytes32 constant _SLOT_PROGRESS =
0xdfbec46864bc123768f0d134913175d9577a55bb71b9b2595fda21e21f36b082; //keccak256("_SLOT_PROGRESS");
bytes32 constant _STAKE_AMOUNT =
0x5d9fadfc729fd027e395e5157ef1b53ef9fa4a8f053043c5f159307543e7cc97; //keccak256("_STAKE_AMOUNT");
bytes32 constant _STAKE_COUNT =
0x10c168823622203e4057b65015ff4d95b4c650b308918e8c92dc32ab5a0a034b; //keccak256("_STAKE_COUNT");
bytes32 constant _T_BLOCK =
0xf3b93531fa65b3a18680d9ea49df06d96fbd883c4889dc7db866f8b131602dfb; //keccak256("_T_BLOCK");
bytes32 constant _TALLY_DATE =
0xf9e1ae10923bfc79f52e309baf8c7699edb821f91ef5b5bd07be29545917b3a6; //keccak256("_TALLY_DATE");
bytes32 constant _TARGET_MINERS =
0x0b8561044b4253c8df1d9ad9f9ce2e0f78e4bd42b2ed8dd2e909e85f750f3bc1; //keccak256("_TARGET_MINERS");
bytes32 constant _TELLOR_CONTRACT =
0x0f1293c916694ac6af4daa2f866f0448d0c2ce8847074a7896d397c961914a08; //keccak256("_TELLOR_CONTRACT");
bytes32 constant _TELLOR_GETTERS =
0xabd9bea65759494fe86471c8386762f989e1f2e778949e94efa4a9d1c4b3545a; //keccak256("_TELLOR_GETTERS");
bytes32 constant _TIME_OF_LAST_NEW_VALUE =
0x2c8b528fbaf48aaf13162a5a0519a7ad5a612da8ff8783465c17e076660a59f1; //keccak256("_TIME_OF_LAST_NEW_VALUE");
bytes32 constant _TIME_TARGET =
0xd4f87b8d0f3d3b7e665df74631f6100b2695daa0e30e40eeac02172e15a999e1; //keccak256("_TIME_TARGET");
bytes32 constant _TIMESTAMP =
0x2f9328a9c75282bec25bb04befad06926366736e0030c985108445fa728335e5; //keccak256("_TIMESTAMP");
bytes32 constant _TOTAL_SUPPLY =
0xe6148e7230ca038d456350e69a91b66968b222bfac9ebfbea6ff0a1fb7380160; //keccak256("_TOTAL_SUPPLY");
bytes32 constant _TOTAL_TIP =
0x1590276b7f31dd8e2a06f9a92867333eeb3eddbc91e73b9833e3e55d8e34f77d; //keccak256("_TOTAL_TIP");
bytes32 constant _VALUE =
0x9147231ab14efb72c38117f68521ddef8de64f092c18c69dbfb602ffc4de7f47; //keccak256("_VALUE");
bytes32 constant _EIP_SLOT =
0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
}
| keccak256("_CURRENT_REWARD");
| 0xd415862fd27fb74541e0f6f725b0c0d5b5fa1f22367d9b78ec6f61d97d05d5f8; | 1,029,484 | [
1,
79,
24410,
581,
5034,
2932,
67,
15487,
67,
862,
21343,
8863,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3639,
374,
7669,
24,
3600,
5292,
22,
8313,
5324,
19192,
5608,
6564,
21,
73,
20,
74,
26,
74,
27,
2947,
70,
20,
71,
20,
72,
25,
70,
25,
507,
21,
74,
3787,
5718,
27,
72,
29,
70,
8285,
557,
26,
74,
9498,
72,
10580,
72,
6260,
72,
25,
74,
28,
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
]
|
pragma solidity ^0.5.5;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @title 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];
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract SupporterRole is Context {
using Roles for Roles.Role;
event SupporterAdded(address indexed account);
event SupporterRemoved(address indexed account);
Roles.Role private _supporters;
constructor () internal {
_addSupporter(_msgSender());
}
modifier onlySupporter() {
require(isSupporter(_msgSender()), "SupporterRole: caller does not have the Supporter role");
_;
}
function isSupporter(address account) public view returns (bool) {
return _supporters.has(account);
}
function addSupporter(address account) public onlySupporter {
_addSupporter(account);
}
function renounceSupporter() public {
_removeSupporter(_msgSender());
}
function _addSupporter(address account) internal {
_supporters.add(account);
emit SupporterAdded(account);
}
function _removeSupporter(address account) internal {
_supporters.remove(account);
emit SupporterRemoved(account);
}
}
contract PauserRole is Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(_msgSender());
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(_msgSender());
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context, PauserRole {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() internal view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() internal view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev A Secondary contract can only be used by its primary account (the one that created it).
*/
contract Secondary is Context {
address private _primary;
/**
* @dev Emitted when the primary contract changes.
*/
event PrimaryTransferred(
address recipient
);
/**
* @dev Sets the primary account to the one that is creating the Secondary contract.
*/
constructor () internal {
address msgSender = _msgSender();
_primary = msgSender;
emit PrimaryTransferred(msgSender);
}
/**
* @dev Reverts if called from any account other than the primary.
*/
modifier onlyPrimary() {
require(_msgSender() == _primary, "Secondary: caller is not the primary account");
_;
}
/**
* @return the address of the primary.
*/
function primary() public view returns (address) {
return _primary;
}
/**
* @dev Transfers contract to a new primary.
* @param recipient The address of new primary.
*/
function transferPrimary(address recipient) public onlyPrimary {
require(recipient != address(0), "Secondary: new primary is the zero address");
_primary = recipient;
emit PrimaryTransferred(recipient);
}
}
/**
* @title __unstable__TokenVault
* @dev Similar to an Escrow for tokens, this contract allows its primary account to spend its tokens as it sees fit.
* This contract is an internal helper for PostDeliveryCrowdsale, and should not be used outside of this context.
*/
// solhint-disable-next-line contract-name-camelcase
contract __unstable__TokenVault is Secondary {
function transferToken(IERC20 token, address to, uint256 amount) public onlyPrimary {
token.transfer(to, amount);
}
function transferFunds(address payable to, uint256 amount) public onlyPrimary {
require (address(this).balance >= amount);
to.transfer(amount);
}
function () external payable {}
}
/**
* @title MoonStaking
*/
contract MoonStaking is Ownable, Pausable, SupporterRole, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
struct Pool {
uint256 rate;
uint256 adapter;
uint256 totalStaked;
}
struct User {
mapping(address => UserSp) tokenPools;
UserSp ePool;
}
struct UserSp {
uint256 staked;
uint256 lastRewardTime;
uint256 earned;
}
mapping(address => User) users;
mapping(address => Pool) pools;
// The MOON TOKEN!
IERC20 public moon;
uint256 eRate;
uint256 eAdapter;
uint256 eTotalStaked;
__unstable__TokenVault private _vault;
/**
* @param _moon The MOON token.
*/
constructor(IERC20 _moon) public {
_vault = new __unstable__TokenVault();
moon = _moon;
}
/**
* @dev Update token pool rate
* @return True when successful
*/
function updatePoolRate(address pool, uint256 _rate, uint256 _adapter)
public onlyOwner returns (bool) {
pools[pool].rate = _rate;
pools[pool].adapter = _adapter;
return true;
}
/**
* @dev Update epool pool rate
* @return True when successful
*/
function updateEpoolRate(uint256 _rate, uint256 _adapter)
public onlyOwner returns (bool) {
eRate = _rate;
eAdapter = _adapter;
return true;
}
/**
* @dev Checks whether the pool is available.
* @return Whether the pool is available.
*/
function isPoolAvailable(address pool) public view returns (bool) {
return pools[pool].rate != 0;
}
/**
* @dev View pool token info
* @param _pool Token address.
* @return Pool info
*/
function poolTokenInfo(address _pool) public view returns (
uint256 rate,
uint256 adapter,
uint256 totalStaked
) {
Pool storage pool = pools[_pool];
return (pool.rate, pool.adapter, pool.totalStaked);
}
/**
* @dev View pool E info
* @return Pool info
*/
function poolInfo(address poolAddress) public view returns (
uint256 rate,
uint256 adapter,
uint256 totalStaked
) {
Pool storage sPool = pools[poolAddress];
return (sPool.rate, sPool.adapter, sPool.totalStaked);
}
/**
* @dev View pool E info
* @return Pool info
*/
function poolEInfo() public view returns (
uint256 rate,
uint256 adapter,
uint256 totalStaked
) {
return (eRate, eAdapter, eTotalStaked);
}
/**
* @dev Get earned reward in e pool.
*/
function getEarnedEpool() public view returns (uint256) {
UserSp storage pool = users[_msgSender()].ePool;
return _getEarned(eRate, eAdapter, pool);
}
/**
* @dev Get earned reward in t pool.
*/
function getEarnedTpool(address stakingPoolAddress) public view returns (uint256) {
UserSp storage stakingPool = users[_msgSender()].tokenPools[stakingPoolAddress];
Pool storage pool = pools[stakingPoolAddress];
return _getEarned(pool.rate, pool.adapter, stakingPool);
}
/**
* @dev Stake with E
* @return true if successful
*/
function stakeE() public payable returns (bool) {
uint256 _value = msg.value;
require(_value != 0, "Zero amount");
address(uint160((address(_vault)))).transfer(_value);
UserSp storage ePool = users[_msgSender()].ePool;
ePool.earned = ePool.earned.add(_getEarned(eRate, eAdapter, ePool));
ePool.lastRewardTime = block.timestamp;
ePool.staked = ePool.staked.add(_value);
eTotalStaked = eTotalStaked.add(_value);
return true;
}
/**
* @dev Stake with tokens
* @param _value Token amount.
* @param token Token address.
* @return true if successful
*/
function stake(uint256 _value, IERC20 token) public returns (bool) {
require(token.balanceOf(_msgSender()) >= _value, "Insufficient Funds");
require(token.allowance(_msgSender(), address(this)) >= _value, "Insufficient Funds Approved");
address tokenAddress = address(token);
require(isPoolAvailable(tokenAddress), "Pool is not available");
_forwardFundsToken(token, _value);
Pool storage pool = pools[tokenAddress];
UserSp storage tokenPool = users[_msgSender()].tokenPools[tokenAddress];
tokenPool.earned = tokenPool.earned.add(_getEarned(pool.rate, pool.adapter, tokenPool));
tokenPool.lastRewardTime = block.timestamp;
tokenPool.staked = tokenPool.staked.add(_value);
pool.totalStaked = pool.totalStaked.add(_value);
return true;
}
/**
* @dev Withdraw all available tokens.
*/
function withdrawTokenPool(address token) public whenNotPaused nonReentrant returns (bool) {
UserSp storage tokenStakingPool = users[_msgSender()].tokenPools[token];
require(tokenStakingPool.staked > 0 != tokenStakingPool.earned > 0, "Not available");
if (tokenStakingPool.earned > 0) {
Pool storage pool = pools[token];
_vault.transferToken(moon, _msgSender(), _getEarned(pool.rate, pool.adapter, tokenStakingPool));
tokenStakingPool.lastRewardTime = block.timestamp;
tokenStakingPool.earned = 0;
}
if (tokenStakingPool.staked > 0) {
_vault.transferToken(IERC20(token), _msgSender(), tokenStakingPool.staked);
tokenStakingPool.staked = 0;
}
return true;
}
/**
* @dev Withdraw all available tokens.
*/
function withdrawEPool() public whenNotPaused nonReentrant returns (bool) {
UserSp storage eStakingPool = users[_msgSender()].ePool;
require(eStakingPool.staked > 0 != eStakingPool.earned > 0, "Not available");
if (eStakingPool.earned > 0) {
_vault.transferToken(moon, _msgSender(), _getEarned(eRate, eAdapter, eStakingPool));
eStakingPool.lastRewardTime = block.timestamp;
eStakingPool.earned = 0;
}
if (eStakingPool.staked > 0) {
_vault.transferFunds(_msgSender(), eStakingPool.staked);
eStakingPool.staked = 0;
}
return true;
}
/**
* @dev Claim earned Moon.
*/
function claimMoonInTpool(address token) public whenNotPaused returns (bool) {
UserSp storage tokenStakingPool = users[_msgSender()].tokenPools[token];
require(tokenStakingPool.staked > 0 != tokenStakingPool.earned > 0, "Not available");
Pool storage pool = pools[token];
_vault.transferToken(moon, _msgSender(), _getEarned(pool.rate, pool.adapter, tokenStakingPool));
tokenStakingPool.lastRewardTime = block.timestamp;
tokenStakingPool.earned = 0;
return true;
}
/**
* @dev Claim earned Moon.
*/
function claimMoonInEpool() public whenNotPaused returns (bool) {
UserSp storage eStakingPool = users[_msgSender()].ePool;
require(eStakingPool.staked > 0 != eStakingPool.earned > 0, "Not available");
_vault.transferToken(moon, _msgSender(), _getEarned(eRate, eAdapter, eStakingPool));
eStakingPool.lastRewardTime = block.timestamp;
eStakingPool.earned = 0;
return true;
}
/**
* @dev Get reserved token.
*/
function getReserved() public view onlyOwner
returns (uint256 vaultTokens, uint256 vaultFunds) {
address vaultAddress = address(_vault);
vaultTokens = moon.balanceOf(vaultAddress);
vaultFunds = address(uint160(vaultAddress)).balance;
}
/**
* @dev Get reserved token by address.
*/
function getReservedByAddress(IERC20 token) public view onlyOwner returns (uint256) {
return token.balanceOf(address(_vault));
}
/**
* @dev Supply token for the vaults.
* @param amount Supply amount
*/
function supplyVault(uint256 amount)
public onlyOwner
returns (bool) {
moon.transferFrom(_msgSender(), address(_vault), amount);
return true;
}
/**
* @dev deprive tokens from vaults.
* @param vault Vault address
* @param amount The amount
*/
function depriveToken(address vault, IERC20 token, uint256 amount)
public onlyOwner returns (bool) {
_vault.transferToken(token, vault, amount);
return true;
}
/**
* @dev deprive funds from vaults.
* @param vault Vault address
* @param amount The amount
*/
function depriveFunds(address payable vault, uint256 amount)
public onlyOwner
returns (bool) {
_vault.transferFunds(vault, amount);
return true;
}
/**
* @dev Fallback function
*/
function () external payable {
address(uint160((address(_vault)))).transfer(msg.value);
}
/**
* @dev Extend parent behavior
* @param erc20Token ERC20 Token
* @param _value Amount contributed
*/
function _forwardFundsToken(IERC20 erc20Token, uint256 _value) internal {
erc20Token.transferFrom(_msgSender(), address(_vault), _value);
}
/**
* @dev Get earned reward.
*/
function _getEarned(uint256 rate, uint256 adapter, UserSp memory stakingPool) internal view returns (uint256) {
uint256 moonPerSec = stakingPool.staked.mul(rate).div(adapter);
return block.timestamp.sub(stakingPool.lastRewardTime).mul(moonPerSec).add(stakingPool.earned);
}
} | * @dev deprive tokens from vaults. @param vault Vault address @param amount The amount/ | function depriveToken(address vault, IERC20 token, uint256 amount)
public onlyOwner returns (bool) {
_vault.transferToken(token, vault, amount);
return true;
}
| 6,159,431 | [
1,
323,
683,
688,
2430,
628,
9229,
87,
18,
225,
9229,
17329,
1758,
225,
3844,
1021,
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,
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,
443,
683,
688,
1345,
12,
2867,
9229,
16,
467,
654,
39,
3462,
1147,
16,
2254,
5034,
3844,
13,
203,
3639,
1071,
1338,
5541,
1135,
261,
6430,
13,
288,
203,
3639,
389,
26983,
18,
13866,
1345,
12,
2316,
16,
9229,
16,
3844,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
contract Leaderboard
{
enum ResetPeriod
{
Eternal,
Yearly,
Monthly,
Weekly,
Daily
}
uint8 constant MAX_NICKNAME_LENGTH = 16;
struct LeaderboardData
{
string name;
ResetPeriod resetPeriod;
bool canScoresDecrease;
uint256 maxSize;
bytes32[] players;
uint256[] scores;
string[] nicknames;
uint256 firstTimestamp;
}
LeaderboardData[] leaderboards;
uint256 nextLeaderboardId;
mapping(uint256 => address) leaderboardOwners;
mapping(bytes32 => string) playerNicknames;
// A value of 0 means the player does not have a score on that leaderboard
mapping(uint256 => mapping(bytes32 => uint256)) playerIndexOneBased;
mapping(bytes32 => uint256[]) participatingLeaderboardsPerPlayer;
/**
* @dev Creates a brand-new leaderboard. The address that calls this is set as the owner of the new leaderboard.
*
* @return uint256 Returns the ID of a new leaderboard. Use this number in future calls.
*/
function createLeaderboard() public returns(uint256)
{
uint256 id = nextLeaderboardId;
nextLeaderboardId++;
LeaderboardData memory newBoard;
newBoard.maxSize = 100000;
leaderboards.push(newBoard);
leaderboardOwners[id] = msg.sender;
return id;
}
/**
* @dev Returns a table of players and scores, in the form of two arrays of equal size, sorted in descending order, from best to worst score.
*
* @param leaderboardId number of the leaderboard to be returned.
*
* @return string[] Nicknames of the players. Anonymous mini-hashes are used instead, for players who have not registered their nicknames.
* @return unit256[] The high-scores for each of the players.
*/
function getLeaderboard(uint256 leaderboardId) public view returns(string[] memory, uint256[] memory)
{
LeaderboardData memory board = leaderboards[leaderboardId];
return (board.nicknames, board.scores);
}
/**
* @dev Clears a specific leaderboard. Restricted to the caller of createLeaderboard().
*
* @param leaderboardId number of the leaderboard to be cleared.
*/
function clearLeaderboard(uint256 leaderboardId) public
{
_checkAuthority(leaderboardId);
_clearLeaderboard(leaderboardId);
}
/**
* @dev Returns a specific leaderboard's name, if any.
*
* @param leaderboardId number of the leaderboard to be inspected.
*
* @return string the leaderboard's display name.
*/
function getName(uint256 leaderboardId) public view returns(string memory)
{
LeaderboardData memory board = leaderboards[leaderboardId];
return board.name;
}
/**
* @dev Set a new name for a specific leaderboard.
*
* @param leaderboardId number of the leaderboard to be configured.
* @param _name the leaderboard's new display name.
*/
function setName(uint256 leaderboardId, string memory _name) public
{
_checkAuthority(leaderboardId);
LeaderboardData storage board = leaderboards[leaderboardId];
board.name = _name;
}
/**
* @dev Returns the frequency at which a specific leaderboard auto-clears. Default is 'Eternal'.
*
* @param leaderboardId number of the leaderboard to be inspected.
*
* @return ResetPeriod one of: Eternal (0), Yearly (1), Monthly (2), Weekly (3) or Daily (4).
*/
function getResetPeriod(uint256 leaderboardId) public view returns(ResetPeriod)
{
LeaderboardData memory board = leaderboards[leaderboardId];
return board.resetPeriod;
}
/**
* @dev Set the frequency at which a specific leaderboard auto-clears.
*
* @param leaderboardId number of the leaderboard to be configured.
* @param _resetPeriod one of: Eternal (0), Yearly (1), Monthly (2), Weekly (3) or Daily (4).
*/
function setResetPeriod(uint256 leaderboardId, ResetPeriod _resetPeriod) public
{
_checkAuthority(leaderboardId);
LeaderboardData storage board = leaderboards[leaderboardId];
board.resetPeriod = _resetPeriod;
}
/**
* @dev Returns a specific leaderboard's "canScoresDecrease" property.
* This defines the behavior of new scores passed in by submitScore().
*
* @param leaderboardId number of the leaderboard to be inspected.
*
* @return bool Returns `true` if lower scores for existing players are saved. `false` otherwise.
*/
function getCanScoresDecrease(uint256 leaderboardId) public view returns(bool)
{
LeaderboardData memory board = leaderboards[leaderboardId];
return board.canScoresDecrease;
}
/**
* @dev Changes a specific leaderboard's "canScoresDecrease" property.
* If set to `true`, then a new player's score always replaces their previous score.
* If set to `false`, then a new score is compared to that player's previous score and is only accepted if it's better.
*
* @param leaderboardId number of the leaderboard to be configured.
* @param _canScoresDecrease boolean value specifying the behavior of new scores that are lower than previous scores.
*/
function setCanScoresDecrease(uint256 leaderboardId, bool _canScoresDecrease) public
{
_checkAuthority(leaderboardId);
LeaderboardData storage board = leaderboards[leaderboardId];
board.canScoresDecrease = _canScoresDecrease;
}
/**
* @dev Returns the maximum number of entries for a given leaderboard. Default is 10,000.
*
* @param leaderboardId number of the leaderboard to be inspected.
*
* @return unit256 The maximum size of the leaderboard.
*/
function getMaxSize(uint256 leaderboardId) public view returns(uint256)
{
LeaderboardData memory board = leaderboards[leaderboardId];
return board.maxSize;
}
/**
* @dev Sets the maximum number of entries on a leaderboard. Restricted to the caller of createLeaderboard().
*
* @param leaderboardId number of the leaderboard to be configured.
* @param _maxSize the new size limit.
*/
function setMaxSize(uint256 leaderboardId, uint256 _maxSize) public
{
_checkAuthority(leaderboardId);
LeaderboardData storage board = leaderboards[leaderboardId];
board.maxSize = _maxSize;
while (board.scores.length > _maxSize)
{
_removeBottomEntry(leaderboardId);
}
}
/**
* @dev Returns the leaderboard data about the calling player: msg.sender is used as the player to lookup.
*
* @param leaderboardId number of the leaderboard to be inspected.
*
* @return string nickname of the calling player, or empty string if they are not present on this leaderboard.
* @return unit256 score of the calling player, or zero if they are not present on this leaderboard.
*/
function getEntry(uint256 leaderboardId) public view returns(string memory, uint256)
{
address player = msg.sender;
bytes32 playerId = _getPlayerId(player);
uint256 playerIndex = playerIndexOneBased[leaderboardId][playerId];
if (playerIndex > 0)
{
playerIndex--;
LeaderboardData memory board = leaderboards[leaderboardId];
if (playerIndex < board.scores.length)
{
return (board.nicknames[playerIndex], board.scores[playerIndex]);
}
}
return ("", 0);
}
/**
* @dev Given an arbitrary score value, estimates what position on the leaderboard it would appear, if submitted.
*
* @param leaderboardId number of the leaderboard to be inspected.
* @param newScore the hypothetical score to evaluate.
*
* @return unit256 zero-index position on the leaderboard where the score would appear, if submitted.
*/
function getPositionForScore(uint256 leaderboardId, uint256 newScore) public view returns(uint256)
{
LeaderboardData storage board = leaderboards[leaderboardId];
for (uint256 i = 0; i < board.scores.length; i++)
{
if (newScore >= board.scores[i])
{
return i;
}
}
return board.scores.length;
}
/**
* @dev Submits a new score for a player. Restricted to the caller of createLeaderboard().
*
* @param leaderboardId number of the leaderboard to be modified.
* @param player address of the player who earned the score.
* @param newScore numeric value of the score earned.
*/
function submitScore(uint256 leaderboardId, address player, uint256 newScore) public
{
_checkAuthority(leaderboardId);
LeaderboardData storage board = leaderboards[leaderboardId];
if (board.maxSize == 0)
{
return;
}
bytes32 playerId = _getPlayerId(player);
// Clear leaderboard if the period has reset
if (_checkResetPeriod(leaderboardId))
{
_clearLeaderboard(leaderboardId);
}
// The leaderboard is empty, receiving its first score
if (board.scores.length == 0)
{
board.firstTimestamp = block.timestamp;
playerIndexOneBased[leaderboardId][playerId] = 1;
board.players.push(playerId);
board.scores.push(newScore);
board.nicknames.push(_getNickname(playerId));
participatingLeaderboardsPerPlayer[playerId].push(leaderboardId);
return;
}
// Check if this player already has a score on this leaderboard
uint256 playerIndex = playerIndexOneBased[leaderboardId][playerId];
bool hasPreviousScore = false;
if (playerIndex > 0 && playerIndex < board.maxSize)
{
hasPreviousScore = true;
playerIndex--;
}
// Player that is already on this leaderboard
if (hasPreviousScore)
{
// Same score. No change
if (newScore == board.scores[playerIndex])
{
return;
}
// The new score is better than this player's old score. Search and insert
if (newScore > board.scores[playerIndex])
{
while (playerIndex > 0)
{
if (newScore < board.scores[playerIndex - 1])
{
break;
}
// Move other scores down by 1
playerIndexOneBased[leaderboardId][board.players[playerIndex - 1]]++;
board.players[playerIndex] = board.players[playerIndex - 1];
board.scores[playerIndex] = board.scores[playerIndex - 1];
board.nicknames[playerIndex] = board.nicknames[playerIndex - 1];
playerIndex--;
}
}
else // The new score is lower than the previous score
{
// However, the leaderboard may be configured to not allow saving worse scores
if ( !board.canScoresDecrease )
{
return;
}
// Search
while (playerIndex < board.scores.length - 1)
{
uint256 i = playerIndex + 1;
if (newScore >= board.scores[i])
{
break;
}
// Move other scores up by 1
playerIndexOneBased[leaderboardId][board.players[i]]--;
board.players[playerIndex] = board.players[i];
board.scores[playerIndex] = board.scores[i];
board.nicknames[playerIndex] = board.nicknames[i];
playerIndex++;
}
}
}
// New player, with worst score of all
else if (newScore < board.scores[board.scores.length - 1])
{
if (board.scores.length < board.maxSize)
{
board.players.push(playerId);
board.scores.push(newScore);
board.nicknames.push(_getNickname(playerId));
playerIndexOneBased[leaderboardId][playerId] = board.scores.length;
participatingLeaderboardsPerPlayer[playerId].push(leaderboardId);
}
return;
}
// New player, inserted in the middle somewhere
else
{
playerIndex = 0;
for ( ; playerIndex < board.scores.length; playerIndex++)
{
// Search for the index to insert at
if (newScore >= board.scores[playerIndex])
{
// Adjust the score at the bottom of the leaderboard
uint256 i = board.scores.length - 1;
if (board.scores.length < board.maxSize)
{
playerIndexOneBased[leaderboardId][board.players[i]]++;
board.players.push(board.players[i]);
board.scores.push(board.scores[i]);
board.nicknames.push(board.nicknames[i]);
}
else {
playerIndexOneBased[leaderboardId][board.players[i]] = 0;
}
// Move other scores down by 1
while (i > playerIndex)
{
playerIndexOneBased[leaderboardId][board.players[i - 1]]++;
board.players[i] = board.players[i - 1];
board.scores[i] = board.scores[i - 1];
board.nicknames[i] = board.nicknames[i - 1];
i--;
}
break;
}
}
participatingLeaderboardsPerPlayer[playerId].push(leaderboardId);
}
// Emplace
playerIndexOneBased[leaderboardId][playerId] = playerIndex + 1;
board.players[playerIndex] = playerId;
board.scores[playerIndex] = newScore;
board.nicknames[playerIndex] = _getNickname(playerId);
}
/**
* @dev Returns a list of leaderboard IDs in which the local player has any scores.
* Local only: The contract uses `msg.sender` to search.
*
* @return unit256[] an array with leaderboard IDs.
*/
function getLeaderboardsForPlayer() external view returns(uint256[] memory)
{
bytes32 playerId = _getPlayerId(msg.sender);
return participatingLeaderboardsPerPlayer[playerId];
}
/**
* @dev Returns the timestamp when the leaderboard will auto-clear, in seconds since unix epoch.
*
* @param leaderboardId number of the leaderboard to be inspected.
*
* @return unit256 the time at which reset will occur, in the form of seconds since unix epoch.
* Returns zero if the leaderboard's `resetPeriod` is set to `Eternal`.
*/
function getResetTimestamp(uint256 leaderboardId) public view returns(uint256)
{
LeaderboardData storage board = leaderboards[leaderboardId];
if (board.resetPeriod == ResetPeriod.Eternal)
{
return 0;
}
uint256 expireTime = board.firstTimestamp;
if (board.resetPeriod == ResetPeriod.Daily)
{
expireTime += 60 * 60 * 24; // 24 hours
}
else if (board.resetPeriod == ResetPeriod.Weekly)
{
expireTime += 60 * 60 * 24 * 7; // 7 days
}
else if (board.resetPeriod == ResetPeriod.Monthly)
{
expireTime += 60 * 60 * 24 * 30; // 30 days
}
else if (board.resetPeriod == ResetPeriod.Yearly)
{
expireTime += 60 * 60 * 24 * 365; // 1 year
}
return expireTime;
}
/**
* @dev Allows a player to register their nickname with all leaderboards created with the contract.
* Local only: The contract uses `msg.sender` to register the nickname.
* Player addresses are hashed before storage.
*
* @param _nickname the desired nickname, up to a 16 byte limit. Nicknames larger than the limit are cropped.
*/
function registerNickname(string memory _nickname) public
{
// Limit the size
bytes memory strBytes = bytes(_nickname);
if (strBytes.length > MAX_NICKNAME_LENGTH)
{
bytes memory result = new bytes(MAX_NICKNAME_LENGTH);
for(uint i = 0; i < MAX_NICKNAME_LENGTH; i++) {
result[i] = strBytes[i];
}
_nickname = string(result);
}
// Save nickname
bytes32 playerId = _getPlayerId(msg.sender);
_nickname = string(abi.encodePacked(_nickname, " ", _getPlayerIdAbbreviation(playerId)));
playerNicknames[playerId] = _nickname;
// Update existing entries for this player across all leaderboards
uint256[] memory leaderboardList = participatingLeaderboardsPerPlayer[playerId];
for (uint256 i = 0; i < leaderboardList.length; i++)
{
uint256 id = leaderboardList[i];
uint256 playerIndex = playerIndexOneBased[id][playerId];
if (playerIndex > 0)
{
playerIndex--;
LeaderboardData storage board = leaderboards[id];
board.nicknames[playerIndex] = _nickname;
}
}
}
/**
* @dev Returns the nickname for the caller.
* Local only: The contract uses `msg.sender` to lookup the nickname.
*
* @return string the nickname previously set by calls to registerNickname().
*/
function getNickname() public view returns(string memory)
{
bytes32 playerId = _getPlayerId(msg.sender);
return _getNickname(playerId);
}
function _getNickname(bytes32 playerId) internal view returns(string memory)
{
if (bytes(playerNicknames[playerId]).length > 0)
{
return playerNicknames[playerId];
}
return _getPlayerIdAbbreviation(playerId);
}
function _getPlayerIdAbbreviation(bytes32 playerId) internal pure returns(string memory)
{
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(5);
str[0] = "#";
uint n = 1;
uint i = 0;
while (n < str.length)
{
str[n] = alphabet[uint(uint8(playerId[i] >> 4))];
str[n+1] = alphabet[uint(uint8(playerId[i] & 0x0f))];
n += 2;
i++;
}
return string(str);
}
function _clearLeaderboard(uint256 leaderboardId) internal
{
LeaderboardData storage board = leaderboards[leaderboardId];
while (board.scores.length > 0)
{
_removeBottomEntry(leaderboardId);
}
}
function _removeBottomEntry(uint256 leaderboardId) internal
{
LeaderboardData storage board = leaderboards[leaderboardId];
bytes32 lastPlayerId = board.players[board.scores.length - 1];
playerIndexOneBased[leaderboardId][lastPlayerId] = 0;
board.players.pop();
board.scores.pop();
board.nicknames.pop();
uint256[] storage leaderboardList = participatingLeaderboardsPerPlayer[lastPlayerId];
bool found;
for (uint256 i = 0; i < leaderboardList.length; i++)
{
if ( !found && leaderboardList[i] == leaderboardId)
{
found = true;
}
if (found && (i + 1) < leaderboardList.length)
{
leaderboardList[i] = leaderboardList[i + 1];
}
}
if (found)
{
leaderboardList.pop();
}
}
function _checkAuthority(uint256 leaderboardId) internal view
{
require(leaderboardOwners[leaderboardId] == msg.sender, "No permission to change leaderboard.");
}
function _getPlayerId(address player) internal pure returns(bytes32)
{
return keccak256(abi.encodePacked(player));
}
function _checkResetPeriod(uint256 leaderboardId) internal view returns(bool)
{
LeaderboardData storage board = leaderboards[leaderboardId];
if (board.resetPeriod == ResetPeriod.Eternal)
{
return false;
}
return getResetTimestamp(leaderboardId) >= block.timestamp;
}
} | * @dev Submits a new score for a player. Restricted to the caller of createLeaderboard(). @param leaderboardId number of the leaderboard to be modified. @param player address of the player who earned the score. @param newScore numeric value of the score earned./ Same score. No change However, the leaderboard may be configured to not allow saving worse scores Search for the index to insert at Adjust the score at the bottom of the leaderboard | function submitScore(uint256 leaderboardId, address player, uint256 newScore) public
{
_checkAuthority(leaderboardId);
LeaderboardData storage board = leaderboards[leaderboardId];
if (board.maxSize == 0)
{
return;
}
bytes32 playerId = _getPlayerId(player);
{
_clearLeaderboard(leaderboardId);
}
{
board.firstTimestamp = block.timestamp;
playerIndexOneBased[leaderboardId][playerId] = 1;
board.players.push(playerId);
board.scores.push(newScore);
board.nicknames.push(_getNickname(playerId));
participatingLeaderboardsPerPlayer[playerId].push(leaderboardId);
return;
}
bool hasPreviousScore = false;
if (playerIndex > 0 && playerIndex < board.maxSize)
{
hasPreviousScore = true;
playerIndex--;
}
{
if (newScore == board.scores[playerIndex])
{
return;
}
{
while (playerIndex > 0)
{
if (newScore < board.scores[playerIndex - 1])
{
break;
}
board.players[playerIndex] = board.players[playerIndex - 1];
board.scores[playerIndex] = board.scores[playerIndex - 1];
board.nicknames[playerIndex] = board.nicknames[playerIndex - 1];
playerIndex--;
}
}
{
if ( !board.canScoresDecrease )
{
return;
}
{
uint256 i = playerIndex + 1;
if (newScore >= board.scores[i])
{
break;
}
board.players[playerIndex] = board.players[i];
board.scores[playerIndex] = board.scores[i];
board.nicknames[playerIndex] = board.nicknames[i];
playerIndex++;
}
}
}
{
if (board.scores.length < board.maxSize)
{
board.players.push(playerId);
board.scores.push(newScore);
board.nicknames.push(_getNickname(playerId));
playerIndexOneBased[leaderboardId][playerId] = board.scores.length;
participatingLeaderboardsPerPlayer[playerId].push(leaderboardId);
}
return;
}
{
playerIndex = 0;
for ( ; playerIndex < board.scores.length; playerIndex++)
{
if (newScore >= board.scores[playerIndex])
{
uint256 i = board.scores.length - 1;
if (board.scores.length < board.maxSize)
{
playerIndexOneBased[leaderboardId][board.players[i]]++;
board.players.push(board.players[i]);
board.scores.push(board.scores[i]);
board.nicknames.push(board.nicknames[i]);
}
else {
playerIndexOneBased[leaderboardId][board.players[i]] = 0;
}
{
playerIndexOneBased[leaderboardId][board.players[i - 1]]++;
board.players[i] = board.players[i - 1];
board.scores[i] = board.scores[i - 1];
board.nicknames[i] = board.nicknames[i - 1];
i--;
}
break;
}
}
participatingLeaderboardsPerPlayer[playerId].push(leaderboardId);
}
board.players[playerIndex] = playerId;
board.scores[playerIndex] = newScore;
board.nicknames[playerIndex] = _getNickname(playerId);
}
| 5,505,618 | [
1,
1676,
22679,
279,
394,
4462,
364,
279,
7291,
18,
29814,
358,
326,
4894,
434,
752,
15254,
3752,
7675,
225,
30052,
548,
1300,
434,
326,
30052,
358,
506,
4358,
18,
225,
7291,
1758,
434,
326,
7291,
10354,
425,
1303,
329,
326,
4462,
18,
225,
394,
7295,
6389,
460,
434,
326,
4462,
425,
1303,
329,
18,
19,
17795,
4462,
18,
2631,
2549,
10724,
16,
326,
30052,
2026,
506,
4351,
358,
486,
1699,
12392,
14591,
307,
8474,
5167,
364,
326,
770,
358,
2243,
622,
17720,
326,
4462,
622,
326,
5469,
434,
326,
30052,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4879,
7295,
12,
11890,
5034,
30052,
548,
16,
1758,
7291,
16,
2254,
5034,
394,
7295,
13,
1071,
203,
565,
288,
203,
3639,
389,
1893,
10962,
12,
27863,
3752,
548,
1769,
203,
203,
3639,
26048,
3752,
751,
2502,
11094,
273,
30052,
87,
63,
27863,
3752,
548,
15533,
203,
203,
3639,
309,
261,
3752,
18,
1896,
1225,
422,
374,
13,
203,
3639,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
203,
3639,
1731,
1578,
7291,
548,
273,
389,
588,
12148,
548,
12,
14872,
1769,
203,
540,
203,
3639,
288,
203,
5411,
389,
8507,
15254,
3752,
12,
27863,
3752,
548,
1769,
203,
3639,
289,
203,
203,
3639,
288,
203,
5411,
11094,
18,
3645,
4921,
273,
1203,
18,
5508,
31,
203,
203,
5411,
7291,
1016,
3335,
9802,
63,
27863,
3752,
548,
6362,
14872,
548,
65,
273,
404,
31,
203,
5411,
11094,
18,
1601,
414,
18,
6206,
12,
14872,
548,
1769,
203,
5411,
11094,
18,
12630,
18,
6206,
12,
2704,
7295,
1769,
203,
5411,
11094,
18,
17091,
1973,
18,
6206,
24899,
588,
29756,
529,
12,
14872,
548,
10019,
203,
203,
5411,
30891,
1776,
15254,
3752,
87,
2173,
12148,
63,
14872,
548,
8009,
6206,
12,
27863,
3752,
548,
1769,
203,
203,
5411,
327,
31,
203,
3639,
289,
203,
203,
3639,
1426,
711,
8351,
7295,
273,
629,
31,
203,
3639,
309,
261,
14872,
1016,
405,
374,
597,
7291,
1016,
411,
11094,
18,
1896,
1225,
13,
203,
3639,
288,
203,
5411,
711,
8351,
7295,
273,
638,
31,
203,
5411,
7291,
1016,
413,
31,
203,
3639,
289,
203,
203,
3639,
2
]
|
./partial_match/4/0x50FEC95AA6EEB2F14eEF9278e62D5961E25fFeB7/sources/NftFactory.sol | claim APWR amount
| uint256 private pwrdist = 0.003 * 1e18; | 8,770,000 | [
1,
14784,
14410,
7181,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2254,
5034,
3238,
8772,
86,
4413,
273,
374,
18,
25425,
380,
404,
73,
2643,
31,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.0;
// It's important to avoid vulnerabilities due to numeric overflow bugs
// OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs
// More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/
import "../contracts/SafeMath.sol";
/************************************************** */
/* FlightSurety Smart Contract */
/************************************************** */
contract FlightSuretyApp {
using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript)
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
FlightSuretyData flightSuretyData; //Data contract
// Flight status codees
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
bool private operational = true;
address private contractOwner; // Account used to deploy contract
mapping(bytes32 => Flight) private flights; //
uint256 public constant airlineFee = 10 ether; // Required fees to activate airlines registeration
uint256 public constant insurenceFee = 1 ether; // Maximum insurance fee
uint256 public constant consensusAirlinesNumber = 4; // Number of airlines that can register before consensus requirement
address[] private multiConsenses; // All voted airlines addresses
address payable dataContractAddress; // Data contract Address
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
string flightNumber;
}
//events
event airlineRegistred(address airline);
event airlineFunded(address airline);
event insurancePurchased(address airline, string flightNumber, uint256 timestamp, address _address , uint256 value);
event flightRegistered(string flightNumber);
event PassengerPayout(address airline);
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
// Modify to call data contract's status
require(isOperational(), "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
modifier checkValue()
{
require(msg.value >= airlineFee, 'Invalid fund value');
_;
uint256 refund = (msg.value).sub(airlineFee);
(msg.sender).transfer(refund);
}
modifier requireIsPassenger()
{
require(flightSuretyData.isPassenger(msg.sender), "Invalid passenger address");
_;
}
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Contract constructor
*
*/
constructor(address payable _dataContractAddress) public
{
contractOwner = msg.sender;
dataContractAddress = _dataContractAddress;
flightSuretyData = FlightSuretyData(dataContractAddress);
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational() public view returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus(bool mode) external requireContractOwner
{
operational = mode;
}
function isDataContractOperational() public view returns(bool)
{
return flightSuretyData.isOperational();
}
function isFlight(bytes32 flight) public view returns(bool)
{
return flights[flight].isRegistered;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
*
*/
function registerAirline(address _newAirline) external requireIsOperational returns(bool success, uint256 votes)
{
uint256 numRegisteredAirlines = flightSuretyData.getNumberOfRegistredAirline();
bool isDuplicated = false;
votes = 0;
if(numRegisteredAirlines <= consensusAirlinesNumber){
require(flightSuretyData.isRegistered(msg.sender), "Airline is not registred");
require(flightSuretyData.isFunded(msg.sender), "Airline is not funded");
votes = multiConsenses.length;
for(uint256 i=0 ; i < votes ; i++){
if(multiConsenses[i] == msg.sender){
isDuplicated = true;
success = false;
return (success, votes);
}
}
multiConsenses.push(msg.sender);
votes = multiConsenses.length;
if (votes >= (numRegisteredAirlines/2)){
multiConsenses = new address[](0);
}
}
if(!isDuplicated){
flightSuretyData.registerAirline(_newAirline);
success = true;
}
emit airlineRegistred(_newAirline);
return (success, votes);
}
function getRegisteredAirlines() external view returns(address[] memory){
return flightSuretyData.getRegisteredAirlines();
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fundAirline() external payable requireIsOperational checkValue
{
require(flightSuretyData.isRegistered(msg.sender), "Airline is not registred");
require(!flightSuretyData.isFunded(msg.sender), "Airline is already funded");
dataContractAddress.transfer(airlineFee);
flightSuretyData.fundAirline();
emit airlineFunded(msg.sender);
}
function getFundedAirlines() external view returns(address[] memory)
{
return flightSuretyData.getFundedAirlines();
}
/**
* @dev Register a new passenger.
*
*/
function registerPassenger(address _address) external
{
flightSuretyData.registerPassenger( _address);
}
/**
* @dev Passenger can buy an insurance.
*
*/
function buyInsurence(address _airline, string calldata _flightNumber, uint256 _timestamp) external payable requireIsOperational requireIsPassenger
{
bytes32 flightKey = flightSuretyData.getFlightKey(_airline, _flightNumber, _timestamp);
require (flights[flightKey].isRegistered, "Flight is not registered");
require(msg.value <= insurenceFee, "Invaled incurence fee");
require(msg.value > 0, "Invaled incurence fee");
flightSuretyData.buy.value(msg.value)(flightKey);
emit insurancePurchased(_airline, _flightNumber, _timestamp, msg.sender, msg.value);
}
/**
* @dev Register a future flight for insuring.
*
*/
function registerFlight(address _airline, string calldata _flightNumber, uint256 _timestamp) external requireIsOperational
{
bytes32 flightKey = flightSuretyData.getFlightKey(_airline, _flightNumber, _timestamp);
require (!flights[flightKey].isRegistered, "Flight is already registered");
flights[flightKey] = Flight({isRegistered: true, statusCode:STATUS_CODE_UNKNOWN, updatedTimestamp:_timestamp, airline: _airline, flightNumber: _flightNumber});
emit flightRegistered(_flightNumber);
}
/**
* @dev Called after oracle has updated flight status
*
*/
function processFlightStatus(bytes32 flightKey, uint8 statusCode) internal requireIsOperational
{
require(oracleResponses[flightKey].isOpen, "Flight status request is closed");
oracleResponses[flightKey].isOpen = false;
flights[flightKey].statusCode = statusCode;
if(statusCode == STATUS_CODE_LATE_AIRLINE)
{
flightSuretyData.creditInsurees(flightKey);
}
}
function payout() public requireIsOperational
{
emit PassengerPayout(msg.sender);
flightSuretyData.pay();
}
// Generate a request for oracles to fetch flight information
function fetchFlightStatus(address airline, string calldata flight, uint256 timestamp) external requireIsOperational
{
uint8 index = getRandomIndex(msg.sender);
// Generate a unique key for storing the request
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
oracleResponses[key] = ResponseInfo({requester: msg.sender, isOpen: true});
emit OracleRequest(index, airline, flight, timestamp);
}
// region ORACLE MANAGEMENT
// Incremented to add pseudo-randomness at various points
uint8 private nonce = 0;
// Fee to be paid when registering oracle
uint256 public constant REGISTRATION_FEE = 1 ether;
// Number of oracles that must respond for valid status
uint256 private constant MIN_RESPONSES = 3;
struct Oracle {
bool isRegistered;
uint8[3] indexes;
}
// Track all registered oracles
mapping(address => Oracle) private oracles;
// Model for responses from oracles
struct ResponseInfo {
address requester; // Account that requested status
bool isOpen; // If open, oracle responses are accepted
mapping(uint8 => address[]) responses; // Mapping key is the status code reported
// This lets us group responses and identify
// the response that majority of the oracles
}
// Track all oracle responses
// Key = hash(index, flight, timestamp)
mapping(bytes32 => ResponseInfo) private oracleResponses;
// Event fired each time an oracle submits a response
event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status);
event OracleReport(address airline, string flight, uint256 timestamp, uint8 status);
// Event fired when flight status request is submitted
// Oracles track this and if they have a matching index
// they fetch data and submit a response
event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp);
// Register an oracle with the contract
function registerOracle
(
)
external
payable
requireIsOperational
{
// Require registration fee
require(msg.value >= REGISTRATION_FEE, "Registration fee is required");
uint8[3] memory indexes = generateIndexes(msg.sender);
oracles[msg.sender] = Oracle({
isRegistered: true,
indexes: indexes
});
}
function getMyIndexes
(
)
view
external
requireIsOperational
returns( uint8[3] memory)
{
require(oracles[msg.sender].isRegistered, "Not registered as an oracle");
return oracles[msg.sender].indexes;
}
// Called by oracle when a response is available to an outstanding request
// For the response to be accepted, there must be a pending request that is open
// and matches one of the three Indexes randomly assigned to the oracle at the
// time of registration (i.e. uninvited oracles are not welcome)
function submitOracleResponse
(
uint8 index,
address airline,
string calldata flight,
uint256 timestamp,
uint8 statusCode
)
external
requireIsOperational
{
require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request");
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request");
oracleResponses[key].responses[statusCode].push(msg.sender);
// Information isn't considered verified until at least MIN_RESPONSES
// oracles respond with the *** same *** information
emit OracleReport(airline, flight, timestamp, statusCode);
if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) {
// Handle flight status as appropriate
processFlightStatus(key, statusCode);
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
}
}
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
// Returns array of three non-duplicating integers from 0-9
function generateIndexes
(
address account
)
internal
returns(uint8[3] memory)
{
uint8[3] memory indexes;
indexes[0] = getRandomIndex(account);
indexes[1] = indexes[0];
while(indexes[1] == indexes[0]) {
indexes[1] = getRandomIndex(account);
}
indexes[2] = indexes[1];
while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = getRandomIndex(account);
}
return indexes;
}
// Returns array of three non-duplicating integers from 0-9
function getRandomIndex
(
address account
)
internal
returns (uint8)
{
uint8 maxValue = 10;
// Pseudo random number...the incrementing nonce adds variation
uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue);
if (nonce > 250) {
nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt
}
return random;
}
// endregion
}
contract FlightSuretyData {
function isOperational() public view returns(bool);
function getNumberOfRegistredAirline() external view returns(uint256);
function registerAirline(address _newAirline) external returns(bool);
function getRegisteredAirlines() external view returns(address[] memory);
function isRegistered(address airline) public view returns(bool);
function fundAirline() external ;
function getFundedAirlines() external view returns(address[] memory);
function isFunded(address airline) public view returns(bool);
function registerPassenger(address _address) external;
function isPassenger(address _address) public view returns(bool);
function buy(bytes32 flightKey) external payable;
function getFlightKey(address airline, string calldata flight, uint256 timestamp) pure external returns(bytes32);
function creditInsurees(bytes32 flightKey) external view;
function pay() external payable;
} | ************************************************* */ FlightSurety Smart Contract */************************************************* */ Flight status codees | contract FlightSuretyApp {
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
bool private operational = true;
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
string flightNumber;
}
event airlineFunded(address airline);
event insurancePurchased(address airline, string flightNumber, uint256 timestamp, address _address , uint256 value);
event flightRegistered(string flightNumber);
event PassengerPayout(address airline);
event airlineRegistred(address airline);
modifier requireIsOperational()
{
require(isOperational(), "Contract is currently not operational");
}
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
modifier checkValue()
{
require(msg.value >= airlineFee, 'Invalid fund value');
_;
uint256 refund = (msg.value).sub(airlineFee);
(msg.sender).transfer(refund);
}
modifier requireIsPassenger()
{
require(flightSuretyData.isPassenger(msg.sender), "Invalid passenger address");
_;
}
constructor(address payable _dataContractAddress) public
{
contractOwner = msg.sender;
dataContractAddress = _dataContractAddress;
flightSuretyData = FlightSuretyData(dataContractAddress);
}
function isOperational() public view returns(bool)
{
return operational;
}
function setOperatingStatus(bool mode) external requireContractOwner
{
operational = mode;
}
function isDataContractOperational() public view returns(bool)
{
return flightSuretyData.isOperational();
}
function isFlight(bytes32 flight) public view returns(bool)
{
return flights[flight].isRegistered;
}
function registerAirline(address _newAirline) external requireIsOperational returns(bool success, uint256 votes)
{
uint256 numRegisteredAirlines = flightSuretyData.getNumberOfRegistredAirline();
bool isDuplicated = false;
votes = 0;
if(numRegisteredAirlines <= consensusAirlinesNumber){
require(flightSuretyData.isRegistered(msg.sender), "Airline is not registred");
require(flightSuretyData.isFunded(msg.sender), "Airline is not funded");
votes = multiConsenses.length;
for(uint256 i=0 ; i < votes ; i++){
if(multiConsenses[i] == msg.sender){
isDuplicated = true;
success = false;
return (success, votes);
}
}
multiConsenses.push(msg.sender);
votes = multiConsenses.length;
if (votes >= (numRegisteredAirlines/2)){
multiConsenses = new address[](0);
}
}
if(!isDuplicated){
flightSuretyData.registerAirline(_newAirline);
success = true;
}
emit airlineRegistred(_newAirline);
return (success, votes);
}
function registerAirline(address _newAirline) external requireIsOperational returns(bool success, uint256 votes)
{
uint256 numRegisteredAirlines = flightSuretyData.getNumberOfRegistredAirline();
bool isDuplicated = false;
votes = 0;
if(numRegisteredAirlines <= consensusAirlinesNumber){
require(flightSuretyData.isRegistered(msg.sender), "Airline is not registred");
require(flightSuretyData.isFunded(msg.sender), "Airline is not funded");
votes = multiConsenses.length;
for(uint256 i=0 ; i < votes ; i++){
if(multiConsenses[i] == msg.sender){
isDuplicated = true;
success = false;
return (success, votes);
}
}
multiConsenses.push(msg.sender);
votes = multiConsenses.length;
if (votes >= (numRegisteredAirlines/2)){
multiConsenses = new address[](0);
}
}
if(!isDuplicated){
flightSuretyData.registerAirline(_newAirline);
success = true;
}
emit airlineRegistred(_newAirline);
return (success, votes);
}
function registerAirline(address _newAirline) external requireIsOperational returns(bool success, uint256 votes)
{
uint256 numRegisteredAirlines = flightSuretyData.getNumberOfRegistredAirline();
bool isDuplicated = false;
votes = 0;
if(numRegisteredAirlines <= consensusAirlinesNumber){
require(flightSuretyData.isRegistered(msg.sender), "Airline is not registred");
require(flightSuretyData.isFunded(msg.sender), "Airline is not funded");
votes = multiConsenses.length;
for(uint256 i=0 ; i < votes ; i++){
if(multiConsenses[i] == msg.sender){
isDuplicated = true;
success = false;
return (success, votes);
}
}
multiConsenses.push(msg.sender);
votes = multiConsenses.length;
if (votes >= (numRegisteredAirlines/2)){
multiConsenses = new address[](0);
}
}
if(!isDuplicated){
flightSuretyData.registerAirline(_newAirline);
success = true;
}
emit airlineRegistred(_newAirline);
return (success, votes);
}
function registerAirline(address _newAirline) external requireIsOperational returns(bool success, uint256 votes)
{
uint256 numRegisteredAirlines = flightSuretyData.getNumberOfRegistredAirline();
bool isDuplicated = false;
votes = 0;
if(numRegisteredAirlines <= consensusAirlinesNumber){
require(flightSuretyData.isRegistered(msg.sender), "Airline is not registred");
require(flightSuretyData.isFunded(msg.sender), "Airline is not funded");
votes = multiConsenses.length;
for(uint256 i=0 ; i < votes ; i++){
if(multiConsenses[i] == msg.sender){
isDuplicated = true;
success = false;
return (success, votes);
}
}
multiConsenses.push(msg.sender);
votes = multiConsenses.length;
if (votes >= (numRegisteredAirlines/2)){
multiConsenses = new address[](0);
}
}
if(!isDuplicated){
flightSuretyData.registerAirline(_newAirline);
success = true;
}
emit airlineRegistred(_newAirline);
return (success, votes);
}
function registerAirline(address _newAirline) external requireIsOperational returns(bool success, uint256 votes)
{
uint256 numRegisteredAirlines = flightSuretyData.getNumberOfRegistredAirline();
bool isDuplicated = false;
votes = 0;
if(numRegisteredAirlines <= consensusAirlinesNumber){
require(flightSuretyData.isRegistered(msg.sender), "Airline is not registred");
require(flightSuretyData.isFunded(msg.sender), "Airline is not funded");
votes = multiConsenses.length;
for(uint256 i=0 ; i < votes ; i++){
if(multiConsenses[i] == msg.sender){
isDuplicated = true;
success = false;
return (success, votes);
}
}
multiConsenses.push(msg.sender);
votes = multiConsenses.length;
if (votes >= (numRegisteredAirlines/2)){
multiConsenses = new address[](0);
}
}
if(!isDuplicated){
flightSuretyData.registerAirline(_newAirline);
success = true;
}
emit airlineRegistred(_newAirline);
return (success, votes);
}
function registerAirline(address _newAirline) external requireIsOperational returns(bool success, uint256 votes)
{
uint256 numRegisteredAirlines = flightSuretyData.getNumberOfRegistredAirline();
bool isDuplicated = false;
votes = 0;
if(numRegisteredAirlines <= consensusAirlinesNumber){
require(flightSuretyData.isRegistered(msg.sender), "Airline is not registred");
require(flightSuretyData.isFunded(msg.sender), "Airline is not funded");
votes = multiConsenses.length;
for(uint256 i=0 ; i < votes ; i++){
if(multiConsenses[i] == msg.sender){
isDuplicated = true;
success = false;
return (success, votes);
}
}
multiConsenses.push(msg.sender);
votes = multiConsenses.length;
if (votes >= (numRegisteredAirlines/2)){
multiConsenses = new address[](0);
}
}
if(!isDuplicated){
flightSuretyData.registerAirline(_newAirline);
success = true;
}
emit airlineRegistred(_newAirline);
return (success, votes);
}
function getRegisteredAirlines() external view returns(address[] memory){
return flightSuretyData.getRegisteredAirlines();
}
function fundAirline() external payable requireIsOperational checkValue
{
require(flightSuretyData.isRegistered(msg.sender), "Airline is not registred");
require(!flightSuretyData.isFunded(msg.sender), "Airline is already funded");
dataContractAddress.transfer(airlineFee);
flightSuretyData.fundAirline();
emit airlineFunded(msg.sender);
}
function getFundedAirlines() external view returns(address[] memory)
{
return flightSuretyData.getFundedAirlines();
}
function registerPassenger(address _address) external
{
flightSuretyData.registerPassenger( _address);
}
function buyInsurence(address _airline, string calldata _flightNumber, uint256 _timestamp) external payable requireIsOperational requireIsPassenger
{
bytes32 flightKey = flightSuretyData.getFlightKey(_airline, _flightNumber, _timestamp);
require (flights[flightKey].isRegistered, "Flight is not registered");
require(msg.value <= insurenceFee, "Invaled incurence fee");
require(msg.value > 0, "Invaled incurence fee");
flightSuretyData.buy.value(msg.value)(flightKey);
emit insurancePurchased(_airline, _flightNumber, _timestamp, msg.sender, msg.value);
}
function registerFlight(address _airline, string calldata _flightNumber, uint256 _timestamp) external requireIsOperational
{
bytes32 flightKey = flightSuretyData.getFlightKey(_airline, _flightNumber, _timestamp);
require (!flights[flightKey].isRegistered, "Flight is already registered");
emit flightRegistered(_flightNumber);
}
flights[flightKey] = Flight({isRegistered: true, statusCode:STATUS_CODE_UNKNOWN, updatedTimestamp:_timestamp, airline: _airline, flightNumber: _flightNumber});
function processFlightStatus(bytes32 flightKey, uint8 statusCode) internal requireIsOperational
{
require(oracleResponses[flightKey].isOpen, "Flight status request is closed");
oracleResponses[flightKey].isOpen = false;
flights[flightKey].statusCode = statusCode;
if(statusCode == STATUS_CODE_LATE_AIRLINE)
{
flightSuretyData.creditInsurees(flightKey);
}
}
function processFlightStatus(bytes32 flightKey, uint8 statusCode) internal requireIsOperational
{
require(oracleResponses[flightKey].isOpen, "Flight status request is closed");
oracleResponses[flightKey].isOpen = false;
flights[flightKey].statusCode = statusCode;
if(statusCode == STATUS_CODE_LATE_AIRLINE)
{
flightSuretyData.creditInsurees(flightKey);
}
}
function payout() public requireIsOperational
{
emit PassengerPayout(msg.sender);
flightSuretyData.pay();
}
function fetchFlightStatus(address airline, string calldata flight, uint256 timestamp) external requireIsOperational
{
uint8 index = getRandomIndex(msg.sender);
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
emit OracleRequest(index, airline, flight, timestamp);
}
oracleResponses[key] = ResponseInfo({requester: msg.sender, isOpen: true});
uint8 private nonce = 0;
uint256 public constant REGISTRATION_FEE = 1 ether;
uint256 private constant MIN_RESPONSES = 3;
struct Oracle {
bool isRegistered;
uint8[3] indexes;
}
mapping(address => Oracle) private oracles;
struct ResponseInfo {
}
event OracleReport(address airline, string flight, uint256 timestamp, uint8 status);
mapping(bytes32 => ResponseInfo) private oracleResponses;
event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status);
event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp);
function registerOracle
(
)
external
payable
requireIsOperational
{
require(msg.value >= REGISTRATION_FEE, "Registration fee is required");
uint8[3] memory indexes = generateIndexes(msg.sender);
oracles[msg.sender] = Oracle({
isRegistered: true,
indexes: indexes
});
}
function registerOracle
(
)
external
payable
requireIsOperational
{
require(msg.value >= REGISTRATION_FEE, "Registration fee is required");
uint8[3] memory indexes = generateIndexes(msg.sender);
oracles[msg.sender] = Oracle({
isRegistered: true,
indexes: indexes
});
}
function getMyIndexes
(
)
view
external
requireIsOperational
returns( uint8[3] memory)
{
require(oracles[msg.sender].isRegistered, "Not registered as an oracle");
return oracles[msg.sender].indexes;
}
function submitOracleResponse
(
uint8 index,
address airline,
string calldata flight,
uint256 timestamp,
uint8 statusCode
)
external
requireIsOperational
{
require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request");
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request");
oracleResponses[key].responses[statusCode].push(msg.sender);
emit OracleReport(airline, flight, timestamp, statusCode);
if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) {
processFlightStatus(key, statusCode);
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
}
}
function submitOracleResponse
(
uint8 index,
address airline,
string calldata flight,
uint256 timestamp,
uint8 statusCode
)
external
requireIsOperational
{
require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request");
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request");
oracleResponses[key].responses[statusCode].push(msg.sender);
emit OracleReport(airline, flight, timestamp, statusCode);
if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) {
processFlightStatus(key, statusCode);
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
}
}
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
function generateIndexes
(
address account
)
internal
returns(uint8[3] memory)
{
uint8[3] memory indexes;
indexes[0] = getRandomIndex(account);
indexes[1] = indexes[0];
while(indexes[1] == indexes[0]) {
indexes[1] = getRandomIndex(account);
}
indexes[2] = indexes[1];
while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = getRandomIndex(account);
}
return indexes;
}
function generateIndexes
(
address account
)
internal
returns(uint8[3] memory)
{
uint8[3] memory indexes;
indexes[0] = getRandomIndex(account);
indexes[1] = indexes[0];
while(indexes[1] == indexes[0]) {
indexes[1] = getRandomIndex(account);
}
indexes[2] = indexes[1];
while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = getRandomIndex(account);
}
return indexes;
}
function generateIndexes
(
address account
)
internal
returns(uint8[3] memory)
{
uint8[3] memory indexes;
indexes[0] = getRandomIndex(account);
indexes[1] = indexes[0];
while(indexes[1] == indexes[0]) {
indexes[1] = getRandomIndex(account);
}
indexes[2] = indexes[1];
while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = getRandomIndex(account);
}
return indexes;
}
function getRandomIndex
(
address account
)
internal
returns (uint8)
{
uint8 maxValue = 10;
uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue);
if (nonce > 250) {
}
return random;
}
function getRandomIndex
(
address account
)
internal
returns (uint8)
{
uint8 maxValue = 10;
uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue);
if (nonce > 250) {
}
return random;
}
}
| 5,353,193 | [
1,
19,
3857,
750,
55,
594,
4098,
19656,
13456,
8227,
342,
342,
3857,
750,
1267,
981,
281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
3857,
750,
55,
594,
4098,
3371,
288,
203,
203,
203,
203,
565,
2254,
28,
3238,
5381,
7136,
67,
5572,
67,
14737,
273,
374,
31,
203,
565,
2254,
28,
3238,
5381,
7136,
67,
5572,
67,
673,
67,
4684,
273,
1728,
31,
203,
565,
2254,
28,
3238,
5381,
7136,
67,
5572,
67,
10512,
67,
37,
7937,
5997,
273,
4200,
31,
203,
565,
2254,
28,
3238,
5381,
7136,
67,
5572,
67,
10512,
67,
6950,
3275,
654,
273,
5196,
31,
203,
565,
2254,
28,
3238,
5381,
7136,
67,
5572,
67,
10512,
67,
1448,
1792,
50,
10109,
273,
8063,
31,
203,
565,
2254,
28,
3238,
5381,
7136,
67,
5572,
67,
10512,
67,
23940,
273,
6437,
31,
203,
203,
565,
1426,
3238,
1674,
287,
273,
638,
31,
7010,
377,
203,
203,
203,
565,
1958,
3857,
750,
288,
203,
3639,
1426,
353,
10868,
31,
203,
3639,
2254,
28,
6593,
31,
203,
3639,
2254,
5034,
3526,
4921,
31,
540,
203,
3639,
1758,
23350,
1369,
31,
203,
3639,
533,
25187,
1854,
31,
203,
565,
289,
203,
203,
565,
871,
23350,
1369,
42,
12254,
12,
2867,
23350,
1369,
1769,
203,
565,
871,
2763,
295,
1359,
10262,
343,
8905,
12,
2867,
23350,
1369,
16,
533,
25187,
1854,
16,
2254,
5034,
2858,
16,
1758,
389,
2867,
269,
2254,
5034,
460,
1769,
203,
565,
871,
25187,
10868,
12,
1080,
25187,
1854,
1769,
203,
565,
871,
10311,
14348,
52,
2012,
12,
2867,
23350,
1369,
1769,
203,
203,
565,
871,
23350,
1369,
1617,
376,
1118,
12,
2867,
23350,
1369,
1769,
203,
203,
203,
565,
9606,
2583,
2520,
2988,
2
]
|
import "Base.sol";
// The canary database
contract CanaryDb is TlcEnabled {
// When did the user last stimulate their canary?
mapping (address => uint) public lastStimulated;
// When was the canary birthed?
mapping (address => uint) public aliveSince;
// Canary types:
// 0 : Does not die from hearbeat timeout
// 1 - 99 : Dies of natural causes after n days of inactivity.
// >= 100 : Not used at this time, reserved for future use.
mapping (address => uint) public canaryTypes;
// Canary status:
// 0 : Created
// 1 : Activated
// 2 : Killed
// 3 : Died (lack of stimulation)
// 4 : Invalid (past valid until date)
mapping (address => uint) public canaryStatuses;
mapping (address => uint) public canaryBalances;
mapping (address => uint) public canaryExpiries;
function create(address addr, uint canaryType) returns (bool res) {
if(TLC != 0x0){
address canary = ContractProvider(TLC).contracts("canary");
if (msg.sender == canary ){
// Check we have received a valid canary type.
if (canaryTypes[addr] < 100){
canaryStatuses[addr] = 0;
canaryTypes[addr] = canaryType;
canaryBalances[addr] = msg.value;
return true;
}
}
}
// Return if deposit cannot be made.
msg.sender.send(msg.value);
return false;
}
function birth(address addr) returns (bool res){
if(canaryStatuses[addr] == 0){
// Liiiiive!!!
canaryStatuses[addr] = 1;
aliveSince[addr] = now;
return true;
}
return false;
}
function stimulate(address addr) returns (bool res){
// Check if canary is alive.
if(canaryStatuses[addr] == 1){
// Store time of stimulation.
lastStimulated[addr] = now;
return true;
}
// You cannot stimulate that which is not alive.
return false;
}
function heartbeat(address addr) returns (bool res){
// Check if canary is alive.
if(canaryStatuses[addr] == 1){
// Check canary can die from lack of stimulation.
if(canaryTypes[addr] >= 1) {
// Death by lack of stimulation.
canaryStatuses[addr] = 3;
return false;
}
// TODO: check this code, are we using the right data type?
if(canaryExpiries[addr] <= now){
// Invalid / Expired canary.
canaryStatuses[addr] = 4;
return false;
}
}
// Things that are not alive do not have a heartbeat.
return true;
}
function kill(address addr) returns (bool res){
// Check if canary is alive.
if(canaryStatuses[addr] == 1){
// Kill it.
canaryStatuses[addr] = 2;
}
// You cannot kill that which is not alive.
return false;
}
// TODO: should we be checking if the canary is killed or dead here
// or should we do it on the Canary contract? I think this is wrong.
function withdraw(address addr, uint amount) returns (bool res) {
// Check if TLC has been registered.
if(TLC != 0x0){
// Check if canary is killed or dead.
if(canaryStatuses[addr] >= 2){
address canary = ContractProvider(TLC).contracts("canary");
if (msg.sender == canary ){
uint oldBalance = canaryBalances[addr];
if(oldBalance >= amount){
msg.sender.send(amount);
canaryBalances[addr] = oldBalance - amount;
return true;
}
}
}
}
return false;
}
}
| The canary database When did the user last stimulate their canary? When was the canary birthed? Canary types: 0 : Does not die from hearbeat timeout 1 - 99 : Dies of natural causes after n days of inactivity. >= 100 : Not used at this time, reserved for future use. Canary status: 0 : Created 1 : Activated 2 : Killed 3 : Died (lack of stimulation) 4 : Invalid (past valid until date) | contract CanaryDb is TlcEnabled {
mapping (address => uint) public lastStimulated;
mapping (address => uint) public aliveSince;
mapping (address => uint) public canaryTypes;
mapping (address => uint) public canaryStatuses;
mapping (address => uint) public canaryBalances;
mapping (address => uint) public canaryExpiries;
function create(address addr, uint canaryType) returns (bool res) {
if(TLC != 0x0){
address canary = ContractProvider(TLC).contracts("canary");
if (msg.sender == canary ){
if (canaryTypes[addr] < 100){
canaryStatuses[addr] = 0;
canaryTypes[addr] = canaryType;
canaryBalances[addr] = msg.value;
return true;
}
}
}
return false;
}
function create(address addr, uint canaryType) returns (bool res) {
if(TLC != 0x0){
address canary = ContractProvider(TLC).contracts("canary");
if (msg.sender == canary ){
if (canaryTypes[addr] < 100){
canaryStatuses[addr] = 0;
canaryTypes[addr] = canaryType;
canaryBalances[addr] = msg.value;
return true;
}
}
}
return false;
}
function create(address addr, uint canaryType) returns (bool res) {
if(TLC != 0x0){
address canary = ContractProvider(TLC).contracts("canary");
if (msg.sender == canary ){
if (canaryTypes[addr] < 100){
canaryStatuses[addr] = 0;
canaryTypes[addr] = canaryType;
canaryBalances[addr] = msg.value;
return true;
}
}
}
return false;
}
function create(address addr, uint canaryType) returns (bool res) {
if(TLC != 0x0){
address canary = ContractProvider(TLC).contracts("canary");
if (msg.sender == canary ){
if (canaryTypes[addr] < 100){
canaryStatuses[addr] = 0;
canaryTypes[addr] = canaryType;
canaryBalances[addr] = msg.value;
return true;
}
}
}
return false;
}
msg.sender.send(msg.value);
function birth(address addr) returns (bool res){
if(canaryStatuses[addr] == 0){
canaryStatuses[addr] = 1;
aliveSince[addr] = now;
return true;
}
return false;
}
function birth(address addr) returns (bool res){
if(canaryStatuses[addr] == 0){
canaryStatuses[addr] = 1;
aliveSince[addr] = now;
return true;
}
return false;
}
function stimulate(address addr) returns (bool res){
if(canaryStatuses[addr] == 1){
lastStimulated[addr] = now;
return true;
}
}
function stimulate(address addr) returns (bool res){
if(canaryStatuses[addr] == 1){
lastStimulated[addr] = now;
return true;
}
}
return false;
function heartbeat(address addr) returns (bool res){
if(canaryStatuses[addr] == 1){
if(canaryTypes[addr] >= 1) {
canaryStatuses[addr] = 3;
return false;
}
if(canaryExpiries[addr] <= now){
canaryStatuses[addr] = 4;
return false;
}
}
}
function heartbeat(address addr) returns (bool res){
if(canaryStatuses[addr] == 1){
if(canaryTypes[addr] >= 1) {
canaryStatuses[addr] = 3;
return false;
}
if(canaryExpiries[addr] <= now){
canaryStatuses[addr] = 4;
return false;
}
}
}
function heartbeat(address addr) returns (bool res){
if(canaryStatuses[addr] == 1){
if(canaryTypes[addr] >= 1) {
canaryStatuses[addr] = 3;
return false;
}
if(canaryExpiries[addr] <= now){
canaryStatuses[addr] = 4;
return false;
}
}
}
function heartbeat(address addr) returns (bool res){
if(canaryStatuses[addr] == 1){
if(canaryTypes[addr] >= 1) {
canaryStatuses[addr] = 3;
return false;
}
if(canaryExpiries[addr] <= now){
canaryStatuses[addr] = 4;
return false;
}
}
}
return true;
function kill(address addr) returns (bool res){
if(canaryStatuses[addr] == 1){
canaryStatuses[addr] = 2;
}
}
function kill(address addr) returns (bool res){
if(canaryStatuses[addr] == 1){
canaryStatuses[addr] = 2;
}
}
return false;
function withdraw(address addr, uint amount) returns (bool res) {
if(TLC != 0x0){
if(canaryStatuses[addr] >= 2){
address canary = ContractProvider(TLC).contracts("canary");
if (msg.sender == canary ){
uint oldBalance = canaryBalances[addr];
if(oldBalance >= amount){
msg.sender.send(amount);
canaryBalances[addr] = oldBalance - amount;
return true;
}
}
}
}
return false;
}
function withdraw(address addr, uint amount) returns (bool res) {
if(TLC != 0x0){
if(canaryStatuses[addr] >= 2){
address canary = ContractProvider(TLC).contracts("canary");
if (msg.sender == canary ){
uint oldBalance = canaryBalances[addr];
if(oldBalance >= amount){
msg.sender.send(amount);
canaryBalances[addr] = oldBalance - amount;
return true;
}
}
}
}
return false;
}
function withdraw(address addr, uint amount) returns (bool res) {
if(TLC != 0x0){
if(canaryStatuses[addr] >= 2){
address canary = ContractProvider(TLC).contracts("canary");
if (msg.sender == canary ){
uint oldBalance = canaryBalances[addr];
if(oldBalance >= amount){
msg.sender.send(amount);
canaryBalances[addr] = oldBalance - amount;
return true;
}
}
}
}
return false;
}
function withdraw(address addr, uint amount) returns (bool res) {
if(TLC != 0x0){
if(canaryStatuses[addr] >= 2){
address canary = ContractProvider(TLC).contracts("canary");
if (msg.sender == canary ){
uint oldBalance = canaryBalances[addr];
if(oldBalance >= amount){
msg.sender.send(amount);
canaryBalances[addr] = oldBalance - amount;
return true;
}
}
}
}
return false;
}
function withdraw(address addr, uint amount) returns (bool res) {
if(TLC != 0x0){
if(canaryStatuses[addr] >= 2){
address canary = ContractProvider(TLC).contracts("canary");
if (msg.sender == canary ){
uint oldBalance = canaryBalances[addr];
if(oldBalance >= amount){
msg.sender.send(amount);
canaryBalances[addr] = oldBalance - amount;
return true;
}
}
}
}
return false;
}
}
| 12,733,157 | [
1,
1986,
848,
814,
2063,
5203,
5061,
326,
729,
1142,
25542,
6243,
3675,
848,
814,
35,
5203,
1703,
326,
848,
814,
17057,
329,
35,
4480,
814,
1953,
30,
374,
294,
9637,
486,
10387,
628,
366,
2091,
2196,
270,
2021,
404,
300,
14605,
294,
463,
606,
434,
15145,
14119,
1839,
290,
4681,
434,
316,
9653,
18,
1545,
2130,
294,
2288,
1399,
622,
333,
813,
16,
8735,
364,
3563,
999,
18,
4480,
814,
1267,
30,
374,
294,
12953,
404,
294,
26939,
690,
576,
294,
1475,
13148,
890,
294,
463,
2092,
261,
80,
484,
434,
25542,
6234,
13,
1059,
294,
1962,
261,
84,
689,
923,
3180,
1509,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
16351,
4480,
814,
4331,
353,
399,
17704,
1526,
288,
203,
203,
565,
2874,
261,
2867,
516,
2254,
13,
1071,
1142,
510,
381,
11799,
31,
203,
565,
2874,
261,
2867,
516,
2254,
13,
1071,
13714,
9673,
31,
203,
565,
2874,
261,
2867,
516,
2254,
13,
1071,
848,
814,
2016,
31,
203,
565,
2874,
261,
2867,
516,
2254,
13,
1071,
848,
814,
15220,
31,
203,
565,
2874,
261,
2867,
516,
2254,
13,
1071,
848,
814,
38,
26488,
31,
203,
565,
2874,
261,
2867,
516,
2254,
13,
1071,
848,
814,
2966,
481,
606,
31,
203,
203,
565,
445,
752,
12,
2867,
3091,
16,
2254,
848,
814,
559,
13,
1135,
261,
6430,
400,
13,
288,
203,
3639,
309,
12,
5967,
39,
480,
374,
92,
20,
15329,
203,
5411,
1758,
848,
814,
273,
13456,
2249,
12,
5967,
39,
2934,
16351,
87,
2932,
4169,
814,
8863,
203,
5411,
309,
261,
3576,
18,
15330,
422,
848,
814,
262,
95,
203,
7734,
309,
261,
4169,
814,
2016,
63,
4793,
65,
411,
2130,
15329,
203,
10792,
848,
814,
15220,
63,
4793,
65,
273,
374,
31,
203,
10792,
848,
814,
2016,
63,
4793,
65,
273,
848,
814,
559,
31,
203,
10792,
848,
814,
38,
26488,
63,
4793,
65,
273,
1234,
18,
1132,
31,
203,
10792,
327,
638,
31,
203,
7734,
289,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
629,
31,
203,
565,
289,
203,
203,
565,
445,
752,
12,
2867,
3091,
16,
2254,
848,
814,
559,
13,
1135,
261,
6430,
400,
13,
288,
203,
3639,
309,
12,
5967,
39,
480,
374,
92,
2
]
|
./full_match/1/0x8E4097eCfcc60F25fF2D7EE4d472ECa4A28a8425/sources/src/Libraries/LibDiamond.sol | an immutable function is a function defined directly in a diamond replace selector with last selector, then delete last selector if not the same then replace _selector with lastSelector delete the last selector if no more selectors for facet address then delete the facet address replace facet address with last facet address and delete last facet address | function removeFunction(
DiamondStorage storage ds,
address _facetAddress,
bytes4 _selector
) internal {
if (LibUtil.isZeroAddress(_facetAddress)) {
revert FunctionDoesNotExist();
}
if (_facetAddress == address(this)) {
revert FunctionIsImmutable();
}
uint256 selectorPosition = ds.selectorToFacetAndPosition[_selector].functionSelectorPosition;
uint256 lastSelectorPosition = ds.facetFunctionSelectors[_facetAddress].functionSelectors.length - 1;
if (selectorPosition != lastSelectorPosition) {
bytes4 lastSelector = ds.facetFunctionSelectors[_facetAddress].functionSelectors[lastSelectorPosition];
ds.facetFunctionSelectors[_facetAddress].functionSelectors[selectorPosition] = lastSelector;
ds.selectorToFacetAndPosition[lastSelector].functionSelectorPosition = uint96(selectorPosition);
}
ds.facetFunctionSelectors[_facetAddress].functionSelectors.pop();
delete ds.selectorToFacetAndPosition[_selector];
if (lastSelectorPosition == 0) {
uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1;
uint256 facetAddressPosition = ds.facetFunctionSelectors[_facetAddress].facetAddressPosition;
if (facetAddressPosition != lastFacetAddressPosition) {
address lastFacetAddress = ds.facetAddresses[lastFacetAddressPosition];
ds.facetAddresses[facetAddressPosition] = lastFacetAddress;
ds.facetFunctionSelectors[lastFacetAddress].facetAddressPosition = facetAddressPosition;
}
ds.facetAddresses.pop();
delete ds.facetFunctionSelectors[_facetAddress].facetAddressPosition;
}
}
| 4,891,794 | [
1,
304,
11732,
445,
353,
279,
445,
2553,
5122,
316,
279,
4314,
301,
1434,
1453,
3451,
598,
1142,
3451,
16,
1508,
1430,
1142,
3451,
309,
486,
326,
1967,
1508,
1453,
389,
9663,
598,
1142,
4320,
1430,
326,
1142,
3451,
309,
1158,
1898,
11424,
364,
11082,
1758,
1508,
1430,
326,
11082,
1758,
1453,
11082,
1758,
598,
1142,
11082,
1758,
471,
1430,
1142,
11082,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
1206,
2083,
12,
203,
3639,
12508,
301,
1434,
3245,
2502,
3780,
16,
203,
3639,
1758,
389,
21568,
1887,
16,
203,
3639,
1731,
24,
389,
9663,
203,
565,
262,
2713,
288,
203,
3639,
309,
261,
5664,
1304,
18,
291,
7170,
1887,
24899,
21568,
1887,
3719,
288,
203,
5411,
15226,
4284,
15264,
5621,
203,
3639,
289,
203,
3639,
309,
261,
67,
21568,
1887,
422,
1758,
12,
2211,
3719,
288,
203,
5411,
15226,
4284,
2520,
16014,
5621,
203,
3639,
289,
203,
3639,
2254,
5034,
3451,
2555,
273,
3780,
18,
9663,
774,
11137,
1876,
2555,
63,
67,
9663,
8009,
915,
4320,
2555,
31,
203,
3639,
2254,
5034,
1142,
4320,
2555,
273,
3780,
18,
21568,
2083,
19277,
63,
67,
21568,
1887,
8009,
915,
19277,
18,
2469,
300,
404,
31,
203,
3639,
309,
261,
9663,
2555,
480,
1142,
4320,
2555,
13,
288,
203,
5411,
1731,
24,
1142,
4320,
273,
3780,
18,
21568,
2083,
19277,
63,
67,
21568,
1887,
8009,
915,
19277,
63,
2722,
4320,
2555,
15533,
203,
5411,
3780,
18,
21568,
2083,
19277,
63,
67,
21568,
1887,
8009,
915,
19277,
63,
9663,
2555,
65,
273,
1142,
4320,
31,
203,
5411,
3780,
18,
9663,
774,
11137,
1876,
2555,
63,
2722,
4320,
8009,
915,
4320,
2555,
273,
2254,
10525,
12,
9663,
2555,
1769,
203,
3639,
289,
203,
3639,
3780,
18,
21568,
2083,
19277,
63,
67,
21568,
1887,
8009,
915,
19277,
18,
5120,
5621,
203,
3639,
1430,
3780,
18,
9663,
774,
11137,
1876,
2555,
63,
67,
9663,
15533,
203,
203,
3639,
309,
261,
2722,
4320,
2555,
422,
374,
13,
288,
203,
2
]
|
./full_match/80001/0xd69c1f2C3Cf3D9c46C325aADc5078d8a5feDB08c/sources/src/Contract.sol | function for admin to get all complaint data | function getAllComplaints() external view onlyAdmin returns (Complaint[] memory) {
Complaint[] memory allComplaints = new Complaint[](complaintCount);
for (uint256 i = 0; i < complaintCount; i++) {
allComplaints[i] = complaints[complainter[i]];
}
return allComplaints;
}
| 5,590,412 | [
1,
915,
364,
3981,
358,
336,
777,
27534,
1598,
501,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
5514,
799,
412,
1598,
87,
1435,
3903,
1476,
1338,
4446,
1135,
261,
799,
412,
1598,
8526,
3778,
13,
288,
203,
3639,
1286,
412,
1598,
8526,
3778,
777,
799,
412,
1598,
87,
273,
394,
1286,
412,
1598,
8526,
12,
832,
412,
1598,
1380,
1769,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
27534,
1598,
1380,
31,
277,
27245,
288,
203,
5411,
777,
799,
412,
1598,
87,
63,
77,
65,
273,
27534,
1598,
87,
63,
832,
7446,
387,
63,
77,
13563,
31,
203,
3639,
289,
203,
3639,
327,
777,
799,
412,
1598,
87,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "../whitelist/Whitelist.sol";
import "./interfaces/IRequesterAuthorizer.sol";
/// @title Abstract contract that can be used to build Airnode authorizers that
/// temporarily or permanently whitelist requesters for Airnode–endpoint pairs
abstract contract RequesterAuthorizer is Whitelist, IRequesterAuthorizer {
/// @notice Extends the expiration of the temporary whitelist of
/// `requester` for the `airnode`–`endpointId` pair and emits an event
/// @param airnode Airnode address
/// @param endpointId Endpoint ID
/// @param requester Requester address
/// @param expirationTimestamp Timestamp at which the temporary whitelist
/// will expire
function _extendWhitelistExpirationAndEmit(
address airnode,
bytes32 endpointId,
address requester,
uint64 expirationTimestamp
) internal {
_extendWhitelistExpiration(
deriveServiceId(airnode, endpointId),
requester,
expirationTimestamp
);
emit ExtendedWhitelistExpiration(
airnode,
endpointId,
requester,
msg.sender,
expirationTimestamp
);
}
/// @notice Sets the expiration of the temporary whitelist of `requester`
/// for the `airnode`–`endpointId` pair and emits an event
/// @dev Unlike `_extendWhitelistExpiration()`, this can hasten expiration.
/// Emits the event even if it does not change the state.
/// @param airnode Airnode address
/// @param endpointId Endpoint ID
/// @param requester Requester address
/// @param expirationTimestamp Timestamp at which the temporary whitelist
/// will expire
function _setWhitelistExpirationAndEmit(
address airnode,
bytes32 endpointId,
address requester,
uint64 expirationTimestamp
) internal {
_setWhitelistExpiration(
deriveServiceId(airnode, endpointId),
requester,
expirationTimestamp
);
emit SetWhitelistExpiration(
airnode,
endpointId,
requester,
msg.sender,
expirationTimestamp
);
}
/// @notice Sets the indefinite whitelist status of `requester` for the
/// `airnode`–`endpointId` pair and emits an event
/// @dev Emits the event even if it does not change the state.
/// @param airnode Airnode address
/// @param endpointId Endpoint ID
/// @param requester Requester address
/// @param status Indefinite whitelist status
function _setIndefiniteWhitelistStatusAndEmit(
address airnode,
bytes32 endpointId,
address requester,
bool status
) internal {
uint192 indefiniteWhitelistCount = _setIndefiniteWhitelistStatus(
deriveServiceId(airnode, endpointId),
requester,
status
);
emit SetIndefiniteWhitelistStatus(
airnode,
endpointId,
requester,
msg.sender,
status,
indefiniteWhitelistCount
);
}
/// @notice Revokes the indefinite whitelist status granted to `requester`
/// for the `airnode`–`endpointId` pair by a specific account and emits an
/// event
/// @dev Only emits the event if it changes the state
/// @param airnode Airnode address
/// @param endpointId Endpoint ID
/// @param requester Requester address
/// @param setter Setter of the indefinite whitelist status
function _revokeIndefiniteWhitelistStatusAndEmit(
address airnode,
bytes32 endpointId,
address requester,
address setter
) internal {
(
bool revoked,
uint192 indefiniteWhitelistCount
) = _revokeIndefiniteWhitelistStatus(
deriveServiceId(airnode, endpointId),
requester,
setter
);
if (revoked) {
emit RevokedIndefiniteWhitelistStatus(
airnode,
endpointId,
requester,
setter,
msg.sender,
indefiniteWhitelistCount
);
}
}
/// @notice Returns if `requester` is whitelisted for the
/// `airnode`–`endpointId` pair
/// @param airnode Airnode address
/// @param endpointId Endpoint ID
/// @param requester Requester address
/// @return isWhitelisted If `requester` is whitelisted for the
/// `airnode`–`endpointId` pair
function requesterIsWhitelisted(
address airnode,
bytes32 endpointId,
address requester
) public view override returns (bool isWhitelisted) {
isWhitelisted = userIsWhitelisted(
deriveServiceId(airnode, endpointId),
requester
);
}
/// @notice Verifies the authorization status of a request
/// @dev This method has redundant arguments because all authorizer
/// contracts have to have the same interface and potential authorizer
/// contracts may require to access the arguments that are redundant here
/// @param requestId Request ID
/// @param airnode Airnode address
/// @param endpointId Endpoint ID
/// @param sponsor Sponsor address
/// @param requester Requester address
/// @return Authorization status of the request
function isAuthorized(
bytes32 requestId, // solhint-disable-line no-unused-vars
address airnode,
bytes32 endpointId,
address sponsor, // solhint-disable-line no-unused-vars
address requester
) external view override returns (bool) {
return requesterIsWhitelisted(airnode, endpointId, requester);
}
/// @notice Returns the whitelist status of `requester` for the
/// `airnode`–`endpointId` pair
/// @param airnode Airnode address
/// @param endpointId Endpoint ID
/// @param requester Requester address
/// @return expirationTimestamp Timestamp at which the temporary whitelist
/// will expire
/// @return indefiniteWhitelistCount Number of times `requester` was
/// whitelisted indefinitely for the `airnode`–`endpointId` pair
function airnodeToEndpointIdToRequesterToWhitelistStatus(
address airnode,
bytes32 endpointId,
address requester
)
external
view
override
returns (uint64 expirationTimestamp, uint192 indefiniteWhitelistCount)
{
WhitelistStatus
storage whitelistStatus = serviceIdToUserToWhitelistStatus[
deriveServiceId(airnode, endpointId)
][requester];
expirationTimestamp = whitelistStatus.expirationTimestamp;
indefiniteWhitelistCount = whitelistStatus.indefiniteWhitelistCount;
}
/// @notice Returns if an account has indefinitely whitelisted `requester`
/// for the `airnode`–`endpointId` pair
/// @param airnode Airnode address
/// @param endpointId Endpoint ID
/// @param requester Requester address
/// @param setter Address of the account that has potentially whitelisted
/// `requester` for the `airnode`–`endpointId` pair indefinitely
/// @return indefiniteWhitelistStatus If `setter` has indefinitely
/// whitelisted `requester` for the `airnode`–`endpointId` pair
function airnodeToEndpointIdToRequesterToSetterToIndefiniteWhitelistStatus(
address airnode,
bytes32 endpointId,
address requester,
address setter
) external view override returns (bool indefiniteWhitelistStatus) {
indefiniteWhitelistStatus = serviceIdToUserToSetterToIndefiniteWhitelistStatus[
deriveServiceId(airnode, endpointId)
][requester][setter];
}
/// @notice Called privately to derive a service ID out of the Airnode
/// address and the endpoint ID
/// @dev This is done to re-use the more general Whitelist contract for
/// the specific case of Airnode–endpoint pairs
/// @param airnode Airnode address
/// @param endpointId Endpoint ID
/// @return serviceId Service ID
function deriveServiceId(address airnode, bytes32 endpointId)
private
pure
returns (bytes32 serviceId)
{
serviceId = keccak256(abi.encodePacked(airnode, endpointId));
}
}
| @notice Sets the indefinite whitelist status of `requester` for the `airnode`–`endpointId` pair and emits an event @dev Emits the event even if it does not change the state. @param airnode Airnode address @param endpointId Endpoint ID @param requester Requester address @param status Indefinite whitelist status | function _setIndefiniteWhitelistStatusAndEmit(
address airnode,
bytes32 endpointId,
address requester,
bool status
) internal {
uint192 indefiniteWhitelistCount = _setIndefiniteWhitelistStatus(
deriveServiceId(airnode, endpointId),
requester,
status
);
emit SetIndefiniteWhitelistStatus(
airnode,
endpointId,
requester,
msg.sender,
status,
indefiniteWhitelistCount
);
}
| 6,445,686 | [
1,
2785,
326,
316,
5649,
1137,
10734,
1267,
434,
1375,
26192,
68,
364,
326,
1375,
1826,
2159,
68,
163,
227,
246,
68,
8003,
548,
68,
3082,
471,
24169,
392,
871,
225,
7377,
1282,
326,
871,
5456,
309,
518,
1552,
486,
2549,
326,
919,
18,
225,
23350,
2159,
432,
481,
2159,
1758,
225,
2494,
548,
6961,
1599,
225,
19961,
868,
21207,
1758,
225,
1267,
657,
5649,
1137,
10734,
1267,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
382,
5649,
1137,
18927,
1482,
1876,
17982,
12,
203,
3639,
1758,
23350,
2159,
16,
203,
3639,
1731,
1578,
2494,
548,
16,
203,
3639,
1758,
19961,
16,
203,
3639,
1426,
1267,
203,
565,
262,
2713,
288,
203,
3639,
2254,
15561,
316,
5649,
1137,
18927,
1380,
273,
389,
542,
382,
5649,
1137,
18927,
1482,
12,
203,
5411,
14763,
29177,
12,
1826,
2159,
16,
2494,
548,
3631,
203,
5411,
19961,
16,
203,
5411,
1267,
203,
3639,
11272,
203,
3639,
3626,
1000,
382,
5649,
1137,
18927,
1482,
12,
203,
5411,
23350,
2159,
16,
203,
5411,
2494,
548,
16,
203,
5411,
19961,
16,
203,
5411,
1234,
18,
15330,
16,
203,
5411,
1267,
16,
203,
5411,
316,
5649,
1137,
18927,
1380,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.6;
import "./MagnatBase.sol";
import "./tokens/erc20.sol";
import "./access/access-control.sol";
/**
* @dev This is a Resource contract for Magnat Game.
* Based on ERC-20 Token — Reference Implementation by OpenZeppelin
* (https://github.com/OpenZeppelin/openzeppelin-solidity/tree/master/contracts/token/ERC20)
*/
contract ERC20ContractExample is ERC20 {
// @dev Contract special states
address private mbAddr; //MagnatBase Contract Address short alias
//string private _name;
//string private _symbol;
uint public contractID; // This contract ID, saved in the MagnatBase Contract[] metadata
bool contractDeployed; // Check if contract deployed and connected to the MagnatBase Contract[]
address public contractAddr; // This contract address
uint8 public contractType; // Type of the contract (1-ERC20, 2-ERC721, 3-OTHER)
string public contractName; // This Contract name (for ERC721 - tokens collection name, for ERC20 - name for all tokens)
string public contractSymbol; // This contract symbol
string public contractShortDesc; // Short description of the contract
bool public contractOnPause; // Set contract on pause
bool public contractDeleted; // Deleted contract or not
string public contractDeletionReason; // Short description of the deletion reason
/************************************************************************************************/
/**************************************** CONSTRUCTOR *******************************************/
/************************************************************************************************/
// @dev Contract constructor
constructor(
address MagnatBaseAddr
) public {
/*********************** ENTER CONTRACT INFO HERE ********************************/
contractAddr = address(this);
contractType = 1;
contractName = 'MagnatGame-IronOre-Resource';
contractSymbol = "MGNT-IRON";
contractShortDesc = "THIS IS IRON OREEEEEE!";
contractOnPause = false;
contractDeleted = false;
contractDeletionReason = '';
/************************* END OF CONTRACT INFO ***********************************/
// @dev Saving aliases
_name = contractName;
_symbol = contractSymbol;
// @dev Checking requirements
require (MagnatBaseAddr != address(0));
// @dev Saving states
mbAddr = MagnatBaseAddr;
}
//address "0x5e3346444010135322268a4630d2ed5f8d09446c"
//name "LockTrip"
//decimals "18"
//symbol "LOC"
//totalSupply "18585932741500854062225000"
//owner ""
//lastUpdated 1528702164286
//issuancesCount 0
//holdersCount 36578
//image "https://ethplorer.io/images/loctrip.png"
//description "Hotel Booking & Vacation…ace With 0% Commissions"
//website "https://locktrip.com/"
//facebook "LockChainLOK"
//twitter "LockChainCo"
//reddit "LockChainCo"
//telegram "https://t.me/LockTrip"
//links "Subreddit: https://www.r…://github.com/LockTrip\n"
/************************************************************************************************/
/************************************** PUBLIC FUNCTIONS*****************************************/
/************************************************************************************************/
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mintResource(
address to,
uint256 value
)
public returns (bool)
{
require (checkCLevel());
_mint(to, value);
return true;
}
// @dev Check CLevel restrictions from MagnatBase
function checkCLevel() public view returns(bool) {
address _address = msg.sender;
return MagnatBase(mbAddr).checkCLevel(_address);
}
// @dev Check CEO restrictions from MagnatBase
function checkCEOLevel() public view returns(bool) {
address _address = msg.sender;
return MagnatBase(mbAddr).checkCEOLevel(_address);
}
// @dev whenNotPaused;
function checkNotPaused() public view returns(bool) {
return MagnatBase(mbAddr).checkNotPaused();
}
}
| @dev whenNotPaused; | function checkNotPaused() public view returns(bool) {
return MagnatBase(mbAddr).checkNotPaused();
}
| 13,087,777 | [
1,
13723,
1248,
28590,
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,
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,
866,
1248,
28590,
1435,
1071,
1476,
1135,
12,
6430,
13,
288,
203,
3639,
327,
12342,
18757,
2171,
12,
1627,
3178,
2934,
1893,
1248,
28590,
5621,
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
]
|
pragma solidity 0.5.17;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../../utils/BytesLib.sol";
/// @title Group Selection
/// @notice The group selection protocol is an interactive method of selecting
/// candidate group from the set of all stakers given a pseudorandom seed value.
///
/// The protocol produces a representative result, where each staker's profit is
/// proportional to the number of tokens they have staked. Produced candidate
/// groups are of constant size.
///
/// Group selection protocol accepts seed as an input - a pseudorandom value
/// used to construct candidate tickets. Each candidate group member can
/// submit their tickets. The maximum number of tickets one can submit depends
/// on their staking weight - relation of the minimum stake to the candidate's
/// stake.
///
/// There is a certain timeout, expressed in blocks, when tickets can be
/// submitted. Each ticket is a mix of staker's address, virtual staker index
/// and group selection seed. Candidate group members are selected based on
/// the best tickets submitted. There has to be a minimum number of tickets
/// submitted, equal to the candidate group size so that the protocol can
/// complete successfully.
library GroupSelection {
using SafeMath for uint256;
using BytesLib for bytes;
struct Storage {
// Tickets submitted by member candidates during the current group
// selection execution and accepted by the protocol for the
// consideration.
uint64[] tickets;
// Information about ticket submitters (group member candidates).
mapping(uint256 => address) candidate;
// Pseudorandom seed value used as an input for the group selection.
uint256 seed;
// Timeout in blocks after which the ticket submission is finished.
uint256 ticketSubmissionTimeout;
// Number of block at which the group selection started and from which
// ticket submissions are accepted.
uint256 ticketSubmissionStartBlock;
// Indicates whether a group selection is currently in progress.
// Concurrent group selections are not allowed.
bool inProgress;
// Captures the minimum stake when group selection starts. This is to ensure the
// same staking weight divisor is applied for all member candidates participating.
uint256 minimumStake;
// Map simulates a sorted linked list of ticket values by their indexes.
// key -> value represent indices from the tickets[] array.
// 'key' index holds an index of a ticket and 'value' holds an index
// of the next ticket. Tickets are sorted by their value in
// descending order starting from the tail.
// Ex. tickets = [151, 42, 175, 7]
// tail: 2 because tickets[2] = 175
// previousTicketIndex[0] -> 1
// previousTicketIndex[1] -> 3
// previousTicketIndex[2] -> 0
// previousTicketIndex[3] -> 3 note: index that holds a lowest
// value points to itself because there is no `nil` in Solidity.
// Traversing from tail: [2]->[0]->[1]->[3] result in 175->151->42->7
bytes previousTicketIndices;
// Tail represents an index of a ticket in a tickets[] array which holds
// the highest ticket value. It is a tail of the linked list defined by
// `previousTicketIndex`.
uint256 tail;
// Size of a group in the threshold relay.
uint256 groupSize;
}
/// @notice Starts group selection protocol.
/// @param _seed pseudorandom seed value used as an input for the group
/// selection. All submitted tickets needs to have the seed mixed-in into the
/// value.
function start(Storage storage self, uint256 _seed) public {
// We execute the minimum required cleanup here needed in case the
// previous group selection failed and did not clean up properly in
// finish function.
cleanupTickets(self);
self.inProgress = true;
self.seed = _seed;
self.ticketSubmissionStartBlock = block.number;
}
/// @notice Finishes group selection protocol clearing up all the submitted
/// tickets. This function may be expensive if not executed as a part of
/// another transaction consuming a lot of gas and as a result, getting
/// gas refund for clearing up the storage.
function finish(Storage storage self) public {
cleanupCandidates(self);
cleanupTickets(self);
self.inProgress = false;
}
/// @notice Submits ticket to request to participate in a new candidate group.
/// @param ticket Bytes representation of a ticket that holds the following:
/// - ticketValue: first 8 bytes of a result of keccak256 cryptography hash
/// function on the combination of the group selection seed (previous
/// beacon output), staker-specific value (address) and virtual staker index.
/// - stakerValue: a staker-specific value which is the address of the staker.
/// - virtualStakerIndex: 4-bytes number within a range of 1 to staker's weight;
/// has to be unique for all tickets submitted by the given staker for the
/// current candidate group selection.
/// @param stakingWeight Ratio of the minimum stake to the candidate's
/// stake.
function submitTicket(
Storage storage self,
bytes32 ticket,
uint256 stakingWeight
) public {
uint64 ticketValue;
uint160 stakerValue;
uint32 virtualStakerIndex;
bytes memory ticketBytes = abi.encodePacked(ticket);
/* solium-disable-next-line */
assembly {
// ticket value is 8 bytes long
ticketValue := mload(add(ticketBytes, 8))
// staker value is 20 bytes long
stakerValue := mload(add(ticketBytes, 28))
// virtual staker index is 4 bytes long
virtualStakerIndex := mload(add(ticketBytes, 32))
}
submitTicket(
self,
ticketValue,
uint256(stakerValue),
uint256(virtualStakerIndex),
stakingWeight
);
}
/// @notice Submits ticket to request to participate in a new candidate group.
/// @param ticketValue First 8 bytes of a result of keccak256 cryptography hash
/// function on the combination of the group selection seed (previous
/// beacon output), staker-specific value (address) and virtual staker index.
/// @param stakerValue Staker-specific value which is the address of the staker.
/// @param virtualStakerIndex 4-bytes number within a range of 1 to staker's weight;
/// has to be unique for all tickets submitted by the given staker for the
/// current candidate group selection.
/// @param stakingWeight Ratio of the minimum stake to the candidate's
/// stake.
function submitTicket(
Storage storage self,
uint64 ticketValue,
uint256 stakerValue,
uint256 virtualStakerIndex,
uint256 stakingWeight
) public {
if (block.number > self.ticketSubmissionStartBlock.add(self.ticketSubmissionTimeout)) {
revert("Ticket submission is over");
}
if (self.candidate[ticketValue] != address(0)) {
revert("Duplicate ticket");
}
if (isTicketValid(
ticketValue,
stakerValue,
virtualStakerIndex,
stakingWeight,
self.seed
)) {
addTicket(self, ticketValue);
} else {
revert("Invalid ticket");
}
}
/// @notice Performs full verification of the ticket.
function isTicketValid(
uint64 ticketValue,
uint256 stakerValue,
uint256 virtualStakerIndex,
uint256 stakingWeight,
uint256 groupSelectionSeed
) internal view returns(bool) {
uint64 ticketValueExpected;
bytes memory ticketBytes = abi.encodePacked(
keccak256(
abi.encodePacked(
groupSelectionSeed,
stakerValue,
virtualStakerIndex
)
)
);
// use first 8 bytes to compare ticket values
/* solium-disable-next-line */
assembly {
ticketValueExpected := mload(add(ticketBytes, 8))
}
bool isVirtualStakerIndexValid = virtualStakerIndex > 0 && virtualStakerIndex <= stakingWeight;
bool isStakerValueValid = stakerValue == uint256(msg.sender);
bool isTicketValueValid = ticketValue == ticketValueExpected;
return isVirtualStakerIndexValid && isStakerValueValid && isTicketValueValid;
}
/// @notice Adds a new, verified ticket. Ticket is accepted when it is lower
/// than the currently highest ticket or when the number of tickets is still
/// below the group size.
function addTicket(Storage storage self, uint64 newTicketValue) internal {
uint256[] memory previousTicketIndex = readPreviousTicketIndices(self);
uint256[] memory ordered = getTicketValueOrderedIndices(
self,
previousTicketIndex
);
// any ticket goes when the tickets array size is lower than the group size
if (self.tickets.length < self.groupSize) {
// no tickets
if (self.tickets.length == 0) {
self.tickets.push(newTicketValue);
// higher than the current highest
} else if (newTicketValue > self.tickets[self.tail]) {
self.tickets.push(newTicketValue);
uint256 oldTail = self.tail;
self.tail = self.tickets.length-1;
previousTicketIndex[self.tail] = oldTail;
// lower than the current lowest
} else if (newTicketValue < self.tickets[ordered[0]]) {
self.tickets.push(newTicketValue);
// last element points to itself
previousTicketIndex[self.tickets.length - 1] = self.tickets.length - 1;
// previous lowest ticket points to the new lowest
previousTicketIndex[ordered[0]] = self.tickets.length - 1;
// higher than the lowest ticket value and lower than the highest ticket value
} else {
self.tickets.push(newTicketValue);
uint256 j = findReplacementIndex(self, newTicketValue, ordered);
previousTicketIndex[self.tickets.length - 1] = previousTicketIndex[j];
previousTicketIndex[j] = self.tickets.length - 1;
}
self.candidate[newTicketValue] = msg.sender;
} else if (newTicketValue < self.tickets[self.tail]) {
uint256 ticketToRemove = self.tickets[self.tail];
// new ticket is lower than currently lowest
if (newTicketValue < self.tickets[ordered[0]]) {
// replacing highest ticket with the new lowest
self.tickets[self.tail] = newTicketValue;
uint256 newTail = previousTicketIndex[self.tail];
previousTicketIndex[ordered[0]] = self.tail;
previousTicketIndex[self.tail] = self.tail;
self.tail = newTail;
} else { // new ticket is between lowest and highest
uint256 j = findReplacementIndex(self, newTicketValue, ordered);
self.tickets[self.tail] = newTicketValue;
// do not change the order if a new ticket is still highest
if (j != self.tail) {
uint newTail = previousTicketIndex[self.tail];
previousTicketIndex[self.tail] = previousTicketIndex[j];
previousTicketIndex[j] = self.tail;
self.tail = newTail;
}
}
// we are replacing tickets so we also need to replace information
// about the submitter
delete self.candidate[ticketToRemove];
self.candidate[newTicketValue] = msg.sender;
}
storePreviousTicketIndices(self, previousTicketIndex);
}
/// @notice Use binary search to find an index for a new ticket in the tickets[] array
function findReplacementIndex(
Storage storage self,
uint64 newTicketValue,
uint256[] memory ordered
) internal view returns (uint256) {
uint256 lo = 0;
uint256 hi = ordered.length - 1;
uint256 mid = 0;
while (lo <= hi) {
mid = (lo + hi) >> 1;
if (newTicketValue < self.tickets[ordered[mid]]) {
hi = mid - 1;
} else if (newTicketValue > self.tickets[ordered[mid]]) {
lo = mid + 1;
} else {
return ordered[mid];
}
}
return ordered[lo];
}
function readPreviousTicketIndices(Storage storage self)
internal view returns (uint256[] memory uncompressed)
{
bytes memory compressed = self.previousTicketIndices;
uncompressed = new uint256[](self.groupSize);
for (uint256 i = 0; i < compressed.length; i++) {
uncompressed[i] = uint256(uint8(compressed[i]));
}
}
function storePreviousTicketIndices(
Storage storage self,
uint256[] memory uncompressed
) internal {
bytes memory compressed = new bytes(uncompressed.length);
for (uint256 i = 0; i < compressed.length; i++) {
compressed[i] = bytes1(uint8(uncompressed[i]));
}
self.previousTicketIndices = compressed;
}
/// @notice Creates an array of ticket indexes based on their values in the
/// ascending order:
///
/// ordered[n-1] = tail
/// ordered[n-2] = previousTicketIndex[tail]
/// ordered[n-3] = previousTicketIndex[ordered[n-2]]
function getTicketValueOrderedIndices(
Storage storage self,
uint256[] memory previousIndices
) internal view returns (uint256[] memory) {
uint256[] memory ordered = new uint256[](self.tickets.length);
if (ordered.length > 0) {
ordered[self.tickets.length-1] = self.tail;
if (ordered.length > 1) {
for (uint256 i = self.tickets.length - 1; i > 0; i--) {
ordered[i-1] = previousIndices[ordered[i]];
}
}
}
return ordered;
}
/// @notice Gets selected participants in ascending order of their tickets.
function selectedParticipants(Storage storage self) public view returns (address[] memory) {
require(
block.number >= self.ticketSubmissionStartBlock.add(self.ticketSubmissionTimeout),
"Ticket submission in progress"
);
require(self.tickets.length >= self.groupSize, "Not enough tickets submitted");
uint256[] memory previousTicketIndex = readPreviousTicketIndices(self);
address[] memory selected = new address[](self.groupSize);
uint256 ticketIndex = self.tail;
selected[self.tickets.length - 1] = self.candidate[self.tickets[ticketIndex]];
for (uint256 i = self.tickets.length - 1; i > 0; i--) {
ticketIndex = previousTicketIndex[ticketIndex];
selected[i-1] = self.candidate[self.tickets[ticketIndex]];
}
return selected;
}
/// @notice Clears up data of the group selection tickets.
function cleanupTickets(Storage storage self) internal {
delete self.tickets;
self.tail = 0;
}
/// @notice Clears up data of the group selection candidates.
/// This operation may have a significant cost if not executed as a part of
/// another transaction consuming a lot of gas and as a result, getting
/// gas refund for clearing up the storage.
function cleanupCandidates(Storage storage self) internal {
for (uint i = 0; i < self.tickets.length; i++) {
delete self.candidate[self.tickets[i]];
}
}
}
| @notice Adds a new, verified ticket. Ticket is accepted when it is lower than the currently highest ticket or when the number of tickets is still below the group size. any ticket goes when the tickets array size is lower than the group size no tickets higher than the current highest lower than the current lowest last element points to itself previous lowest ticket points to the new lowest higher than the lowest ticket value and lower than the highest ticket value new ticket is lower than currently lowest replacing highest ticket with the new lowest do not change the order if a new ticket is still highest | function addTicket(Storage storage self, uint64 newTicketValue) internal {
uint256[] memory previousTicketIndex = readPreviousTicketIndices(self);
uint256[] memory ordered = getTicketValueOrderedIndices(
self,
previousTicketIndex
);
if (self.tickets.length < self.groupSize) {
if (self.tickets.length == 0) {
self.tickets.push(newTicketValue);
self.tickets.push(newTicketValue);
uint256 oldTail = self.tail;
self.tail = self.tickets.length-1;
previousTicketIndex[self.tail] = oldTail;
self.tickets.push(newTicketValue);
previousTicketIndex[self.tickets.length - 1] = self.tickets.length - 1;
previousTicketIndex[ordered[0]] = self.tickets.length - 1;
self.tickets.push(newTicketValue);
uint256 j = findReplacementIndex(self, newTicketValue, ordered);
previousTicketIndex[self.tickets.length - 1] = previousTicketIndex[j];
previousTicketIndex[j] = self.tickets.length - 1;
}
self.candidate[newTicketValue] = msg.sender;
uint256 ticketToRemove = self.tickets[self.tail];
if (newTicketValue < self.tickets[ordered[0]]) {
self.tickets[self.tail] = newTicketValue;
uint256 newTail = previousTicketIndex[self.tail];
previousTicketIndex[ordered[0]] = self.tail;
previousTicketIndex[self.tail] = self.tail;
self.tail = newTail;
uint256 j = findReplacementIndex(self, newTicketValue, ordered);
self.tickets[self.tail] = newTicketValue;
if (j != self.tail) {
uint newTail = previousTicketIndex[self.tail];
previousTicketIndex[self.tail] = previousTicketIndex[j];
previousTicketIndex[j] = self.tail;
self.tail = newTail;
}
}
self.candidate[newTicketValue] = msg.sender;
}
storePreviousTicketIndices(self, previousTicketIndex);
}
| 7,324,564 | [
1,
3655,
279,
394,
16,
13808,
9322,
18,
22023,
353,
8494,
1347,
518,
353,
2612,
2353,
326,
4551,
9742,
9322,
578,
1347,
326,
1300,
434,
24475,
353,
4859,
5712,
326,
1041,
963,
18,
1281,
9322,
13998,
1347,
326,
24475,
526,
963,
353,
2612,
2353,
326,
1041,
963,
1158,
24475,
10478,
2353,
326,
783,
9742,
2612,
2353,
326,
783,
11981,
1142,
930,
3143,
358,
6174,
2416,
11981,
9322,
3143,
358,
326,
394,
11981,
10478,
2353,
326,
11981,
9322,
460,
471,
2612,
2353,
326,
9742,
9322,
460,
394,
9322,
353,
2612,
2353,
4551,
11981,
13993,
9742,
9322,
598,
326,
394,
11981,
741,
486,
2549,
326,
1353,
309,
279,
394,
9322,
353,
4859,
9742,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
13614,
12,
3245,
2502,
365,
16,
2254,
1105,
394,
13614,
620,
13,
2713,
288,
203,
3639,
2254,
5034,
8526,
3778,
2416,
13614,
1016,
273,
855,
8351,
13614,
8776,
12,
2890,
1769,
203,
3639,
2254,
5034,
8526,
3778,
5901,
273,
3181,
29378,
620,
16756,
8776,
12,
203,
5411,
365,
16,
203,
5411,
2416,
13614,
1016,
203,
3639,
11272,
203,
203,
3639,
309,
261,
2890,
18,
6470,
2413,
18,
2469,
411,
365,
18,
1655,
1225,
13,
288,
203,
5411,
309,
261,
2890,
18,
6470,
2413,
18,
2469,
422,
374,
13,
288,
203,
7734,
365,
18,
6470,
2413,
18,
6206,
12,
2704,
13614,
620,
1769,
203,
7734,
365,
18,
6470,
2413,
18,
6206,
12,
2704,
13614,
620,
1769,
203,
7734,
2254,
5034,
1592,
12363,
273,
365,
18,
13101,
31,
203,
7734,
365,
18,
13101,
273,
365,
18,
6470,
2413,
18,
2469,
17,
21,
31,
203,
7734,
2416,
13614,
1016,
63,
2890,
18,
13101,
65,
273,
1592,
12363,
31,
203,
7734,
365,
18,
6470,
2413,
18,
6206,
12,
2704,
13614,
620,
1769,
203,
7734,
2416,
13614,
1016,
63,
2890,
18,
6470,
2413,
18,
2469,
300,
404,
65,
273,
365,
18,
6470,
2413,
18,
2469,
300,
404,
31,
203,
7734,
2416,
13614,
1016,
63,
9885,
63,
20,
13563,
273,
365,
18,
6470,
2413,
18,
2469,
300,
404,
31,
203,
7734,
365,
18,
6470,
2413,
18,
6206,
12,
2704,
13614,
620,
1769,
203,
7734,
2254,
5034,
525,
273,
1104,
15201,
1016,
12,
2890,
16,
394,
13614,
620,
16,
5901,
1769,
203,
7734,
2416,
13614,
1016,
63,
2890,
2
]
|
// SPDX-License-Identifier: MIT
/*
MIT License
Copyright (c) 2018 requestnetwork
Copyright (c) 2018 Fragments, Inc.
Copyright (c) 2020 Ditto Money
Copyright (c) 2021 Goes Up Higher
Copyright (c) 2021 Cryptographic Ultra Money
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
pragma solidity ^0.6.0;
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;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
interface ILP {
function sync() external;
}
abstract contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
/**
* @title SafeMathInt
* @dev Math operations for int256 with overflow safety checks.
*/
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b)
internal
pure
returns (int256)
{
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a)
internal
pure
returns (int256)
{
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
}
/**
* @title 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;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
_owner = msg.sender;
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(_owner);
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function getUnlockTime() public view returns (uint256) {return _lockTime;}
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = block.timestamp + time;
emit OwnershipTransferred(_owner, address(0));
}
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(block.timestamp > _lockTime , "Contract is locked");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline
) external;
}
/**
* @title CUM ERC20 token
* @dev
* The goal of CUM is to be hardest money.
* Based on the Ampleforth protocol.
*/
contract CUM is Context, ERC20Detailed, Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
mapping (address => bool) private _isExcludedFromFee;
address BURN_ADDRESS = 0x0000000000000000000000000000000000000001;
address public liq_locker;
uint256 public _liquidityFee = 4;
uint256 private _previousLiquidityFee = _liquidityFee;
uint256 public _burnFee = 2;
uint256 private _previousBurnFee = _burnFee;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 public numTokensSellToAddToLiquidity = 66666 * 10**2 * 10**DECIMALS;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SetLPEvent(address lpAddress);
event SetLLEvent(address llAddress);
event AddressExcluded(address exAddress);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
event LogRebase(uint256 indexed epoch, uint256 totalSupply);
// Used for authentication
address public master;
// LP atomic sync
address public lp;
ILP public lpContract;
modifier onlyMaster() {
require(msg.sender == master);
_;
}
// Only the owner can transfer tokens in the initial phase.
// This is allow the AMM listing to happen in an orderly fashion.
bool public initialDistributionFinished;
mapping (address => bool) allowTransfer;
modifier initialDistributionLock {
require(initialDistributionFinished || isOwner() || allowTransfer[msg.sender]);
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
uint256 private constant DECIMALS = 9;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 66666 * 10**6 * 10**DECIMALS;
// TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer.
// Use the highest value that fits in a uint256 for max granularity.
uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY);
// MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _totalSupply;
uint256 private _gonsPerFragment;
mapping(address => uint256) private _gonBalances;
// This is denominated in Fragments, because the gons-fragments conversion might change before
// it's fully paid.
mapping (address => mapping (address => uint256)) private _allowedFragments;
/**
* @dev Notifies Fragments contract about a new rebase cycle.
* @param supplyDelta The number of new fragment tokens to add into circulation via expansion.
* @return The total number of fragments after the supply adjustment.
*/
function rebase(uint256 epoch, int256 supplyDelta)
external
onlyMaster
returns (uint256)
{
if (supplyDelta == 0) {
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
if (supplyDelta < 0) {
_totalSupply = _totalSupply.sub(uint256(-supplyDelta));
} else {
_totalSupply = _totalSupply.add(uint256(supplyDelta));
}
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
numTokensSellToAddToLiquidity = _totalSupply.div(10000);
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
lpContract.sync();
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
constructor()
ERC20Detailed("Cryptographic Ultra Money", "CUM", uint8(DECIMALS))
public
{
_totalSupply = INITIAL_FRAGMENTS_SUPPLY;
_gonBalances[msg.sender] = TOTAL_GONS;
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[BURN_ADDRESS] = true;
initialDistributionFinished = false;
emit Transfer(address(0x0), msg.sender, _totalSupply);
}
/**
* @notice Sets a new master
*/
function setMaster(address masterAddress)
external
onlyOwner
returns (uint256)
{
master = masterAddress;
}
/**
* @notice Sets contract LP address
*/
function setLP(address lpAddress)
external
onlyOwner
returns (uint256)
{
lp = lpAddress;
lpContract = ILP(lp);
emit SetLPEvent(lp);
}
/**
* @notice Sets Liquidity Locker address
*/
function setLiqLocker(address llAddress)
external
onlyOwner
returns (uint256)
{
liq_locker = llAddress;
_isExcludedFromFee[liq_locker] = true;
emit SetLLEvent(liq_locker);
}
/**
* @notice Adds excluded address
*/
function excludeFromFeeAdd(address exAddress)
external
onlyOwner
returns (uint256)
{
_isExcludedFromFee[exAddress] = true;
emit AddressExcluded(exAddress);
}
function excludeFromFeeRemove(address exAddress)
external
onlyOwner
returns (uint256)
{
_isExcludedFromFee[exAddress] = false;
}
/**
* @return The total number of fragments.
*/
function totalSupply()
public
view
override
returns (uint256)
{
return _totalSupply;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
public
view
override
returns (uint256)
{
return _gonBalances[who].div(_gonsPerFragment);
}
function _approve(address owner, address spender, uint256 value) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowedFragments[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
public
validRecipient(to)
initialDistributionLock
override
returns (bool)
{
_transfer(_msgSender(), to, value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
public
view
override
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Transfer tokens from one address to another.
* @param sender The address you want to send tokens from.
* @param recipient The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address sender, address recipient, uint256 value)
public
validRecipient(recipient)
override
returns (bool)
{
_transfer(sender, recipient, value);
_approve(sender, _msgSender(), _allowedFragments[sender][_msgSender()].sub(value));
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
public
initialDistributionLock
override
returns (bool)
{
_allowedFragments[_msgSender()][spender] = value;
emit Approval(_msgSender(), spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
initialDistributionLock
returns (bool)
{
_allowedFragments[_msgSender()][spender] = _allowedFragments[_msgSender()][spender].add(addedValue);
emit Approval(_msgSender(), spender, _allowedFragments[_msgSender()][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
initialDistributionLock
returns (bool)
{
uint256 oldValue = _allowedFragments[_msgSender()][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[_msgSender()][spender] = 0;
} else {
_allowedFragments[_msgSender()][spender] = oldValue.sub(subtractedValue);
}
emit Approval(_msgSender(), spender, _allowedFragments[_msgSender()][spender]);
return true;
}
function setInitialDistributionFinished()
external
onlyOwner
{
initialDistributionFinished = true;
}
function enableTransfer(address _addr)
external
onlyOwner
{
allowTransfer[_addr] = true;
}
function removeAllFee() private {
if(_burnFee == 0 && _liquidityFee == 0) return;
_previousBurnFee = _burnFee;
_previousLiquidityFee = _liquidityFee;
_burnFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_burnFee = _previousBurnFee;
_liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
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");
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
swapAndLiquify(contractTokenBalance);
}
bool takeFee = true;
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
_tokenTransfer(from, to, amount, takeFee);
}
function setBurnFeePercent(uint256 burnFee) external onlyOwner() {
require(burnFee <= 10);
_burnFee = burnFee;
}
function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() {
require(liquidityFee <= 10);
_liquidityFee = liquidityFee;
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
receive() external payable {}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
// split the contract balance into halves
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
liq_locker,
block.timestamp
);
}
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if(!takeFee)
removeAllFee();
_transferStandard(sender, recipient, amount);
if(!takeFee)
restoreAllFee();
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10**2
);
}
function calculateBurnFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_burnFee).div(
10**2
);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tBurn = calculateBurnFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tBurn).sub(tLiquidity);
return (tTransferAmount, tBurn, tLiquidity);
}
function _transferBurn(uint256 tBurn) private {
_gonBalances[BURN_ADDRESS] = _gonBalances[BURN_ADDRESS].add(tBurn);
}
function _takeLiquidity(uint256 tLiquidity) private {
_gonBalances[address(this)] = _gonBalances[address(this)].add(tLiquidity);
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
uint256 gonValue = tAmount.mul(_gonsPerFragment);
(uint256 tTransferAmount, uint256 tBurn, uint256 tLiquidity) = _getTValues(gonValue);
_gonBalances[sender] = _gonBalances[sender].sub(gonValue);
_gonBalances[recipient] = _gonBalances[recipient].add(tTransferAmount);
_transferBurn(tBurn);
_takeLiquidity(tLiquidity);
emit Transfer(sender, BURN_ADDRESS, tBurn.div(_gonsPerFragment));
emit Transfer(sender, address(this), tLiquidity.div(_gonsPerFragment));
emit Transfer(sender, recipient, tTransferAmount.div(_gonsPerFragment));
}
} | * @dev Decrease the amount of tokens that an owner has allowed to a spender. @param spender The address which will spend the funds. @param subtractedValue The amount of tokens to decrease the allowance by./ | function decreaseAllowance(address spender, uint256 subtractedValue)
external
initialDistributionLock
returns (bool)
{
uint256 oldValue = _allowedFragments[_msgSender()][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[_msgSender()][spender] = 0;
_allowedFragments[_msgSender()][spender] = oldValue.sub(subtractedValue);
}
emit Approval(_msgSender(), spender, _allowedFragments[_msgSender()][spender]);
return true;
}
| 257,467 | [
1,
23326,
448,
326,
3844,
434,
2430,
716,
392,
3410,
711,
2935,
358,
279,
17571,
264,
18,
225,
17571,
264,
1021,
1758,
1492,
903,
17571,
326,
284,
19156,
18,
225,
10418,
329,
620,
1021,
3844,
434,
2430,
358,
20467,
326,
1699,
1359,
635,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
20467,
7009,
1359,
12,
2867,
17571,
264,
16,
2254,
5034,
10418,
329,
620,
13,
203,
3639,
3903,
203,
3639,
2172,
9003,
2531,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
2254,
5034,
11144,
273,
389,
8151,
27588,
63,
67,
3576,
12021,
1435,
6362,
87,
1302,
264,
15533,
203,
3639,
309,
261,
1717,
1575,
329,
620,
1545,
11144,
13,
288,
203,
5411,
389,
8151,
27588,
63,
67,
3576,
12021,
1435,
6362,
87,
1302,
264,
65,
273,
374,
31,
203,
5411,
389,
8151,
27588,
63,
67,
3576,
12021,
1435,
6362,
87,
1302,
264,
65,
273,
11144,
18,
1717,
12,
1717,
1575,
329,
620,
1769,
203,
3639,
289,
203,
3639,
3626,
1716,
685,
1125,
24899,
3576,
12021,
9334,
17571,
264,
16,
389,
8151,
27588,
63,
67,
3576,
12021,
1435,
6362,
87,
1302,
264,
19226,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xE672E0E0101A7F58d728751E2a5e6Da5Ff1FDa64/sources/Users/petr/ankr/aws-smart-contracts/legacy/contracts/upgrades/AETH_R21.sol | new ratio should be in the range [oldRatio - threshold , oldRatio] | uint256 threshold = oldRatio.mul(_RATIO_THRESHOLD).div(MAX_THRESHOLD);
| 2,644,777 | [
1,
2704,
7169,
1410,
506,
316,
326,
1048,
306,
1673,
8541,
300,
5573,
269,
1592,
8541,
65,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2254,
5034,
5573,
273,
1592,
8541,
18,
16411,
24899,
54,
789,
4294,
67,
23840,
2934,
2892,
12,
6694,
67,
23840,
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
]
|
/**
Source code of Opium Protocol
Web https://opium.network
Telegram https://t.me/opium_network
Twitter https://twitter.com/opium_network
*/
// File: LICENSE
/**
The software and documentation available in this repository (the "Software") is protected by copyright law and accessible pursuant to the license set forth below. Copyright © 2020 Blockeys BV. All rights reserved.
Permission is hereby granted, free of charge, to any person or organization obtaining the Software (the “Licensee”) to privately study, review, and analyze the Software. Licensee shall not use the Software for any other purpose. Licensee shall not modify, transfer, assign, share, or sub-license the Software or any derivative works of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// File: contracts/Lib/LibDerivative.sol
pragma solidity 0.5.16;
pragma experimental ABIEncoderV2;
/// @title Opium.Lib.LibDerivative contract should be inherited by contracts that use Derivative structure and calculate derivativeHash
contract LibDerivative {
// Opium derivative structure (ticker) definition
struct Derivative {
// Margin parameter for syntheticId
uint256 margin;
// Maturity of derivative
uint256 endTime;
// Additional parameters for syntheticId
uint256[] params;
// oracleId of derivative
address oracleId;
// Margin token address of derivative
address token;
// syntheticId of derivative
address syntheticId;
}
/// @notice Calculates hash of provided Derivative
/// @param _derivative Derivative Instance of derivative to hash
/// @return derivativeHash bytes32 Derivative hash
function getDerivativeHash(Derivative memory _derivative) public pure returns (bytes32 derivativeHash) {
derivativeHash = keccak256(abi.encodePacked(
_derivative.margin,
_derivative.endTime,
_derivative.params,
_derivative.oracleId,
_derivative.token,
_derivative.syntheticId
));
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* IMPORTANT: It is unsafe to assume that an address for which this
* function returns false is an externally-owned account (EOA) and not a
* contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*/
contract ReentrancyGuard {
// counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
// File: erc721o/contracts/Libs/LibPosition.sol
pragma solidity ^0.5.4;
library LibPosition {
function getLongTokenId(bytes32 _hash) public pure returns (uint256 tokenId) {
tokenId = uint256(keccak256(abi.encodePacked(_hash, "LONG")));
}
function getShortTokenId(bytes32 _hash) public pure returns (uint256 tokenId) {
tokenId = uint256(keccak256(abi.encodePacked(_hash, "SHORT")));
}
}
// File: contracts/Interface/IDerivativeLogic.sol
pragma solidity 0.5.16;
/// @title Opium.Interface.IDerivativeLogic contract is an interface that every syntheticId should implement
contract IDerivativeLogic is LibDerivative {
/// @notice Validates ticker
/// @param _derivative Derivative Instance of derivative to validate
/// @return Returns boolean whether ticker is valid
function validateInput(Derivative memory _derivative) public view returns (bool);
/// @notice Calculates margin required for derivative creation
/// @param _derivative Derivative Instance of derivative
/// @return buyerMargin uint256 Margin needed from buyer (LONG position)
/// @return sellerMargin uint256 Margin needed from seller (SHORT position)
function getMargin(Derivative memory _derivative) public view returns (uint256 buyerMargin, uint256 sellerMargin);
/// @notice Calculates payout for derivative execution
/// @param _derivative Derivative Instance of derivative
/// @param _result uint256 Data retrieved from oracleId on the maturity
/// @return buyerPayout uint256 Payout in ratio for buyer (LONG position holder)
/// @return sellerPayout uint256 Payout in ratio for seller (SHORT position holder)
function getExecutionPayout(Derivative memory _derivative, uint256 _result) public view returns (uint256 buyerPayout, uint256 sellerPayout);
/// @notice Returns syntheticId author address for Opium commissions
/// @return authorAddress address The address of syntheticId address
function getAuthorAddress() public view returns (address authorAddress);
/// @notice Returns syntheticId author commission in base of COMMISSION_BASE
/// @return commission uint256 Author commission
function getAuthorCommission() public view returns (uint256 commission);
/// @notice Returns whether thirdparty could execute on derivative's owner's behalf
/// @param _derivativeOwner address Derivative owner address
/// @return Returns boolean whether _derivativeOwner allowed third party execution
function thirdpartyExecutionAllowed(address _derivativeOwner) public view returns (bool);
/// @notice Returns whether syntheticId implements pool logic
/// @return Returns whether syntheticId implements pool logic
function isPool() public view returns (bool);
/// @notice Sets whether thirds parties are allowed or not to execute derivative's on msg.sender's behalf
/// @param _allow bool Flag for execution allowance
function allowThirdpartyExecution(bool _allow) public;
// Event with syntheticId metadata JSON string (for DIB.ONE derivative explorer)
event MetadataSet(string metadata);
}
// File: contracts/Errors/CoreErrors.sol
pragma solidity 0.5.16;
contract CoreErrors {
string constant internal ERROR_CORE_NOT_POOL = "CORE:NOT_POOL";
string constant internal ERROR_CORE_CANT_BE_POOL = "CORE:CANT_BE_POOL";
string constant internal ERROR_CORE_TICKER_WAS_CANCELLED = "CORE:TICKER_WAS_CANCELLED";
string constant internal ERROR_CORE_SYNTHETIC_VALIDATION_ERROR = "CORE:SYNTHETIC_VALIDATION_ERROR";
string constant internal ERROR_CORE_NOT_ENOUGH_TOKEN_ALLOWANCE = "CORE:NOT_ENOUGH_TOKEN_ALLOWANCE";
string constant internal ERROR_CORE_TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH = "CORE:TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH";
string constant internal ERROR_CORE_TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH = "CORE:TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH";
string constant internal ERROR_CORE_EXECUTION_BEFORE_MATURITY_NOT_ALLOWED = "CORE:EXECUTION_BEFORE_MATURITY_NOT_ALLOWED";
string constant internal ERROR_CORE_SYNTHETIC_EXECUTION_WAS_NOT_ALLOWED = "CORE:SYNTHETIC_EXECUTION_WAS_NOT_ALLOWED";
string constant internal ERROR_CORE_INSUFFICIENT_POOL_BALANCE = "CORE:INSUFFICIENT_POOL_BALANCE";
string constant internal ERROR_CORE_CANT_CANCEL_DUMMY_ORACLE_ID = "CORE:CANT_CANCEL_DUMMY_ORACLE_ID";
string constant internal ERROR_CORE_CANCELLATION_IS_NOT_ALLOWED = "CORE:CANCELLATION_IS_NOT_ALLOWED";
string constant internal ERROR_CORE_UNKNOWN_POSITION_TYPE = "CORE:UNKNOWN_POSITION_TYPE";
}
// File: contracts/Errors/RegistryErrors.sol
pragma solidity 0.5.16;
contract RegistryErrors {
string constant internal ERROR_REGISTRY_ONLY_INITIALIZER = "REGISTRY:ONLY_INITIALIZER";
string constant internal ERROR_REGISTRY_ONLY_OPIUM_ADDRESS_ALLOWED = "REGISTRY:ONLY_OPIUM_ADDRESS_ALLOWED";
string constant internal ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS = "REGISTRY:CANT_BE_ZERO_ADDRESS";
string constant internal ERROR_REGISTRY_ALREADY_SET = "REGISTRY:ALREADY_SET";
}
// File: contracts/Registry.sol
pragma solidity 0.5.16;
/// @title Opium.Registry contract keeps addresses of deployed Opium contracts set to allow them route and communicate to each other
contract Registry is RegistryErrors {
// Address of Opium.TokenMinter contract
address private minter;
// Address of Opium.Core contract
address private core;
// Address of Opium.OracleAggregator contract
address private oracleAggregator;
// Address of Opium.SyntheticAggregator contract
address private syntheticAggregator;
// Address of Opium.TokenSpender contract
address private tokenSpender;
// Address of Opium commission receiver
address private opiumAddress;
// Address of Opium contract set deployer
address public initializer;
/// @notice This modifier restricts access to functions, which could be called only by initializer
modifier onlyInitializer() {
require(msg.sender == initializer, ERROR_REGISTRY_ONLY_INITIALIZER);
_;
}
/// @notice Sets initializer
constructor() public {
initializer = msg.sender;
}
// SETTERS
/// @notice Sets Opium.TokenMinter, Opium.Core, Opium.OracleAggregator, Opium.SyntheticAggregator, Opium.TokenSpender, Opium commission receiver addresses and allows to do it only once
/// @param _minter address Address of Opium.TokenMinter
/// @param _core address Address of Opium.Core
/// @param _oracleAggregator address Address of Opium.OracleAggregator
/// @param _syntheticAggregator address Address of Opium.SyntheticAggregator
/// @param _tokenSpender address Address of Opium.TokenSpender
/// @param _opiumAddress address Address of Opium commission receiver
function init(
address _minter,
address _core,
address _oracleAggregator,
address _syntheticAggregator,
address _tokenSpender,
address _opiumAddress
) external onlyInitializer {
require(
minter == address(0) &&
core == address(0) &&
oracleAggregator == address(0) &&
syntheticAggregator == address(0) &&
tokenSpender == address(0) &&
opiumAddress == address(0),
ERROR_REGISTRY_ALREADY_SET
);
require(
_minter != address(0) &&
_core != address(0) &&
_oracleAggregator != address(0) &&
_syntheticAggregator != address(0) &&
_tokenSpender != address(0) &&
_opiumAddress != address(0),
ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS
);
minter = _minter;
core = _core;
oracleAggregator = _oracleAggregator;
syntheticAggregator = _syntheticAggregator;
tokenSpender = _tokenSpender;
opiumAddress = _opiumAddress;
}
/// @notice Allows opium commission receiver address to change itself
/// @param _opiumAddress address New opium commission receiver address
function changeOpiumAddress(address _opiumAddress) external {
require(opiumAddress == msg.sender, ERROR_REGISTRY_ONLY_OPIUM_ADDRESS_ALLOWED);
require(_opiumAddress != address(0), ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS);
opiumAddress = _opiumAddress;
}
// GETTERS
/// @notice Returns address of Opium.TokenMinter
/// @param result address Address of Opium.TokenMinter
function getMinter() external view returns (address result) {
return minter;
}
/// @notice Returns address of Opium.Core
/// @param result address Address of Opium.Core
function getCore() external view returns (address result) {
return core;
}
/// @notice Returns address of Opium.OracleAggregator
/// @param result address Address of Opium.OracleAggregator
function getOracleAggregator() external view returns (address result) {
return oracleAggregator;
}
/// @notice Returns address of Opium.SyntheticAggregator
/// @param result address Address of Opium.SyntheticAggregator
function getSyntheticAggregator() external view returns (address result) {
return syntheticAggregator;
}
/// @notice Returns address of Opium.TokenSpender
/// @param result address Address of Opium.TokenSpender
function getTokenSpender() external view returns (address result) {
return tokenSpender;
}
/// @notice Returns address of Opium commission receiver
/// @param result address Address of Opium commission receiver
function getOpiumAddress() external view returns (address result) {
return opiumAddress;
}
}
// File: contracts/Errors/UsingRegistryErrors.sol
pragma solidity 0.5.16;
contract UsingRegistryErrors {
string constant internal ERROR_USING_REGISTRY_ONLY_CORE_ALLOWED = "USING_REGISTRY:ONLY_CORE_ALLOWED";
}
// File: contracts/Lib/UsingRegistry.sol
pragma solidity 0.5.16;
/// @title Opium.Lib.UsingRegistry contract should be inherited by contracts, that are going to use Opium.Registry
contract UsingRegistry is UsingRegistryErrors {
// Emitted when registry instance is set
event RegistrySet(address registry);
// Instance of Opium.Registry contract
Registry internal registry;
/// @notice This modifier restricts access to functions, which could be called only by Opium.Core
modifier onlyCore() {
require(msg.sender == registry.getCore(), ERROR_USING_REGISTRY_ONLY_CORE_ALLOWED);
_;
}
/// @notice Defines registry instance and emits appropriate event
constructor(address _registry) public {
registry = Registry(_registry);
emit RegistrySet(_registry);
}
/// @notice Getter for registry variable
/// @return address Address of registry set in current contract
function getRegistry() external view returns (address) {
return address(registry);
}
}
// File: contracts/Lib/LibCommission.sol
pragma solidity 0.5.16;
/// @title Opium.Lib.LibCommission contract defines constants for Opium commissions
contract LibCommission {
// Represents 100% base for commissions calculation
uint256 constant public COMMISSION_BASE = 10000;
// Represents 100% base for Opium commission
uint256 constant public OPIUM_COMMISSION_BASE = 10;
// Represents which part of `syntheticId` author commissions goes to opium
uint256 constant public OPIUM_COMMISSION_PART = 1;
}
// File: openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.5.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
// File: erc721o/contracts/Libs/UintArray.sol
pragma solidity ^0.5.4;
library UintArray {
function indexOf(uint256[] memory A, uint256 a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (0, false);
}
function contains(uint256[] memory A, uint256 a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
function difference(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory, uint256[] memory) {
uint256 length = A.length;
bool[] memory includeMap = new bool[](length);
uint256 count = 0;
// First count the new length because can't push for in-memory arrays
for (uint256 i = 0; i < length; i++) {
uint256 e = A[i];
if (!contains(B, e)) {
includeMap[i] = true;
count++;
}
}
uint256[] memory newUints = new uint256[](count);
uint256[] memory newUintsIdxs = new uint256[](count);
uint256 j = 0;
for (uint256 i = 0; i < length; i++) {
if (includeMap[i]) {
newUints[j] = A[i];
newUintsIdxs[j] = i;
j++;
}
}
return (newUints, newUintsIdxs);
}
function intersect(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory, uint256[] memory, uint256[] memory) {
uint256 length = A.length;
bool[] memory includeMap = new bool[](length);
uint256 newLength = 0;
for (uint256 i = 0; i < length; i++) {
if (contains(B, A[i])) {
includeMap[i] = true;
newLength++;
}
}
uint256[] memory newUints = new uint256[](newLength);
uint256[] memory newUintsAIdxs = new uint256[](newLength);
uint256[] memory newUintsBIdxs = new uint256[](newLength);
uint256 j = 0;
for (uint256 i = 0; i < length; i++) {
if (includeMap[i]) {
newUints[j] = A[i];
newUintsAIdxs[j] = i;
(newUintsBIdxs[j], ) = indexOf(B, A[i]);
j++;
}
}
return (newUints, newUintsAIdxs, newUintsBIdxs);
}
function isUnique(uint256[] memory A) internal pure returns (bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
(uint256 idx, bool isIn) = indexOf(A, A[i]);
if (isIn && idx < i) {
return false;
}
}
return true;
}
}
// File: openzeppelin-solidity/contracts/introspection/IERC165.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: openzeppelin-solidity/contracts/introspection/ERC165.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.5.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) public;
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
// File: erc721o/contracts/Interfaces/IERC721O.sol
pragma solidity ^0.5.4;
contract IERC721O {
// Token description
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function totalSupply() public view returns (uint256);
function exists(uint256 _tokenId) public view returns (bool);
function implementsERC721() public pure returns (bool);
function tokenByIndex(uint256 _index) public view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId);
function tokenURI(uint256 _tokenId) public view returns (string memory tokenUri);
function getApproved(uint256 _tokenId) public view returns (address);
function implementsERC721O() public pure returns (bool);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function balanceOf(address owner) public view returns (uint256);
function balanceOf(address _owner, uint256 _tokenId) public view returns (uint256);
function tokensOwned(address _owner) public view returns (uint256[] memory, uint256[] memory);
// Non-Fungible Safe Transfer From
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public;
// Non-Fungible Unsafe Transfer From
function transferFrom(address _from, address _to, uint256 _tokenId) public;
// Fungible Unsafe Transfer
function transfer(address _to, uint256 _tokenId, uint256 _quantity) public;
// Fungible Unsafe Transfer From
function transferFrom(address _from, address _to, uint256 _tokenId, uint256 _quantity) public;
// Fungible Safe Transfer From
function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount, bytes memory _data) public;
// Fungible Safe Batch Transfer From
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts) public;
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts, bytes memory _data) public;
// Fungible Unsafe Batch Transfer From
function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts) public;
// Approvals
function setApprovalForAll(address _operator, bool _approved) public;
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId, address _tokenOwner) public view returns (address);
function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator);
function isApprovedOrOwner(address _spender, address _owner, uint256 _tokenId) public view returns (bool);
function permit(address _holder, address _spender, uint256 _nonce, uint256 _expiry, bool _allowed, bytes calldata _signature) external;
// Composable
function compose(uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public;
function decompose(uint256 _portfolioId, uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public;
function recompose(uint256 _portfolioId, uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity) public;
// Required Events
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event TransferWithQuantity(address indexed from, address indexed to, uint256 indexed tokenId, uint256 quantity);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event BatchTransfer(address indexed from, address indexed to, uint256[] tokenTypes, uint256[] amounts);
event Composition(uint256 portfolioId, uint256[] tokenIds, uint256[] tokenRatio);
}
// File: erc721o/contracts/Interfaces/IERC721OReceiver.sol
pragma solidity ^0.5.4;
/**
* @title ERC721O token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721O contracts.
*/
contract IERC721OReceiver {
/**
* @dev Magic value to be returned upon successful reception of an amount of ERC721O tokens
* ERC721O_RECEIVED = `bytes4(keccak256("onERC721OReceived(address,address,uint256,uint256,bytes)"))` = 0xf891ffe0
* ERC721O_BATCH_RECEIVED = `bytes4(keccak256("onERC721OBatchReceived(address,address,uint256[],uint256[],bytes)"))` = 0xd0e17c0b
*/
bytes4 constant internal ERC721O_RECEIVED = 0xf891ffe0;
bytes4 constant internal ERC721O_BATCH_RECEIVED = 0xd0e17c0b;
function onERC721OReceived(
address _operator,
address _from,
uint256 tokenId,
uint256 amount,
bytes memory data
) public returns(bytes4);
function onERC721OBatchReceived(
address _operator,
address _from,
uint256[] memory _types,
uint256[] memory _amounts,
bytes memory _data
) public returns (bytes4);
}
// File: erc721o/contracts/Libs/ObjectsLib.sol
pragma solidity ^0.5.4;
library ObjectLib {
// Libraries
using SafeMath for uint256;
enum Operations { ADD, SUB, REPLACE }
// Constants regarding bin or chunk sizes for balance packing
uint256 constant TYPES_BITS_SIZE = 32; // Max size of each object
uint256 constant TYPES_PER_UINT256 = 256 / TYPES_BITS_SIZE; // Number of types per uint256
//
// Objects and Tokens Functions
//
/**
* @dev Return the bin number and index within that bin where ID is
* @param _tokenId Object type
* @return (Bin number, ID's index within that bin)
*/
function getTokenBinIndex(uint256 _tokenId) internal pure returns (uint256 bin, uint256 index) {
bin = _tokenId * TYPES_BITS_SIZE / 256;
index = _tokenId % TYPES_PER_UINT256;
return (bin, index);
}
/**
* @dev update the balance of a type provided in _binBalances
* @param _binBalances Uint256 containing the balances of objects
* @param _index Index of the object in the provided bin
* @param _amount Value to update the type balance
* @param _operation Which operation to conduct :
* Operations.REPLACE : Replace type balance with _amount
* Operations.ADD : ADD _amount to type balance
* Operations.SUB : Substract _amount from type balance
*/
function updateTokenBalance(
uint256 _binBalances,
uint256 _index,
uint256 _amount,
Operations _operation) internal pure returns (uint256 newBinBalance)
{
uint256 objectBalance;
if (_operation == Operations.ADD) {
objectBalance = getValueInBin(_binBalances, _index);
newBinBalance = writeValueInBin(_binBalances, _index, objectBalance.add(_amount));
} else if (_operation == Operations.SUB) {
objectBalance = getValueInBin(_binBalances, _index);
newBinBalance = writeValueInBin(_binBalances, _index, objectBalance.sub(_amount));
} else if (_operation == Operations.REPLACE) {
newBinBalance = writeValueInBin(_binBalances, _index, _amount);
} else {
revert("Invalid operation"); // Bad operation
}
return newBinBalance;
}
/*
* @dev return value in _binValue at position _index
* @param _binValue uint256 containing the balances of TYPES_PER_UINT256 types
* @param _index index at which to retrieve value
* @return Value at given _index in _bin
*/
function getValueInBin(uint256 _binValue, uint256 _index) internal pure returns (uint256) {
// Mask to retrieve data for a given binData
uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1;
// Shift amount
uint256 rightShift = 256 - TYPES_BITS_SIZE * (_index + 1);
return (_binValue >> rightShift) & mask;
}
/**
* @dev return the updated _binValue after writing _amount at _index
* @param _binValue uint256 containing the balances of TYPES_PER_UINT256 types
* @param _index Index at which to retrieve value
* @param _amount Value to store at _index in _bin
* @return Value at given _index in _bin
*/
function writeValueInBin(uint256 _binValue, uint256 _index, uint256 _amount) internal pure returns (uint256) {
require(_amount < 2**TYPES_BITS_SIZE, "Amount to write in bin is too large");
// Mask to retrieve data for a given binData
uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1;
// Shift amount
uint256 leftShift = 256 - TYPES_BITS_SIZE * (_index + 1);
return (_binValue & ~(mask << leftShift) ) | (_amount << leftShift);
}
}
// File: erc721o/contracts/ERC721OBase.sol
pragma solidity ^0.5.4;
contract ERC721OBase is IERC721O, ERC165, IERC721 {
// Libraries
using ObjectLib for ObjectLib.Operations;
using ObjectLib for uint256;
// Array with all tokenIds
uint256[] internal allTokens;
// Packed balances
mapping(address => mapping(uint256 => uint256)) internal packedTokenBalance;
// Operators
mapping(address => mapping(address => bool)) internal operators;
// Keeps aprovals for tokens from owner to approved address
// tokenApprovals[tokenId][owner] = approved
mapping (uint256 => mapping (address => address)) internal tokenApprovals;
// Token Id state
mapping(uint256 => uint256) internal tokenTypes;
uint256 constant internal INVALID = 0;
uint256 constant internal POSITION = 1;
uint256 constant internal PORTFOLIO = 2;
// Interface constants
bytes4 internal constant INTERFACE_ID_ERC721O = 0x12345678;
// EIP712 constants
bytes32 public DOMAIN_SEPARATOR;
bytes32 public PERMIT_TYPEHASH;
// mapping holds nonces for approval permissions
// nonces[holder] => nonce
mapping (address => uint) public nonces;
modifier isOperatorOrOwner(address _from) {
require((msg.sender == _from) || operators[_from][msg.sender], "msg.sender is neither _from nor operator");
_;
}
constructor() public {
_registerInterface(INTERFACE_ID_ERC721O);
// Calculate EIP712 constants
DOMAIN_SEPARATOR = keccak256(abi.encode(
keccak256("EIP712Domain(string name,string version,address verifyingContract)"),
keccak256(bytes("ERC721o")),
keccak256(bytes("1")),
address(this)
));
PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)");
}
function implementsERC721O() public pure returns (bool) {
return true;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
return tokenTypes[_tokenId] != INVALID;
}
/**
* @dev return the _tokenId type' balance of _address
* @param _address Address to query balance of
* @param _tokenId type to query balance of
* @return Amount of objects of a given type ID
*/
function balanceOf(address _address, uint256 _tokenId) public view returns (uint256) {
(uint256 bin, uint256 index) = _tokenId.getTokenBinIndex();
return packedTokenBalance[_address][bin].getValueInBin(index);
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets Iterate through the list of existing tokens and return the indexes
* and balances of the tokens owner by the user
* @param _owner The adddress we are checking
* @return indexes The tokenIds
* @return balances The balances of each token
*/
function tokensOwned(address _owner) public view returns (uint256[] memory indexes, uint256[] memory balances) {
uint256 numTokens = totalSupply();
uint256[] memory tokenIndexes = new uint256[](numTokens);
uint256[] memory tempTokens = new uint256[](numTokens);
uint256 count;
for (uint256 i = 0; i < numTokens; i++) {
uint256 tokenId = allTokens[i];
if (balanceOf(_owner, tokenId) > 0) {
tempTokens[count] = balanceOf(_owner, tokenId);
tokenIndexes[count] = tokenId;
count++;
}
}
// copy over the data to a correct size array
uint256[] memory _ownedTokens = new uint256[](count);
uint256[] memory _ownedTokensIndexes = new uint256[](count);
for (uint256 i = 0; i < count; i++) {
_ownedTokens[i] = tempTokens[i];
_ownedTokensIndexes[i] = tokenIndexes[i];
}
return (_ownedTokensIndexes, _ownedTokens);
}
/**
* @dev Will set _operator operator status to true or false
* @param _operator Address to changes operator status.
* @param _approved _operator's new operator status (true or false)
*/
function setApprovalForAll(address _operator, bool _approved) public {
// Update operator status
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/// @notice Approve for all by signature
function permit(address _holder, address _spender, uint256 _nonce, uint256 _expiry, bool _allowed, bytes calldata _signature) external {
// Calculate hash
bytes32 digest =
keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(
PERMIT_TYPEHASH,
_holder,
_spender,
_nonce,
_expiry,
_allowed
))
));
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
bytes32 r;
bytes32 s;
uint8 v;
bytes memory signature = _signature;
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := byte(0, mload(add(signature, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
address recoveredAddress;
// If the version is correct return the signer address
if (v != 27 && v != 28) {
recoveredAddress = address(0);
} else {
// solium-disable-next-line arg-overflow
recoveredAddress = ecrecover(digest, v, r, s);
}
require(_holder != address(0), "Holder can't be zero address");
require(_holder == recoveredAddress, "Signer address is invalid");
require(_expiry == 0 || now <= _expiry, "Permission expired");
require(_nonce == nonces[_holder]++, "Nonce is invalid");
// Update operator status
operators[_holder][_spender] = _allowed;
emit ApprovalForAll(_holder, _spender, _allowed);
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
require(_to != msg.sender, "Can't approve to yourself");
tokenApprovals[_tokenId][msg.sender] = _to;
emit Approval(msg.sender, _to, _tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 _tokenId, address _tokenOwner) public view returns (address) {
return tokenApprovals[_tokenId][_tokenOwner];
}
/**
* @dev Function that verifies whether _operator is an authorized operator of _tokenHolder.
* @param _operator The address of the operator to query status of
* @param _owner Address of the tokenHolder
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator) {
return operators[_owner][_operator];
}
function isApprovedOrOwner(
address _spender,
address _owner,
uint256 _tokenId
) public view returns (bool) {
return (
_spender == _owner ||
getApproved(_tokenId, _owner) == _spender ||
isApprovedForAll(_owner, _spender)
);
}
function _updateTokenBalance(
address _from,
uint256 _tokenId,
uint256 _amount,
ObjectLib.Operations op
) internal {
(uint256 bin, uint256 index) = _tokenId.getTokenBinIndex();
packedTokenBalance[_from][bin] = packedTokenBalance[_from][bin].updateTokenBalance(
index, _amount, op
);
}
}
// File: erc721o/contracts/ERC721OTransferable.sol
pragma solidity ^0.5.4;
contract ERC721OTransferable is ERC721OBase, ReentrancyGuard {
// Libraries
using Address for address;
// safeTransfer constants
bytes4 internal constant ERC721O_RECEIVED = 0xf891ffe0;
bytes4 internal constant ERC721O_BATCH_RECEIVED = 0xd0e17c0b;
function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts) public {
// Batch Transfering
_batchTransferFrom(_from, _to, _tokenIds, _amounts);
}
/**
* @dev transfer objects from different tokenIds to specified address
* @param _from The address to BatchTransfer objects from.
* @param _to The address to batchTransfer objects to.
* @param _tokenIds Array of tokenIds to update balance of
* @param _amounts Array of amount of object per type to be transferred.
* @param _data Data to pass to onERC721OReceived() function if recipient is contract
* Note: Arrays should be sorted so that all tokenIds in a same bin are adjacent (more efficient).
*/
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] memory _tokenIds,
uint256[] memory _amounts,
bytes memory _data
) public nonReentrant {
// Batch Transfering
_batchTransferFrom(_from, _to, _tokenIds, _amounts);
// Pass data if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC721OReceiver(_to).onERC721OBatchReceived(
msg.sender, _from, _tokenIds, _amounts, _data
);
require(retval == ERC721O_BATCH_RECEIVED);
}
}
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] memory _tokenIds,
uint256[] memory _amounts
) public {
safeBatchTransferFrom(_from, _to, _tokenIds, _amounts, "");
}
function transfer(address _to, uint256 _tokenId, uint256 _amount) public {
_transferFrom(msg.sender, _to, _tokenId, _amount);
}
function transferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) public {
_transferFrom(_from, _to, _tokenId, _amount);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) public {
safeTransferFrom(_from, _to, _tokenId, _amount, "");
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount, bytes memory _data) public nonReentrant {
_transferFrom(_from, _to, _tokenId, _amount);
require(
_checkAndCallSafeTransfer(_from, _to, _tokenId, _amount, _data),
"Sent to a contract which is not an ERC721O receiver"
);
}
/**
* @dev transfer objects from different tokenIds to specified address
* @param _from The address to BatchTransfer objects from.
* @param _to The address to batchTransfer objects to.
* @param _tokenIds Array of tokenIds to update balance of
* @param _amounts Array of amount of object per type to be transferred.
* Note: Arrays should be sorted so that all tokenIds in a same bin are adjacent (more efficient).
*/
function _batchTransferFrom(
address _from,
address _to,
uint256[] memory _tokenIds,
uint256[] memory _amounts
) internal isOperatorOrOwner(_from) {
// Requirements
require(_tokenIds.length == _amounts.length, "Inconsistent array length between args");
require(_to != address(0), "Invalid to address");
// Number of transfers to execute
uint256 nTransfer = _tokenIds.length;
// Don't do useless calculations
if (_from == _to) {
for (uint256 i = 0; i < nTransfer; i++) {
emit Transfer(_from, _to, _tokenIds[i]);
emit TransferWithQuantity(_from, _to, _tokenIds[i], _amounts[i]);
}
return;
}
for (uint256 i = 0; i < nTransfer; i++) {
require(_amounts[i] <= balanceOf(_from, _tokenIds[i]), "Quantity greater than from balance");
_updateTokenBalance(_from, _tokenIds[i], _amounts[i], ObjectLib.Operations.SUB);
_updateTokenBalance(_to, _tokenIds[i], _amounts[i], ObjectLib.Operations.ADD);
emit Transfer(_from, _to, _tokenIds[i]);
emit TransferWithQuantity(_from, _to, _tokenIds[i], _amounts[i]);
}
// Emit batchTransfer event
emit BatchTransfer(_from, _to, _tokenIds, _amounts);
}
function _transferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) internal {
require(isApprovedOrOwner(msg.sender, _from, _tokenId), "Not approved");
require(_amount <= balanceOf(_from, _tokenId), "Quantity greater than from balance");
require(_to != address(0), "Invalid to address");
_updateTokenBalance(_from, _tokenId, _amount, ObjectLib.Operations.SUB);
_updateTokenBalance(_to, _tokenId, _amount, ObjectLib.Operations.ADD);
emit Transfer(_from, _to, _tokenId);
emit TransferWithQuantity(_from, _to, _tokenId, _amount);
}
function _checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
uint256 _amount,
bytes memory _data
) internal returns (bool) {
if (!_to.isContract()) {
return true;
}
bytes4 retval = IERC721OReceiver(_to).onERC721OReceived(msg.sender, _from, _tokenId, _amount, _data);
return(retval == ERC721O_RECEIVED);
}
}
// File: erc721o/contracts/ERC721OMintable.sol
pragma solidity ^0.5.4;
contract ERC721OMintable is ERC721OTransferable {
// Libraries
using LibPosition for bytes32;
// Internal functions
function _mint(uint256 _tokenId, address _to, uint256 _supply) internal {
// If the token doesn't exist, add it to the tokens array
if (!exists(_tokenId)) {
tokenTypes[_tokenId] = POSITION;
allTokens.push(_tokenId);
}
_updateTokenBalance(_to, _tokenId, _supply, ObjectLib.Operations.ADD);
emit Transfer(address(0), _to, _tokenId);
emit TransferWithQuantity(address(0), _to, _tokenId, _supply);
}
function _burn(address _tokenOwner, uint256 _tokenId, uint256 _quantity) internal {
uint256 ownerBalance = balanceOf(_tokenOwner, _tokenId);
require(ownerBalance >= _quantity, "TOKEN_MINTER:NOT_ENOUGH_POSITIONS");
_updateTokenBalance(_tokenOwner, _tokenId, _quantity, ObjectLib.Operations.SUB);
emit Transfer(_tokenOwner, address(0), _tokenId);
emit TransferWithQuantity(_tokenOwner, address(0), _tokenId, _quantity);
}
function _mint(address _buyer, address _seller, bytes32 _derivativeHash, uint256 _quantity) internal {
_mintLong(_buyer, _derivativeHash, _quantity);
_mintShort(_seller, _derivativeHash, _quantity);
}
function _mintLong(address _buyer, bytes32 _derivativeHash, uint256 _quantity) internal {
uint256 longTokenId = _derivativeHash.getLongTokenId();
_mint(longTokenId, _buyer, _quantity);
}
function _mintShort(address _seller, bytes32 _derivativeHash, uint256 _quantity) internal {
uint256 shortTokenId = _derivativeHash.getShortTokenId();
_mint(shortTokenId, _seller, _quantity);
}
function _registerPortfolio(uint256 _portfolioId, uint256[] memory _tokenIds, uint256[] memory _tokenRatio) internal {
if (!exists(_portfolioId)) {
tokenTypes[_portfolioId] = PORTFOLIO;
emit Composition(_portfolioId, _tokenIds, _tokenRatio);
}
}
}
// File: erc721o/contracts/ERC721OComposable.sol
pragma solidity ^0.5.4;
contract ERC721OComposable is ERC721OMintable {
// Libraries
using UintArray for uint256[];
using SafeMath for uint256;
function compose(uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public {
require(_tokenIds.length == _tokenRatio.length, "TOKEN_MINTER:TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH");
require(_quantity > 0, "TOKEN_MINTER:WRONG_QUANTITY");
require(_tokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY");
require(_tokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE");
for (uint256 i = 0; i < _tokenIds.length; i++) {
_burn(msg.sender, _tokenIds[i], _tokenRatio[i].mul(_quantity));
}
uint256 portfolioId = uint256(keccak256(abi.encodePacked(
_tokenIds,
_tokenRatio
)));
_registerPortfolio(portfolioId, _tokenIds, _tokenRatio);
_mint(portfolioId, msg.sender, _quantity);
}
function decompose(uint256 _portfolioId, uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public {
require(_tokenIds.length == _tokenRatio.length, "TOKEN_MINTER:TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH");
require(_quantity > 0, "TOKEN_MINTER:WRONG_QUANTITY");
require(_tokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY");
require(_tokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE");
uint256 portfolioId = uint256(keccak256(abi.encodePacked(
_tokenIds,
_tokenRatio
)));
require(portfolioId == _portfolioId, "TOKEN_MINTER:WRONG_PORTFOLIO_ID");
_burn(msg.sender, _portfolioId, _quantity);
for (uint256 i = 0; i < _tokenIds.length; i++) {
_mint(_tokenIds[i], msg.sender, _tokenRatio[i].mul(_quantity));
}
}
function recompose(
uint256 _portfolioId,
uint256[] memory _initialTokenIds,
uint256[] memory _initialTokenRatio,
uint256[] memory _finalTokenIds,
uint256[] memory _finalTokenRatio,
uint256 _quantity
) public {
require(_initialTokenIds.length == _initialTokenRatio.length, "TOKEN_MINTER:INITIAL_TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH");
require(_finalTokenIds.length == _finalTokenRatio.length, "TOKEN_MINTER:FINAL_TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH");
require(_quantity > 0, "TOKEN_MINTER:WRONG_QUANTITY");
require(_initialTokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY");
require(_finalTokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY");
require(_initialTokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE");
require(_finalTokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE");
uint256 oldPortfolioId = uint256(keccak256(abi.encodePacked(
_initialTokenIds,
_initialTokenRatio
)));
require(oldPortfolioId == _portfolioId, "TOKEN_MINTER:WRONG_PORTFOLIO_ID");
_burn(msg.sender, _portfolioId, _quantity);
_removedIds(_initialTokenIds, _initialTokenRatio, _finalTokenIds, _finalTokenRatio, _quantity);
_addedIds(_initialTokenIds, _initialTokenRatio, _finalTokenIds, _finalTokenRatio, _quantity);
_keptIds(_initialTokenIds, _initialTokenRatio, _finalTokenIds, _finalTokenRatio, _quantity);
uint256 newPortfolioId = uint256(keccak256(abi.encodePacked(
_finalTokenIds,
_finalTokenRatio
)));
_registerPortfolio(newPortfolioId, _finalTokenIds, _finalTokenRatio);
_mint(newPortfolioId, msg.sender, _quantity);
}
function _removedIds(
uint256[] memory _initialTokenIds,
uint256[] memory _initialTokenRatio,
uint256[] memory _finalTokenIds,
uint256[] memory _finalTokenRatio,
uint256 _quantity
) private {
(uint256[] memory removedIds, uint256[] memory removedIdsIdxs) = _initialTokenIds.difference(_finalTokenIds);
for (uint256 i = 0; i < removedIds.length; i++) {
uint256 index = removedIdsIdxs[i];
_mint(_initialTokenIds[index], msg.sender, _initialTokenRatio[index].mul(_quantity));
}
_finalTokenRatio;
}
function _addedIds(
uint256[] memory _initialTokenIds,
uint256[] memory _initialTokenRatio,
uint256[] memory _finalTokenIds,
uint256[] memory _finalTokenRatio,
uint256 _quantity
) private {
(uint256[] memory addedIds, uint256[] memory addedIdsIdxs) = _finalTokenIds.difference(_initialTokenIds);
for (uint256 i = 0; i < addedIds.length; i++) {
uint256 index = addedIdsIdxs[i];
_burn(msg.sender, _finalTokenIds[index], _finalTokenRatio[index].mul(_quantity));
}
_initialTokenRatio;
}
function _keptIds(
uint256[] memory _initialTokenIds,
uint256[] memory _initialTokenRatio,
uint256[] memory _finalTokenIds,
uint256[] memory _finalTokenRatio,
uint256 _quantity
) private {
(uint256[] memory keptIds, uint256[] memory keptInitialIdxs, uint256[] memory keptFinalIdxs) = _initialTokenIds.intersect(_finalTokenIds);
for (uint256 i = 0; i < keptIds.length; i++) {
uint256 initialIndex = keptInitialIdxs[i];
uint256 finalIndex = keptFinalIdxs[i];
if (_initialTokenRatio[initialIndex] > _finalTokenRatio[finalIndex]) {
uint256 diff = _initialTokenRatio[initialIndex] - _finalTokenRatio[finalIndex];
_mint(_initialTokenIds[initialIndex], msg.sender, diff.mul(_quantity));
} else if (_initialTokenRatio[initialIndex] < _finalTokenRatio[finalIndex]) {
uint256 diff = _finalTokenRatio[finalIndex] - _initialTokenRatio[initialIndex];
_burn(msg.sender, _initialTokenIds[initialIndex], diff.mul(_quantity));
}
}
}
}
// File: erc721o/contracts/Libs/UintsLib.sol
pragma solidity ^0.5.4;
library UintsLib {
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
}
// File: erc721o/contracts/ERC721OBackwardCompatible.sol
pragma solidity ^0.5.4;
contract ERC721OBackwardCompatible is ERC721OComposable {
using UintsLib for uint256;
// Interface constants
bytes4 internal constant INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 internal constant INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
bytes4 internal constant INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
// Reciever constants
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
// Metadata URI
string internal baseTokenURI;
constructor(string memory _baseTokenURI) public ERC721OBase() {
baseTokenURI = _baseTokenURI;
_registerInterface(INTERFACE_ID_ERC721);
_registerInterface(INTERFACE_ID_ERC721_ENUMERABLE);
_registerInterface(INTERFACE_ID_ERC721_METADATA);
}
// ERC721 compatibility
function implementsERC721() public pure returns (bool) {
return true;
}
/**
* @dev Gets the owner of a given NFT
* @param _tokenId uint256 representing the unique token identifier
* @return address the owner of the token
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
if (exists(_tokenId)) {
return address(this);
}
return address(0);
}
/**
* @dev Gets the number of tokens owned by the address we are checking
* @param _owner The adddress we are checking
* @return balance The unique amount of tokens owned
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
(, uint256[] memory tokens) = tokensOwned(_owner);
return tokens.length;
}
// ERC721 - Enumerable compatibility
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId) {
(, uint256[] memory tokens) = tokensOwned(_owner);
require(_index < tokens.length);
return tokens[_index];
}
// ERC721 - Metadata compatibility
function tokenURI(uint256 _tokenId) public view returns (string memory tokenUri) {
require(exists(_tokenId), "Token doesn't exist");
return string(abi.encodePacked(
baseTokenURI,
_tokenId.uint2str(),
".json"
));
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
if (exists(_tokenId)) {
return address(this);
}
return address(0);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public {
safeTransferFrom(_from, _to, _tokenId, "");
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public nonReentrant {
_transferFrom(_from, _to, _tokenId, 1);
require(
_checkAndCallSafeTransfer(_from, _to, _tokenId, _data),
"Sent to a contract which is not an ERC721 receiver"
);
}
function transferFrom(address _from, address _to, uint256 _tokenId) public {
_transferFrom(_from, _to, _tokenId, 1);
}
/**
* @dev Internal function to invoke `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 whether the call correctly returned the expected magic value
*/
function _checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
) internal returns (bool) {
if (!_to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(_to).onERC721Received(
msg.sender, _from, _tokenId, _data
);
return (retval == ERC721_RECEIVED);
}
}
// File: contracts/TokenMinter.sol
pragma solidity 0.5.16;
/// @title Opium.TokenMinter contract implements ERC721O token standard for minting, burning and transferring position tokens
contract TokenMinter is ERC721OBackwardCompatible, UsingRegistry {
/// @notice Calls constructors of super-contracts
/// @param _baseTokenURI string URI for token explorers
/// @param _registry address Address of Opium.registry
constructor(string memory _baseTokenURI, address _registry) public ERC721OBackwardCompatible(_baseTokenURI) UsingRegistry(_registry) {}
/// @notice Mints LONG and SHORT position tokens
/// @param _buyer address Address of LONG position receiver
/// @param _seller address Address of SHORT position receiver
/// @param _derivativeHash bytes32 Hash of derivative (ticker) of position
/// @param _quantity uint256 Quantity of positions to mint
function mint(address _buyer, address _seller, bytes32 _derivativeHash, uint256 _quantity) external onlyCore {
_mint(_buyer, _seller, _derivativeHash, _quantity);
}
/// @notice Mints only LONG position tokens for "pooled" derivatives
/// @param _buyer address Address of LONG position receiver
/// @param _derivativeHash bytes32 Hash of derivative (ticker) of position
/// @param _quantity uint256 Quantity of positions to mint
function mint(address _buyer, bytes32 _derivativeHash, uint256 _quantity) external onlyCore {
_mintLong(_buyer, _derivativeHash, _quantity);
}
/// @notice Burns position tokens
/// @param _tokenOwner address Address of tokens owner
/// @param _tokenId uint256 tokenId of positions to burn
/// @param _quantity uint256 Quantity of positions to burn
function burn(address _tokenOwner, uint256 _tokenId, uint256 _quantity) external onlyCore {
_burn(_tokenOwner, _tokenId, _quantity);
}
/// @notice ERC721 interface compatible function for position token name retrieving
/// @return Returns name of token
function name() external view returns (string memory) {
return "Opium Network Position Token";
}
/// @notice ERC721 interface compatible function for position token symbol retrieving
/// @return Returns symbol of token
function symbol() external view returns (string memory) {
return "ONP";
}
/// VIEW FUNCTIONS
/// @notice Checks whether _spender is approved to spend tokens on _owners behalf or owner itself
/// @param _spender address Address of spender
/// @param _owner address Address of owner
/// @param _tokenId address tokenId of interest
/// @return Returns whether _spender is approved to spend tokens
function isApprovedOrOwner(
address _spender,
address _owner,
uint256 _tokenId
) public view returns (bool) {
return (
_spender == _owner ||
getApproved(_tokenId, _owner) == _spender ||
isApprovedForAll(_owner, _spender) ||
isOpiumSpender(_spender)
);
}
/// @notice Checks whether _spender is Opium.TokenSpender
/// @return Returns whether _spender is Opium.TokenSpender
function isOpiumSpender(address _spender) public view returns (bool) {
return _spender == registry.getTokenSpender();
}
}
// File: contracts/Errors/OracleAggregatorErrors.sol
pragma solidity 0.5.16;
contract OracleAggregatorErrors {
string constant internal ERROR_ORACLE_AGGREGATOR_NOT_ENOUGH_ETHER = "ORACLE_AGGREGATOR:NOT_ENOUGH_ETHER";
string constant internal ERROR_ORACLE_AGGREGATOR_QUERY_WAS_ALREADY_MADE = "ORACLE_AGGREGATOR:QUERY_WAS_ALREADY_MADE";
string constant internal ERROR_ORACLE_AGGREGATOR_DATA_DOESNT_EXIST = "ORACLE_AGGREGATOR:DATA_DOESNT_EXIST";
string constant internal ERROR_ORACLE_AGGREGATOR_DATA_ALREADY_EXIST = "ORACLE_AGGREGATOR:DATA_ALREADY_EXIST";
}
// File: contracts/Interface/IOracleId.sol
pragma solidity 0.5.16;
/// @title Opium.Interface.IOracleId contract is an interface that every oracleId should implement
interface IOracleId {
/// @notice Requests data from `oracleId` one time
/// @param timestamp uint256 Timestamp at which data are needed
function fetchData(uint256 timestamp) external payable;
/// @notice Requests data from `oracleId` multiple times
/// @param timestamp uint256 Timestamp at which data are needed for the first time
/// @param period uint256 Period in seconds between multiple timestamps
/// @param times uint256 How many timestamps are requested
function recursivelyFetchData(uint256 timestamp, uint256 period, uint256 times) external payable;
/// @notice Requests and returns price in ETH for one request. This function could be called as `view` function. Oraclize API for price calculations restricts making this function as view.
/// @return fetchPrice uint256 Price of one data request in ETH
function calculateFetchPrice() external returns (uint256 fetchPrice);
// Event with oracleId metadata JSON string (for DIB.ONE derivative explorer)
event MetadataSet(string metadata);
}
// File: contracts/OracleAggregator.sol
pragma solidity 0.5.16;
/// @title Opium.OracleAggregator contract requests and caches the data from `oracleId`s and provides them to the Core for positions execution
contract OracleAggregator is OracleAggregatorErrors, ReentrancyGuard {
using SafeMath for uint256;
// Storage for the `oracleId` results
// dataCache[oracleId][timestamp] => data
mapping (address => mapping(uint256 => uint256)) public dataCache;
// Flags whether data were provided
// dataExist[oracleId][timestamp] => bool
mapping (address => mapping(uint256 => bool)) public dataExist;
// Flags whether data were requested
// dataRequested[oracleId][timestamp] => bool
mapping (address => mapping(uint256 => bool)) public dataRequested;
// MODIFIERS
/// @notice Checks whether enough ETH were provided withing data request to proceed
/// @param oracleId address Address of the `oracleId` smart contract
/// @param times uint256 How many times the `oracleId` is being requested
modifier enoughEtherProvided(address oracleId, uint256 times) {
// Calling Opium.IOracleId function to get the data fetch price per one request
uint256 oneTimePrice = calculateFetchPrice(oracleId);
// Checking if enough ether was provided for `times` amount of requests
require(msg.value >= oneTimePrice.mul(times), ERROR_ORACLE_AGGREGATOR_NOT_ENOUGH_ETHER);
_;
}
// PUBLIC FUNCTIONS
/// @notice Requests data from `oracleId` one time
/// @param oracleId address Address of the `oracleId` smart contract
/// @param timestamp uint256 Timestamp at which data are needed
function fetchData(address oracleId, uint256 timestamp) public payable nonReentrant enoughEtherProvided(oracleId, 1) {
// Check if was not requested before and mark as requested
_registerQuery(oracleId, timestamp);
// Call the `oracleId` contract and transfer ETH
IOracleId(oracleId).fetchData.value(msg.value)(timestamp);
}
/// @notice Requests data from `oracleId` multiple times
/// @param oracleId address Address of the `oracleId` smart contract
/// @param timestamp uint256 Timestamp at which data are needed for the first time
/// @param period uint256 Period in seconds between multiple timestamps
/// @param times uint256 How many timestamps are requested
function recursivelyFetchData(address oracleId, uint256 timestamp, uint256 period, uint256 times) public payable nonReentrant enoughEtherProvided(oracleId, times) {
// Check if was not requested before and mark as requested in loop for each timestamp
for (uint256 i = 0; i < times; i++) {
_registerQuery(oracleId, timestamp + period * i);
}
// Call the `oracleId` contract and transfer ETH
IOracleId(oracleId).recursivelyFetchData.value(msg.value)(timestamp, period, times);
}
/// @notice Receives and caches data from `msg.sender`
/// @param timestamp uint256 Timestamp of data
/// @param data uint256 Data itself
function __callback(uint256 timestamp, uint256 data) public {
// Don't allow to push data twice
require(!dataExist[msg.sender][timestamp], ERROR_ORACLE_AGGREGATOR_DATA_ALREADY_EXIST);
// Saving data
dataCache[msg.sender][timestamp] = data;
// Flagging that data were received
dataExist[msg.sender][timestamp] = true;
}
/// @notice Requests and returns price in ETH for one request. This function could be called as `view` function. Oraclize API for price calculations restricts making this function as view.
/// @param oracleId address Address of the `oracleId` smart contract
/// @return fetchPrice uint256 Price of one data request in ETH
function calculateFetchPrice(address oracleId) public returns(uint256 fetchPrice) {
fetchPrice = IOracleId(oracleId).calculateFetchPrice();
}
// PRIVATE FUNCTIONS
/// @notice Checks if data was not requested and provided before and marks as requested
/// @param oracleId address Address of the `oracleId` smart contract
/// @param timestamp uint256 Timestamp at which data are requested
function _registerQuery(address oracleId, uint256 timestamp) private {
// Check if data was not requested and provided yet
require(!dataRequested[oracleId][timestamp] && !dataExist[oracleId][timestamp], ERROR_ORACLE_AGGREGATOR_QUERY_WAS_ALREADY_MADE);
// Mark as requested
dataRequested[oracleId][timestamp] = true;
}
// VIEW FUNCTIONS
/// @notice Returns cached data if they exist, or reverts with an error
/// @param oracleId address Address of the `oracleId` smart contract
/// @param timestamp uint256 Timestamp at which data were requested
/// @return dataResult uint256 Cached data provided by `oracleId`
function getData(address oracleId, uint256 timestamp) public view returns(uint256 dataResult) {
// Check if Opium.OracleAggregator has data
require(hasData(oracleId, timestamp), ERROR_ORACLE_AGGREGATOR_DATA_DOESNT_EXIST);
// Return cached data
dataResult = dataCache[oracleId][timestamp];
}
/// @notice Getter for dataExist mapping
/// @param oracleId address Address of the `oracleId` smart contract
/// @param timestamp uint256 Timestamp at which data were requested
/// @param result bool Returns whether data were provided already
function hasData(address oracleId, uint256 timestamp) public view returns(bool result) {
return dataExist[oracleId][timestamp];
}
}
// File: contracts/Errors/SyntheticAggregatorErrors.sol
pragma solidity 0.5.16;
contract SyntheticAggregatorErrors {
string constant internal ERROR_SYNTHETIC_AGGREGATOR_DERIVATIVE_HASH_NOT_MATCH = "SYNTHETIC_AGGREGATOR:DERIVATIVE_HASH_NOT_MATCH";
string constant internal ERROR_SYNTHETIC_AGGREGATOR_WRONG_MARGIN = "SYNTHETIC_AGGREGATOR:WRONG_MARGIN";
string constant internal ERROR_SYNTHETIC_AGGREGATOR_COMMISSION_TOO_BIG = "SYNTHETIC_AGGREGATOR:COMMISSION_TOO_BIG";
}
// File: contracts/SyntheticAggregator.sol
pragma solidity 0.5.16;
/// @notice Opium.SyntheticAggregator contract initialized, identifies and caches syntheticId sensitive data
contract SyntheticAggregator is SyntheticAggregatorErrors, LibDerivative, LibCommission, ReentrancyGuard {
// Emitted when new ticker is initialized
event Create(Derivative derivative, bytes32 derivativeHash);
// Enum for types of syntheticId
// Invalid - syntheticId is not initialized yet
// NotPool - syntheticId with p2p logic
// Pool - syntheticId with pooled logic
enum SyntheticTypes { Invalid, NotPool, Pool }
// Cache of buyer margin by ticker
// buyerMarginByHash[derivativeHash] = buyerMargin
mapping (bytes32 => uint256) public buyerMarginByHash;
// Cache of seller margin by ticker
// sellerMarginByHash[derivativeHash] = sellerMargin
mapping (bytes32 => uint256) public sellerMarginByHash;
// Cache of type by ticker
// typeByHash[derivativeHash] = type
mapping (bytes32 => SyntheticTypes) public typeByHash;
// Cache of commission by ticker
// commissionByHash[derivativeHash] = commission
mapping (bytes32 => uint256) public commissionByHash;
// Cache of author addresses by ticker
// authorAddressByHash[derivativeHash] = authorAddress
mapping (bytes32 => address) public authorAddressByHash;
// PUBLIC FUNCTIONS
/// @notice Initializes ticker, if was not initialized and returns `syntheticId` author commission from cache
/// @param _derivativeHash bytes32 Hash of derivative
/// @param _derivative Derivative Derivative itself
/// @return commission uint256 Synthetic author commission
function getAuthorCommission(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (uint256 commission) {
// Initialize derivative if wasn't initialized before
_initDerivative(_derivativeHash, _derivative);
commission = commissionByHash[_derivativeHash];
}
/// @notice Initializes ticker, if was not initialized and returns `syntheticId` author address from cache
/// @param _derivativeHash bytes32 Hash of derivative
/// @param _derivative Derivative Derivative itself
/// @return authorAddress address Synthetic author address
function getAuthorAddress(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (address authorAddress) {
// Initialize derivative if wasn't initialized before
_initDerivative(_derivativeHash, _derivative);
authorAddress = authorAddressByHash[_derivativeHash];
}
/// @notice Initializes ticker, if was not initialized and returns buyer and seller margin from cache
/// @param _derivativeHash bytes32 Hash of derivative
/// @param _derivative Derivative Derivative itself
/// @return buyerMargin uint256 Margin of buyer
/// @return sellerMargin uint256 Margin of seller
function getMargin(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (uint256 buyerMargin, uint256 sellerMargin) {
// If it's a pool, just return margin from syntheticId contract
if (_isPool(_derivativeHash, _derivative)) {
return IDerivativeLogic(_derivative.syntheticId).getMargin(_derivative);
}
// Initialize derivative if wasn't initialized before
_initDerivative(_derivativeHash, _derivative);
// Check if margins for _derivativeHash were already cached
buyerMargin = buyerMarginByHash[_derivativeHash];
sellerMargin = sellerMarginByHash[_derivativeHash];
}
/// @notice Checks whether `syntheticId` implements pooled logic
/// @param _derivativeHash bytes32 Hash of derivative
/// @param _derivative Derivative Derivative itself
/// @return result bool Returns whether synthetic implements pooled logic
function isPool(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (bool result) {
result = _isPool(_derivativeHash, _derivative);
}
// PRIVATE FUNCTIONS
/// @notice Initializes ticker, if was not initialized and returns whether `syntheticId` implements pooled logic
/// @param _derivativeHash bytes32 Hash of derivative
/// @param _derivative Derivative Derivative itself
/// @return result bool Returns whether synthetic implements pooled logic
function _isPool(bytes32 _derivativeHash, Derivative memory _derivative) private returns (bool result) {
// Initialize derivative if wasn't initialized before
_initDerivative(_derivativeHash, _derivative);
result = typeByHash[_derivativeHash] == SyntheticTypes.Pool;
}
/// @notice Initializes ticker: caches syntheticId type, margin, author address and commission
/// @param _derivativeHash bytes32 Hash of derivative
/// @param _derivative Derivative Derivative itself
function _initDerivative(bytes32 _derivativeHash, Derivative memory _derivative) private {
// Check if type for _derivativeHash was already cached
SyntheticTypes syntheticType = typeByHash[_derivativeHash];
// Type could not be Invalid, thus this condition says us that type was not cached before
if (syntheticType != SyntheticTypes.Invalid) {
return;
}
// For security reasons we calculate hash of provided _derivative
bytes32 derivativeHash = getDerivativeHash(_derivative);
require(derivativeHash == _derivativeHash, ERROR_SYNTHETIC_AGGREGATOR_DERIVATIVE_HASH_NOT_MATCH);
// POOL
// Get isPool from SyntheticId
bool result = IDerivativeLogic(_derivative.syntheticId).isPool();
// Cache type returned from synthetic
typeByHash[derivativeHash] = result ? SyntheticTypes.Pool : SyntheticTypes.NotPool;
// MARGIN
// Get margin from SyntheticId
(uint256 buyerMargin, uint256 sellerMargin) = IDerivativeLogic(_derivative.syntheticId).getMargin(_derivative);
// We are not allowing both margins to be equal to 0
require(buyerMargin != 0 || sellerMargin != 0, ERROR_SYNTHETIC_AGGREGATOR_WRONG_MARGIN);
// Cache margins returned from synthetic
buyerMarginByHash[derivativeHash] = buyerMargin;
sellerMarginByHash[derivativeHash] = sellerMargin;
// AUTHOR ADDRESS
// Cache author address returned from synthetic
authorAddressByHash[derivativeHash] = IDerivativeLogic(_derivative.syntheticId).getAuthorAddress();
// AUTHOR COMMISSION
// Get commission from syntheticId
uint256 commission = IDerivativeLogic(_derivative.syntheticId).getAuthorCommission();
// Check if commission is not set > 100%
require(commission <= COMMISSION_BASE, ERROR_SYNTHETIC_AGGREGATOR_COMMISSION_TOO_BIG);
// Cache commission
commissionByHash[derivativeHash] = commission;
// If we are here, this basically means this ticker was not used before, so we emit an event for Dapps developers about new ticker (derivative) and it's hash
emit Create(_derivative, derivativeHash);
}
}
// File: contracts/Lib/Whitelisted.sol
pragma solidity 0.5.16;
/// @title Opium.Lib.Whitelisted contract implements whitelist with modifier to restrict access to only whitelisted addresses
contract Whitelisted {
// Whitelist array
address[] internal whitelist;
/// @notice This modifier restricts access to functions, which could be called only by whitelisted addresses
modifier onlyWhitelisted() {
// Allowance flag
bool allowed = false;
// Going through whitelisted addresses array
uint256 whitelistLength = whitelist.length;
for (uint256 i = 0; i < whitelistLength; i++) {
// If `msg.sender` is met within whitelisted addresses, raise the flag and exit the loop
if (whitelist[i] == msg.sender) {
allowed = true;
break;
}
}
// Check if flag was raised
require(allowed, "Only whitelisted allowed");
_;
}
/// @notice Getter for whitelisted addresses array
/// @return Array of whitelisted addresses
function getWhitelist() public view returns (address[] memory) {
return whitelist;
}
}
// File: contracts/Lib/WhitelistedWithGovernance.sol
pragma solidity 0.5.16;
/// @title Opium.Lib.WhitelistedWithGovernance contract implements Opium.Lib.Whitelisted and adds governance for whitelist controlling
contract WhitelistedWithGovernance is Whitelisted {
// Emitted when new governor is set
event GovernorSet(address governor);
// Emitted when new whitelist is proposed
event Proposed(address[] whitelist);
// Emitted when proposed whitelist is committed (set)
event Committed(address[] whitelist);
// Proposal life timelock interval
uint256 public timeLockInterval;
// Governor address
address public governor;
// Timestamp of last proposal
uint256 public proposalTime;
// Proposed whitelist
address[] public proposedWhitelist;
/// @notice This modifier restricts access to functions, which could be called only by governor
modifier onlyGovernor() {
require(msg.sender == governor, "Only governor allowed");
_;
}
/// @notice Contract constructor
/// @param _timeLockInterval uint256 Initial value for timelock interval
/// @param _governor address Initial value for governor
constructor(uint256 _timeLockInterval, address _governor) public {
timeLockInterval = _timeLockInterval;
governor = _governor;
emit GovernorSet(governor);
}
/// @notice Calling this function governor could propose new whitelist addresses array. Also it allows to initialize first whitelist if it was not initialized yet.
function proposeWhitelist(address[] memory _whitelist) public onlyGovernor {
// Restrict empty proposals
require(_whitelist.length != 0, "Can't be empty");
// Consider empty whitelist as not initialized, as proposing of empty whitelists is not allowed
// If whitelist has never been initialized, we set whitelist right away without proposal
if (whitelist.length == 0) {
whitelist = _whitelist;
emit Committed(_whitelist);
// Otherwise save current time as timestamp of proposal, save proposed whitelist and emit event
} else {
proposalTime = now;
proposedWhitelist = _whitelist;
emit Proposed(_whitelist);
}
}
/// @notice Calling this function governor commits proposed whitelist if timelock interval of proposal was passed
function commitWhitelist() public onlyGovernor {
// Check if proposal was made
require(proposalTime != 0, "Didn't proposed yet");
// Check if timelock interval was passed
require((proposalTime + timeLockInterval) < now, "Can't commit yet");
// Set new whitelist and emit event
whitelist = proposedWhitelist;
emit Committed(whitelist);
// Reset proposal time lock
proposalTime = 0;
}
/// @notice This function allows governor to transfer governance to a new governor and emits event
/// @param _governor address Address of new governor
function setGovernor(address _governor) public onlyGovernor {
require(_governor != address(0), "Can't set zero address");
governor = _governor;
emit GovernorSet(governor);
}
}
// File: contracts/Lib/WhitelistedWithGovernanceAndChangableTimelock.sol
pragma solidity 0.5.16;
/// @notice Opium.Lib.WhitelistedWithGovernanceAndChangableTimelock contract implements Opium.Lib.WhitelistedWithGovernance and adds possibility for governor to change timelock interval within timelock interval
contract WhitelistedWithGovernanceAndChangableTimelock is WhitelistedWithGovernance {
// Emitted when new timelock is proposed
event Proposed(uint256 timelock);
// Emitted when new timelock is committed (set)
event Committed(uint256 timelock);
// Timestamp of last timelock proposal
uint256 public timeLockProposalTime;
// Proposed timelock
uint256 public proposedTimeLock;
/// @notice Calling this function governor could propose new timelock
/// @param _timelock uint256 New timelock value
function proposeTimelock(uint256 _timelock) public onlyGovernor {
timeLockProposalTime = now;
proposedTimeLock = _timelock;
emit Proposed(_timelock);
}
/// @notice Calling this function governor could commit previously proposed new timelock if timelock interval of proposal was passed
function commitTimelock() public onlyGovernor {
// Check if proposal was made
require(timeLockProposalTime != 0, "Didn't proposed yet");
// Check if timelock interval was passed
require((timeLockProposalTime + timeLockInterval) < now, "Can't commit yet");
// Set new timelock and emit event
timeLockInterval = proposedTimeLock;
emit Committed(proposedTimeLock);
// Reset timelock time lock
timeLockProposalTime = 0;
}
}
// File: contracts/TokenSpender.sol
pragma solidity 0.5.16;
/// @title Opium.TokenSpender contract holds users ERC20 approvals and allows whitelisted contracts to use tokens
contract TokenSpender is WhitelistedWithGovernanceAndChangableTimelock {
using SafeERC20 for IERC20;
// Initial timelock period
uint256 public constant WHITELIST_TIMELOCK = 1 hours;
/// @notice Calls constructors of super-contracts
/// @param _governor address Address of governor, who is allowed to adjust whitelist
constructor(address _governor) public WhitelistedWithGovernance(WHITELIST_TIMELOCK, _governor) {}
/// @notice Using this function whitelisted contracts could call ERC20 transfers
/// @param token IERC20 Instance of token
/// @param from address Address from which tokens are transferred
/// @param to address Address of tokens receiver
/// @param amount uint256 Amount of tokens to be transferred
function claimTokens(IERC20 token, address from, address to, uint256 amount) external onlyWhitelisted {
token.safeTransferFrom(from, to, amount);
}
/// @notice Using this function whitelisted contracts could call ERC721O transfers
/// @param token IERC721O Instance of token
/// @param from address Address from which tokens are transferred
/// @param to address Address of tokens receiver
/// @param tokenId uint256 Token ID to be transferred
/// @param amount uint256 Amount of tokens to be transferred
function claimPositions(IERC721O token, address from, address to, uint256 tokenId, uint256 amount) external onlyWhitelisted {
token.safeTransferFrom(from, to, tokenId, amount);
}
}
// File: contracts/Core.sol
pragma solidity 0.5.16;
/// @title Opium.Core contract creates positions, holds and distributes margin at the maturity
contract Core is LibDerivative, LibCommission, UsingRegistry, CoreErrors, ReentrancyGuard {
using SafeMath for uint256;
using LibPosition for bytes32;
using SafeERC20 for IERC20;
// Emitted when Core creates new position
event Created(address buyer, address seller, bytes32 derivativeHash, uint256 quantity);
// Emitted when Core executes positions
event Executed(address tokenOwner, uint256 tokenId, uint256 quantity);
// Emitted when Core cancels ticker for the first time
event Canceled(bytes32 derivativeHash);
// Period of time after which ticker could be canceled if no data was provided to the `oracleId`
uint256 public constant NO_DATA_CANCELLATION_PERIOD = 2 weeks;
// Vaults for pools
// This mapping holds balances of pooled positions
// poolVaults[syntheticAddress][tokenAddress] => availableBalance
mapping (address => mapping(address => uint256)) public poolVaults;
// Vaults for fees
// This mapping holds balances of fee recipients
// feesVaults[feeRecipientAddress][tokenAddress] => availableBalance
mapping (address => mapping(address => uint256)) public feesVaults;
// Hashes of cancelled tickers
mapping (bytes32 => bool) public cancelled;
/// @notice Calls Core.Lib.UsingRegistry constructor
constructor(address _registry) public UsingRegistry(_registry) {}
// PUBLIC FUNCTIONS
/// @notice This function allows fee recipients to withdraw their fees
/// @param _tokenAddress address Address of an ERC20 token to withdraw
function withdrawFee(address _tokenAddress) public nonReentrant {
uint256 balance = feesVaults[msg.sender][_tokenAddress];
feesVaults[msg.sender][_tokenAddress] = 0;
IERC20(_tokenAddress).safeTransfer(msg.sender, balance);
}
/// @notice Creates derivative contracts (positions)
/// @param _derivative Derivative Derivative definition
/// @param _quantity uint256 Quantity of derivatives to be created
/// @param _addresses address[2] Addresses of buyer and seller
/// [0] - buyer address
/// [1] - seller address - if seller is set to `address(0)`, consider as pooled position
function create(Derivative memory _derivative, uint256 _quantity, address[2] memory _addresses) public nonReentrant {
if (_addresses[1] == address(0)) {
_createPooled(_derivative, _quantity, _addresses[0]);
} else {
_create(_derivative, _quantity, _addresses);
}
}
/// @notice Executes several positions of `msg.sender` with same `tokenId`
/// @param _tokenId uint256 `tokenId` of positions that needs to be executed
/// @param _quantity uint256 Quantity of positions to execute
/// @param _derivative Derivative Derivative definition
function execute(uint256 _tokenId, uint256 _quantity, Derivative memory _derivative) public nonReentrant {
uint256[] memory tokenIds = new uint256[](1);
uint256[] memory quantities = new uint256[](1);
Derivative[] memory derivatives = new Derivative[](1);
tokenIds[0] = _tokenId;
quantities[0] = _quantity;
derivatives[0] = _derivative;
_execute(msg.sender, tokenIds, quantities, derivatives);
}
/// @notice Executes several positions of `_tokenOwner` with same `tokenId`
/// @param _tokenOwner address Address of the owner of positions
/// @param _tokenId uint256 `tokenId` of positions that needs to be executed
/// @param _quantity uint256 Quantity of positions to execute
/// @param _derivative Derivative Derivative definition
function execute(address _tokenOwner, uint256 _tokenId, uint256 _quantity, Derivative memory _derivative) public nonReentrant {
uint256[] memory tokenIds = new uint256[](1);
uint256[] memory quantities = new uint256[](1);
Derivative[] memory derivatives = new Derivative[](1);
tokenIds[0] = _tokenId;
quantities[0] = _quantity;
derivatives[0] = _derivative;
_execute(_tokenOwner, tokenIds, quantities, derivatives);
}
/// @notice Executes several positions of `msg.sender` with different `tokenId`s
/// @param _tokenIds uint256[] `tokenId`s of positions that needs to be executed
/// @param _quantities uint256[] Quantity of positions to execute for each `tokenId`
/// @param _derivatives Derivative[] Derivative definitions for each `tokenId`
function execute(uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) public nonReentrant {
_execute(msg.sender, _tokenIds, _quantities, _derivatives);
}
/// @notice Executes several positions of `_tokenOwner` with different `tokenId`s
/// @param _tokenOwner address Address of the owner of positions
/// @param _tokenIds uint256[] `tokenId`s of positions that needs to be executed
/// @param _quantities uint256[] Quantity of positions to execute for each `tokenId`
/// @param _derivatives Derivative[] Derivative definitions for each `tokenId`
function execute(address _tokenOwner, uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) public nonReentrant {
_execute(_tokenOwner, _tokenIds, _quantities, _derivatives);
}
/// @notice Cancels tickers, burns positions and returns margins to positions owners in case no data were provided within `NO_DATA_CANCELLATION_PERIOD`
/// @param _tokenId uint256 `tokenId` of positions that needs to be canceled
/// @param _quantity uint256 Quantity of positions to cancel
/// @param _derivative Derivative Derivative definition
function cancel(uint256 _tokenId, uint256 _quantity, Derivative memory _derivative) public nonReentrant {
uint256[] memory tokenIds = new uint256[](1);
uint256[] memory quantities = new uint256[](1);
Derivative[] memory derivatives = new Derivative[](1);
tokenIds[0] = _tokenId;
quantities[0] = _quantity;
derivatives[0] = _derivative;
_cancel(tokenIds, quantities, derivatives);
}
/// @notice Cancels tickers, burns positions and returns margins to positions owners in case no data were provided within `NO_DATA_CANCELLATION_PERIOD`
/// @param _tokenIds uint256[] `tokenId` of positions that needs to be canceled
/// @param _quantities uint256[] Quantity of positions to cancel for each `tokenId`
/// @param _derivatives Derivative[] Derivative definitions for each `tokenId`
function cancel(uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) public nonReentrant {
_cancel(_tokenIds, _quantities, _derivatives);
}
// PRIVATE FUNCTIONS
struct CreatePooledLocalVars {
SyntheticAggregator syntheticAggregator;
IDerivativeLogic derivativeLogic;
IERC20 marginToken;
TokenSpender tokenSpender;
TokenMinter tokenMinter;
}
/// @notice This function creates pooled positions
/// @param _derivative Derivative Derivative definition
/// @param _quantity uint256 Quantity of positions to create
/// @param _address address Address of position receiver
function _createPooled(Derivative memory _derivative, uint256 _quantity, address _address) private {
// Local variables
CreatePooledLocalVars memory vars;
// Create instance of Opium.SyntheticAggregator
// Create instance of Opium.IDerivativeLogic
// Create instance of margin token
// Create instance of Opium.TokenSpender
// Create instance of Opium.TokenMinter
vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator());
vars.derivativeLogic = IDerivativeLogic(_derivative.syntheticId);
vars.marginToken = IERC20(_derivative.token);
vars.tokenSpender = TokenSpender(registry.getTokenSpender());
vars.tokenMinter = TokenMinter(registry.getMinter());
// Generate hash for derivative
bytes32 derivativeHash = getDerivativeHash(_derivative);
// Check with Opium.SyntheticAggregator if syntheticId is a pool
require(vars.syntheticAggregator.isPool(derivativeHash, _derivative), ERROR_CORE_NOT_POOL);
// Check if ticker was canceled
require(!cancelled[derivativeHash], ERROR_CORE_TICKER_WAS_CANCELLED);
// Validate input data against Derivative logic (`syntheticId`)
require(vars.derivativeLogic.validateInput(_derivative), ERROR_CORE_SYNTHETIC_VALIDATION_ERROR);
// Get cached margin required according to logic from Opium.SyntheticAggregator
(uint256 margin, ) = vars.syntheticAggregator.getMargin(derivativeHash, _derivative);
// Check ERC20 tokens allowance: margin * quantity
// `msg.sender` must provide margin for position creation
require(vars.marginToken.allowance(msg.sender, address(vars.tokenSpender)) >= margin.mul(_quantity), ERROR_CORE_NOT_ENOUGH_TOKEN_ALLOWANCE);
// Take ERC20 tokens from msg.sender, should never revert in correct ERC20 implementation
vars.tokenSpender.claimTokens(vars.marginToken, msg.sender, address(this), margin.mul(_quantity));
// Since it's a pooled position, we add transferred margin to pool balance
poolVaults[_derivative.syntheticId][_derivative.token] = poolVaults[_derivative.syntheticId][_derivative.token].add(margin.mul(_quantity));
// Mint LONG position tokens
vars.tokenMinter.mint(_address, derivativeHash, _quantity);
emit Created(_address, address(0), derivativeHash, _quantity);
}
struct CreateLocalVars {
SyntheticAggregator syntheticAggregator;
IDerivativeLogic derivativeLogic;
IERC20 marginToken;
TokenSpender tokenSpender;
TokenMinter tokenMinter;
}
/// @notice This function creates p2p positions
/// @param _derivative Derivative Derivative definition
/// @param _quantity uint256 Quantity of positions to create
/// @param _addresses address[2] Addresses of buyer and seller
/// [0] - buyer address
/// [1] - seller address
function _create(Derivative memory _derivative, uint256 _quantity, address[2] memory _addresses) private {
// Local variables
CreateLocalVars memory vars;
// Create instance of Opium.SyntheticAggregator
// Create instance of Opium.IDerivativeLogic
// Create instance of margin token
// Create instance of Opium.TokenSpender
// Create instance of Opium.TokenMinter
vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator());
vars.derivativeLogic = IDerivativeLogic(_derivative.syntheticId);
vars.marginToken = IERC20(_derivative.token);
vars.tokenSpender = TokenSpender(registry.getTokenSpender());
vars.tokenMinter = TokenMinter(registry.getMinter());
// Generate hash for derivative
bytes32 derivativeHash = getDerivativeHash(_derivative);
// Check with Opium.SyntheticAggregator if syntheticId is not a pool
require(!vars.syntheticAggregator.isPool(derivativeHash, _derivative), ERROR_CORE_CANT_BE_POOL);
// Check if ticker was canceled
require(!cancelled[derivativeHash], ERROR_CORE_TICKER_WAS_CANCELLED);
// Validate input data against Derivative logic (`syntheticId`)
require(vars.derivativeLogic.validateInput(_derivative), ERROR_CORE_SYNTHETIC_VALIDATION_ERROR);
uint256[2] memory margins;
// Get cached margin required according to logic from Opium.SyntheticAggregator
// margins[0] - buyerMargin
// margins[1] - sellerMargin
(margins[0], margins[1]) = vars.syntheticAggregator.getMargin(derivativeHash, _derivative);
// Check ERC20 tokens allowance: (margins[0] + margins[1]) * quantity
// `msg.sender` must provide margin for position creation
require(vars.marginToken.allowance(msg.sender, address(vars.tokenSpender)) >= margins[0].add(margins[1]).mul(_quantity), ERROR_CORE_NOT_ENOUGH_TOKEN_ALLOWANCE);
// Take ERC20 tokens from msg.sender, should never revert in correct ERC20 implementation
vars.tokenSpender.claimTokens(vars.marginToken, msg.sender, address(this), margins[0].add(margins[1]).mul(_quantity));
// Mint LONG and SHORT positions tokens
vars.tokenMinter.mint(_addresses[0], _addresses[1], derivativeHash, _quantity);
emit Created(_addresses[0], _addresses[1], derivativeHash, _quantity);
}
struct ExecuteAndCancelLocalVars {
TokenMinter tokenMinter;
OracleAggregator oracleAggregator;
SyntheticAggregator syntheticAggregator;
}
/// @notice Executes several positions of `_tokenOwner` with different `tokenId`s
/// @param _tokenOwner address Address of the owner of positions
/// @param _tokenIds uint256[] `tokenId`s of positions that needs to be executed
/// @param _quantities uint256[] Quantity of positions to execute for each `tokenId`
/// @param _derivatives Derivative[] Derivative definitions for each `tokenId`
function _execute(address _tokenOwner, uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) private {
require(_tokenIds.length == _quantities.length, ERROR_CORE_TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH);
require(_tokenIds.length == _derivatives.length, ERROR_CORE_TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH);
// Local variables
ExecuteAndCancelLocalVars memory vars;
// Create instance of Opium.TokenMinter
// Create instance of Opium.OracleAggregator
// Create instance of Opium.SyntheticAggregator
vars.tokenMinter = TokenMinter(registry.getMinter());
vars.oracleAggregator = OracleAggregator(registry.getOracleAggregator());
vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator());
for (uint256 i; i < _tokenIds.length; i++) {
// Check if execution is performed after endTime
require(now > _derivatives[i].endTime, ERROR_CORE_EXECUTION_BEFORE_MATURITY_NOT_ALLOWED);
// Checking whether execution is performed by `_tokenOwner` or `_tokenOwner` allowed third party executions on it's behalf
require(
_tokenOwner == msg.sender ||
IDerivativeLogic(_derivatives[i].syntheticId).thirdpartyExecutionAllowed(_tokenOwner),
ERROR_CORE_SYNTHETIC_EXECUTION_WAS_NOT_ALLOWED
);
// Returns payout for all positions
uint256 payout = _getPayout(_derivatives[i], _tokenIds[i], _quantities[i], vars);
// Transfer payout
if (payout > 0) {
IERC20(_derivatives[i].token).safeTransfer(_tokenOwner, payout);
}
// Burn executed position tokens
vars.tokenMinter.burn(_tokenOwner, _tokenIds[i], _quantities[i]);
emit Executed(_tokenOwner, _tokenIds[i], _quantities[i]);
}
}
/// @notice Cancels tickers, burns positions and returns margins to positions owners in case no data were provided within `NO_DATA_CANCELLATION_PERIOD`
/// @param _tokenIds uint256[] `tokenId` of positions that needs to be canceled
/// @param _quantities uint256[] Quantity of positions to cancel for each `tokenId`
/// @param _derivatives Derivative[] Derivative definitions for each `tokenId`
function _cancel(uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) private {
require(_tokenIds.length == _quantities.length, ERROR_CORE_TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH);
require(_tokenIds.length == _derivatives.length, ERROR_CORE_TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH);
// Local variables
ExecuteAndCancelLocalVars memory vars;
// Create instance of Opium.TokenMinter
// Create instance of Opium.OracleAggregator
// Create instance of Opium.SyntheticAggregator
vars.tokenMinter = TokenMinter(registry.getMinter());
vars.oracleAggregator = OracleAggregator(registry.getOracleAggregator());
vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator());
for (uint256 i; i < _tokenIds.length; i++) {
// Don't allow to cancel tickers with "dummy" oracleIds
require(_derivatives[i].oracleId != address(0), ERROR_CORE_CANT_CANCEL_DUMMY_ORACLE_ID);
// Check if cancellation is called after `NO_DATA_CANCELLATION_PERIOD` and `oracleId` didn't provided data
require(
_derivatives[i].endTime + NO_DATA_CANCELLATION_PERIOD <= now &&
!vars.oracleAggregator.hasData(_derivatives[i].oracleId, _derivatives[i].endTime),
ERROR_CORE_CANCELLATION_IS_NOT_ALLOWED
);
// Generate hash for derivative
bytes32 derivativeHash = getDerivativeHash(_derivatives[i]);
// Emit `Canceled` event only once and mark ticker as canceled
if (!cancelled[derivativeHash]) {
cancelled[derivativeHash] = true;
emit Canceled(derivativeHash);
}
uint256[2] memory margins;
// Get cached margin required according to logic from Opium.SyntheticAggregator
// margins[0] - buyerMargin
// margins[1] - sellerMargin
(margins[0], margins[1]) = vars.syntheticAggregator.getMargin(derivativeHash, _derivatives[i]);
uint256 payout;
// Check if `_tokenId` is an ID of LONG position
if (derivativeHash.getLongTokenId() == _tokenIds[i]) {
// Set payout to buyerPayout
payout = margins[0];
// Check if `_tokenId` is an ID of SHORT position
} else if (derivativeHash.getShortTokenId() == _tokenIds[i]) {
// Set payout to sellerPayout
payout = margins[1];
} else {
// Either portfolioId, hack or bug
revert(ERROR_CORE_UNKNOWN_POSITION_TYPE);
}
// Transfer payout * _quantities[i]
if (payout > 0) {
IERC20(_derivatives[i].token).safeTransfer(msg.sender, payout.mul(_quantities[i]));
}
// Burn canceled position tokens
vars.tokenMinter.burn(msg.sender, _tokenIds[i], _quantities[i]);
}
}
/// @notice Calculates payout for position and gets fees
/// @param _derivative Derivative Derivative definition
/// @param _tokenId uint256 `tokenId` of positions
/// @param _quantity uint256 Quantity of positions
/// @param _vars ExecuteAndCancelLocalVars Helping local variables
/// @return payout uint256 Payout for all tokens
function _getPayout(Derivative memory _derivative, uint256 _tokenId, uint256 _quantity, ExecuteAndCancelLocalVars memory _vars) private returns (uint256 payout) {
// Trying to getData from Opium.OracleAggregator, could be reverted
// Opium allows to use "dummy" oracleIds, in this case data is set to `0`
uint256 data;
if (_derivative.oracleId != address(0)) {
data = _vars.oracleAggregator.getData(_derivative.oracleId, _derivative.endTime);
} else {
data = 0;
}
uint256[2] memory payoutRatio;
// Get payout ratio from Derivative logic
// payoutRatio[0] - buyerPayout
// payoutRatio[1] - sellerPayout
(payoutRatio[0], payoutRatio[1]) = IDerivativeLogic(_derivative.syntheticId).getExecutionPayout(_derivative, data);
// Generate hash for derivative
bytes32 derivativeHash = getDerivativeHash(_derivative);
// Check if ticker was canceled
require(!cancelled[derivativeHash], ERROR_CORE_TICKER_WAS_CANCELLED);
uint256[2] memory margins;
// Get cached total margin required from Opium.SyntheticAggregator
// margins[0] - buyerMargin
// margins[1] - sellerMargin
(margins[0], margins[1]) = _vars.syntheticAggregator.getMargin(derivativeHash, _derivative);
uint256[2] memory payouts;
// Calculate payouts from ratio
// payouts[0] -> buyerPayout = (buyerMargin + sellerMargin) * buyerPayoutRatio / (buyerPayoutRatio + sellerPayoutRatio)
// payouts[1] -> sellerPayout = (buyerMargin + sellerMargin) * sellerPayoutRatio / (buyerPayoutRatio + sellerPayoutRatio)
payouts[0] = margins[0].add(margins[1]).mul(payoutRatio[0]).div(payoutRatio[0].add(payoutRatio[1]));
payouts[1] = margins[0].add(margins[1]).mul(payoutRatio[1]).div(payoutRatio[0].add(payoutRatio[1]));
// Check if `_tokenId` is an ID of LONG position
if (derivativeHash.getLongTokenId() == _tokenId) {
// Check if it's a pooled position
if (_vars.syntheticAggregator.isPool(derivativeHash, _derivative)) {
// Pooled position payoutRatio is considered as full payout, not as payoutRatio
payout = payoutRatio[0];
// Multiply payout by quantity
payout = payout.mul(_quantity);
// Check sufficiency of syntheticId balance in poolVaults
require(
poolVaults[_derivative.syntheticId][_derivative.token] >= payout
,
ERROR_CORE_INSUFFICIENT_POOL_BALANCE
);
// Subtract paid out margin from poolVault
poolVaults[_derivative.syntheticId][_derivative.token] = poolVaults[_derivative.syntheticId][_derivative.token].sub(payout);
} else {
// Set payout to buyerPayout
payout = payouts[0];
// Multiply payout by quantity
payout = payout.mul(_quantity);
}
// Take fees only from profit makers
// Check: payout > buyerMargin * quantity
if (payout > margins[0].mul(_quantity)) {
// Get Opium and `syntheticId` author fees and subtract it from payout
payout = payout.sub(_getFees(_vars.syntheticAggregator, derivativeHash, _derivative, payout - margins[0].mul(_quantity)));
}
// Check if `_tokenId` is an ID of SHORT position
} else if (derivativeHash.getShortTokenId() == _tokenId) {
// Set payout to sellerPayout
payout = payouts[1];
// Multiply payout by quantity
payout = payout.mul(_quantity);
// Take fees only from profit makers
// Check: payout > sellerMargin * quantity
if (payout > margins[1].mul(_quantity)) {
// Get Opium fees and subtract it from payout
payout = payout.sub(_getFees(_vars.syntheticAggregator, derivativeHash, _derivative, payout - margins[1].mul(_quantity)));
}
} else {
// Either portfolioId, hack or bug
revert(ERROR_CORE_UNKNOWN_POSITION_TYPE);
}
}
/// @notice Calculates `syntheticId` author and opium fees from profit makers
/// @param _syntheticAggregator SyntheticAggregator Instance of Opium.SyntheticAggregator
/// @param _derivativeHash bytes32 Derivative hash
/// @param _derivative Derivative Derivative definition
/// @param _profit uint256 payout of one position
/// @return fee uint256 Opium and `syntheticId` author fee
function _getFees(SyntheticAggregator _syntheticAggregator, bytes32 _derivativeHash, Derivative memory _derivative, uint256 _profit) private returns (uint256 fee) {
// Get cached `syntheticId` author address from Opium.SyntheticAggregator
address authorAddress = _syntheticAggregator.getAuthorAddress(_derivativeHash, _derivative);
// Get cached `syntheticId` fee percentage from Opium.SyntheticAggregator
uint256 commission = _syntheticAggregator.getAuthorCommission(_derivativeHash, _derivative);
// Calculate fee
// fee = profit * commission / COMMISSION_BASE
fee = _profit.mul(commission).div(COMMISSION_BASE);
// If commission is zero, finish
if (fee == 0) {
return 0;
}
// Calculate opium fee
// opiumFee = fee * OPIUM_COMMISSION_PART / OPIUM_COMMISSION_BASE
uint256 opiumFee = fee.mul(OPIUM_COMMISSION_PART).div(OPIUM_COMMISSION_BASE);
// Calculate author fee
// authorFee = fee - opiumFee
uint256 authorFee = fee.sub(opiumFee);
// Get opium address
address opiumAddress = registry.getOpiumAddress();
// Update feeVault for Opium team
// feesVault[opium][token] += opiumFee
feesVaults[opiumAddress][_derivative.token] = feesVaults[opiumAddress][_derivative.token].add(opiumFee);
// Update feeVault for `syntheticId` author
// feeVault[author][token] += authorFee
feesVaults[authorAddress][_derivative.token] = feesVaults[authorAddress][_derivative.token].add(authorFee);
}
}
// File: contracts/Errors/MatchingErrors.sol
pragma solidity 0.5.16;
contract MatchingErrors {
string constant internal ERROR_MATCH_CANCELLATION_NOT_ALLOWED = "MATCH:CANCELLATION_NOT_ALLOWED";
string constant internal ERROR_MATCH_ALREADY_CANCELED = "MATCH:ALREADY_CANCELED";
string constant internal ERROR_MATCH_ORDER_WAS_CANCELED = "MATCH:ORDER_WAS_CANCELED";
string constant internal ERROR_MATCH_TAKER_ADDRESS_WRONG = "MATCH:TAKER_ADDRESS_WRONG";
string constant internal ERROR_MATCH_ORDER_IS_EXPIRED = "MATCH:ORDER_IS_EXPIRED";
string constant internal ERROR_MATCH_SENDER_ADDRESS_WRONG = "MATCH:SENDER_ADDRESS_WRONG";
string constant internal ERROR_MATCH_SIGNATURE_NOT_VERIFIED = "MATCH:SIGNATURE_NOT_VERIFIED";
string constant internal ERROR_MATCH_NOT_ENOUGH_ALLOWED_FEES = "MATCH:NOT_ENOUGH_ALLOWED_FEES";
}
// File: contracts/Lib/LibEIP712.sol
pragma solidity 0.5.16;
/// @title Opium.Lib.LibEIP712 contract implements the domain of EIP712 for meta transactions
contract LibEIP712 {
// EIP712Domain structure
// name - protocol name
// version - protocol version
// verifyingContract - signed message verifying contract
struct EIP712Domain {
string name;
string version;
address verifyingContract;
}
// Calculate typehash of ERC712Domain
bytes32 constant internal EIP712DOMAIN_TYPEHASH = keccak256(abi.encodePacked(
"EIP712Domain(",
"string name,",
"string version,",
"address verifyingContract",
")"
));
// solhint-disable-next-line var-name-mixedcase
bytes32 internal DOMAIN_SEPARATOR;
// Calculate domain separator at creation
constructor () public {
DOMAIN_SEPARATOR = keccak256(abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256("Opium Network"),
keccak256("1"),
address(this)
));
}
/// @notice Hashes EIP712Message
/// @param hashStruct bytes32 Hash of structured message
/// @return result bytes32 Hash of EIP712Message
function hashEIP712Message(bytes32 hashStruct) internal view returns (bytes32 result) {
bytes32 domainSeparator = DOMAIN_SEPARATOR;
assembly {
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header
mstore(add(memPtr, 2), domainSeparator) // EIP712 domain hash
mstore(add(memPtr, 34), hashStruct) // Hash of struct
// Compute hash
result := keccak256(memPtr, 66)
}
return result;
}
}
// File: contracts/Matching/SwaprateMatch/LibSwaprateOrder.sol
pragma solidity 0.5.16;
/// @title Opium.Matching.SwaprateMatch.LibSwaprateOrder contract implements EIP712 signed SwaprateOrder for Opium.Matching.SwaprateMatch
contract LibSwaprateOrder is LibEIP712 {
/**
Structure of order
Description should be considered from the order signer (maker) perspective
syntheticId - address of derivative syntheticId
oracleId - address of derivative oracleId
token - address of derivative margin token
makerMarginAddress - address of token that maker is willing to pay with
takerMarginAddress - address of token that maker is willing to receive
makerAddress - address of maker
takerAddress - address of counterparty (taker). If zero address, then taker could be anyone
senderAddress - address which is allowed to settle the order on-chain. If zero address, then anyone could settle
relayerAddress - address of the relayer fee recipient
affiliateAddress - address of the affiliate fee recipient
feeTokenAddress - address of token which is used for fees
endTime - timestamp of derivative maturity
quantity - quantity of positions maker wants to receive
partialFill - whether maker allows partial fill of it's order
param0...param9 - additional params to pass it to syntheticId
relayerFee - amount of fee in feeToken that should be paid to relayer
affiliateFee - amount of fee in feeToken that should be paid to affiliate
nonce - unique order ID
signature - Signature of EIP712 message. Not used in hash, but then set for order processing purposes
*/
struct SwaprateOrder {
address syntheticId;
address oracleId;
address token;
address makerAddress;
address takerAddress;
address senderAddress;
address relayerAddress;
address affiliateAddress;
address feeTokenAddress;
uint256 endTime;
uint256 quantity;
uint256 partialFill;
uint256 param0;
uint256 param1;
uint256 param2;
uint256 param3;
uint256 param4;
uint256 param5;
uint256 param6;
uint256 param7;
uint256 param8;
uint256 param9;
uint256 relayerFee;
uint256 affiliateFee;
uint256 nonce;
// Not used in hash
bytes signature;
}
// Calculate typehash of Order
bytes32 constant internal EIP712_ORDER_TYPEHASH = keccak256(abi.encodePacked(
"Order(",
"address syntheticId,",
"address oracleId,",
"address token,",
"address makerAddress,",
"address takerAddress,",
"address senderAddress,",
"address relayerAddress,",
"address affiliateAddress,",
"address feeTokenAddress,",
"uint256 endTime,",
"uint256 quantity,",
"uint256 partialFill,",
"uint256 param0,",
"uint256 param1,",
"uint256 param2,",
"uint256 param3,",
"uint256 param4,",
"uint256 param5,",
"uint256 param6,",
"uint256 param7,",
"uint256 param8,",
"uint256 param9,",
"uint256 relayerFee,",
"uint256 affiliateFee,",
"uint256 nonce",
")"
));
/// @notice Hashes the order
/// @param _order SwaprateOrder Order to hash
/// @return hash bytes32 Order hash
function hashOrder(SwaprateOrder memory _order) public pure returns (bytes32 hash) {
hash = keccak256(
abi.encodePacked(
abi.encodePacked(
EIP712_ORDER_TYPEHASH,
uint256(_order.syntheticId),
uint256(_order.oracleId),
uint256(_order.token),
uint256(_order.makerAddress),
uint256(_order.takerAddress),
uint256(_order.senderAddress),
uint256(_order.relayerAddress),
uint256(_order.affiliateAddress),
uint256(_order.feeTokenAddress)
),
abi.encodePacked(
_order.endTime,
_order.quantity,
_order.partialFill
),
abi.encodePacked(
_order.param0,
_order.param1,
_order.param2,
_order.param3,
_order.param4
),
abi.encodePacked(
_order.param5,
_order.param6,
_order.param7,
_order.param8,
_order.param9
),
abi.encodePacked(
_order.relayerFee,
_order.affiliateFee,
_order.nonce
)
)
);
}
/// @notice Verifies order signature
/// @param _hash bytes32 Hash of the order
/// @param _signature bytes Signature of the order
/// @param _address address Address of the order signer
/// @return bool Returns whether `_signature` is valid and was created by `_address`
function verifySignature(bytes32 _hash, bytes memory _signature, address _address) internal view returns (bool) {
require(_signature.length == 65, "ORDER:INVALID_SIGNATURE_LENGTH");
bytes32 digest = hashEIP712Message(_hash);
address recovered = retrieveAddress(digest, _signature);
return _address == recovered;
}
/// @notice Helping function to recover signer address
/// @param _hash bytes32 Hash for signature
/// @param _signature bytes Signature
/// @return address Returns address of signature creator
function retrieveAddress(bytes32 _hash, bytes memory _signature) private pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := byte(0, mload(add(_signature, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
// solium-disable-next-line arg-overflow
return ecrecover(_hash, v, r, s);
}
}
}
// File: contracts/Matching/SwaprateMatch/SwaprateMatchBase.sol
pragma solidity 0.5.16;
/// @title Opium.Matching.SwaprateMatchBase contract implements logic for order validation and cancelation
contract SwaprateMatchBase is MatchingErrors, LibSwaprateOrder, UsingRegistry, ReentrancyGuard {
using SafeMath for uint256;
using LibPosition for bytes32;
using SafeERC20 for IERC20;
// Emmitted when order was canceled
event Canceled(bytes32 orderHash);
// Canceled orders
// This mapping holds hashes of canceled orders
// canceled[orderHash] => canceled
mapping (bytes32 => bool) public canceled;
// Verified orders
// This mapping holds hashes of verified orders to verify only once
// verified[orderHash] => verified
mapping (bytes32 => bool) public verified;
// Vaults for fees
// This mapping holds balances of relayers and affiliates fees to withdraw
// balances[feeRecipientAddress][tokenAddress] => balances
mapping (address => mapping (address => uint256)) public balances;
// Keeps whether fee was already taken
mapping (bytes32 => bool) public feeTaken;
/// @notice Calling this function maker of the order could cancel it on-chain
/// @param _order SwaprateOrder
function cancel(SwaprateOrder memory _order) public {
require(msg.sender == _order.makerAddress, ERROR_MATCH_CANCELLATION_NOT_ALLOWED);
bytes32 orderHash = hashOrder(_order);
require(!canceled[orderHash], ERROR_MATCH_ALREADY_CANCELED);
canceled[orderHash] = true;
emit Canceled(orderHash);
}
/// @notice Function to withdraw fees from orders for relayer and affiliates
/// @param _token IERC20 Instance of token to withdraw
function withdraw(IERC20 _token) public nonReentrant {
uint256 balance = balances[msg.sender][address(_token)];
balances[msg.sender][address(_token)] = 0;
_token.safeTransfer(msg.sender, balance);
}
/// @notice This function checks whether order was canceled
/// @param _hash bytes32 Hash of the order
function validateNotCanceled(bytes32 _hash) internal view {
require(!canceled[_hash], ERROR_MATCH_ORDER_WAS_CANCELED);
}
/// @notice This function validates takerAddress of _leftOrder. It should match either with _rightOrder.makerAddress or be set to zero address
/// @param _leftOrder SwaprateOrder Left order
/// @param _rightOrder SwaprateOrder Right order
function validateTakerAddress(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder) pure internal {
require(
_leftOrder.takerAddress == address(0) ||
_leftOrder.takerAddress == _rightOrder.makerAddress,
ERROR_MATCH_TAKER_ADDRESS_WRONG
);
}
/// @notice This function validates whether sender address equals to `msg.sender` or set to zero address
/// @param _order SwaprateOrder
function validateSenderAddress(SwaprateOrder memory _order) internal view {
require(
_order.senderAddress == address(0) ||
_order.senderAddress == msg.sender,
ERROR_MATCH_SENDER_ADDRESS_WRONG
);
}
/// @notice This function validates order signature if not validated before
/// @param orderHash bytes32 Hash of the order
/// @param _order SwaprateOrder
function validateSignature(bytes32 orderHash, SwaprateOrder memory _order) internal {
if (verified[orderHash]) {
return;
}
bool result = verifySignature(orderHash, _order.signature, _order.makerAddress);
require(result, ERROR_MATCH_SIGNATURE_NOT_VERIFIED);
verified[orderHash] = true;
}
/// @notice This function is responsible for taking relayer and affiliate fees, if they were not taken already
/// @param _orderHash bytes32 Hash of the order
/// @param _order Order Order itself
function takeFees(bytes32 _orderHash, SwaprateOrder memory _order) internal {
// Check if fee was already taken
if (feeTaken[_orderHash]) {
return;
}
// Check if feeTokenAddress is not set to zero address
if (_order.feeTokenAddress == address(0)) {
return;
}
// Calculate total amount of fees needs to be transfered
uint256 fees = _order.relayerFee.add(_order.affiliateFee);
// If total amount of fees is non-zero
if (fees == 0) {
return;
}
// Create instance of fee token
IERC20 feeToken = IERC20(_order.feeTokenAddress);
// Create instance of TokenSpender
TokenSpender tokenSpender = TokenSpender(registry.getTokenSpender());
// Check if user has enough token approval to pay the fees
require(feeToken.allowance(_order.makerAddress, address(tokenSpender)) >= fees, ERROR_MATCH_NOT_ENOUGH_ALLOWED_FEES);
// Transfer fee
tokenSpender.claimTokens(feeToken, _order.makerAddress, address(this), fees);
// Get opium address
address opiumAddress = registry.getOpiumAddress();
// Add commission to relayer balance, or to opium balance if relayer is not set
if (_order.relayerAddress != address(0)) {
balances[_order.relayerAddress][_order.feeTokenAddress] = balances[_order.relayerAddress][_order.feeTokenAddress].add(_order.relayerFee);
} else {
balances[opiumAddress][_order.feeTokenAddress] = balances[opiumAddress][_order.feeTokenAddress].add(_order.relayerFee);
}
// Add commission to affiliate balance, or to opium balance if affiliate is not set
if (_order.affiliateAddress != address(0)) {
balances[_order.affiliateAddress][_order.feeTokenAddress] = balances[_order.affiliateAddress][_order.feeTokenAddress].add(_order.affiliateFee);
} else {
balances[opiumAddress][_order.feeTokenAddress] = balances[opiumAddress][_order.feeTokenAddress].add(_order.affiliateFee);
}
// Mark the fee of token as taken
feeTaken[_orderHash] = true;
}
/// @notice Helper to get minimal of two integers
/// @param _a uint256 First integer
/// @param _b uint256 Second integer
/// @return uint256 Minimal integer
function min(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a < _b ? _a : _b;
}
}
// File: contracts/Matching/SwaprateMatch/SwaprateMatch.sol
pragma solidity 0.5.16;
/// @title Opium.Matching.SwaprateMatch contract implements create() function to settle a pair of orders and create derivatives for order makers
contract SwaprateMatch is SwaprateMatchBase, LibDerivative {
// Orders filled quantity
// This mapping holds orders filled quantity
// filled[orderHash] => filled
mapping (bytes32 => uint256) public filled;
/// @notice Calls constructors of super-contracts
/// @param _registry address Address of Opium.registry
constructor (address _registry) public UsingRegistry(_registry) {}
/// @notice This function receives left and right orders, derivative related to it
/// @param _leftOrder Order
/// @param _rightOrder Order
/// @param _derivative Derivative Data of derivative for validation and calculation purposes
function create(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder, Derivative memory _derivative) public nonReentrant {
// New deals must not offer tokenIds
require(
_leftOrder.syntheticId == _rightOrder.syntheticId,
"MATCH:NOT_CREATION"
);
// Check if it's not pool
require(!IDerivativeLogic(_derivative.syntheticId).isPool(), "MATCH:CANT_BE_POOL");
// Validate taker if set
validateTakerAddress(_leftOrder, _rightOrder);
validateTakerAddress(_rightOrder, _leftOrder);
// Validate sender if set
validateSenderAddress(_leftOrder);
validateSenderAddress(_rightOrder);
// Validate if was canceled
// orderHashes[0] - leftOrderHash
// orderHashes[1] - rightOrderHash
bytes32[2] memory orderHashes;
orderHashes[0] = hashOrder(_leftOrder);
validateNotCanceled(orderHashes[0]);
validateSignature(orderHashes[0], _leftOrder);
orderHashes[1] = hashOrder(_rightOrder);
validateNotCanceled(orderHashes[1]);
validateSignature(orderHashes[1], _rightOrder);
// Calculate derivative hash and get margin
// margins[0] - leftMargin
// margins[1] - rightMargin
(uint256[2] memory margins, ) = _calculateDerivativeAndGetMargin(_derivative);
// Calculate and validate availabilities of orders and fill them
uint256 fillable = _checkFillability(orderHashes[0], _leftOrder, orderHashes[1], _rightOrder);
// Validate derivative parameters with orders
_verifyDerivative(_leftOrder, _rightOrder, _derivative);
// Take fees
takeFees(orderHashes[0], _leftOrder);
takeFees(orderHashes[1], _rightOrder);
// Send margin to Core
_distributeFunds(_leftOrder, _rightOrder, _derivative, margins, fillable);
// Settle contracts
Core(registry.getCore()).create(_derivative, fillable, [_leftOrder.makerAddress, _rightOrder.makerAddress]);
}
// PRIVATE FUNCTIONS
/// @notice Calculates derivative hash and gets margin
/// @param _derivative Derivative
/// @return margins uint256[2] left and right margin
/// @return derivativeHash bytes32 Hash of the derivative
function _calculateDerivativeAndGetMargin(Derivative memory _derivative) private returns (uint256[2] memory margins, bytes32 derivativeHash) {
// Calculate derivative related data for validation
derivativeHash = getDerivativeHash(_derivative);
// Get cached total margin required according to logic
// margins[0] - leftMargin
// margins[1] - rightMargin
(margins[0], margins[1]) = SyntheticAggregator(registry.getSyntheticAggregator()).getMargin(derivativeHash, _derivative);
}
/// @notice Calculate and validate availabilities of orders and fill them
/// @param _leftOrderHash bytes32
/// @param _leftOrder SwaprateOrder
/// @param _rightOrderHash bytes32
/// @param _rightOrder SwaprateOrder
/// @return fillable uint256
function _checkFillability(bytes32 _leftOrderHash, SwaprateOrder memory _leftOrder, bytes32 _rightOrderHash, SwaprateOrder memory _rightOrder) private returns (uint256 fillable) {
// Calculate availabilities of orders
uint256 leftAvailable = _leftOrder.quantity.sub(filled[_leftOrderHash]);
uint256 rightAvailable = _rightOrder.quantity.sub(filled[_rightOrderHash]);
require(leftAvailable != 0 && rightAvailable !=0, "MATCH:NO_AVAILABLE");
// We could only fill minimum available of both counterparties
fillable = min(leftAvailable, rightAvailable);
// Check fillable with order conditions about partial fill requirements
if (_leftOrder.partialFill == 0 && _rightOrder.partialFill == 0) {
require(_leftOrder.quantity == _rightOrder.quantity, "MATCH:FULL_FILL_NOT_POSSIBLE");
} else if (_leftOrder.partialFill == 0 && _rightOrder.partialFill == 1) {
require(_leftOrder.quantity <= rightAvailable, "MATCH:FULL_FILL_NOT_POSSIBLE");
} else if (_leftOrder.partialFill == 1 && _rightOrder.partialFill == 0) {
require(leftAvailable >= _rightOrder.quantity, "MATCH:FULL_FILL_NOT_POSSIBLE");
}
// Update filled
filled[_leftOrderHash] = filled[_leftOrderHash].add(fillable);
filled[_rightOrderHash] = filled[_rightOrderHash].add(fillable);
}
/// @notice Validate derivative parameters with orders
/// @param _leftOrder SwaprateOrder
/// @param _rightOrder SwaprateOrder
/// @param _derivative Derivative
function _verifyDerivative(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder, Derivative memory _derivative) private pure {
string memory orderError = "MATCH:DERIVATIVE_PARAM_IS_WRONG";
// Validate derivative endTime
require(
_derivative.endTime == _leftOrder.endTime &&
_derivative.endTime == _rightOrder.endTime,
orderError
);
// Validate derivative syntheticId
require(
_derivative.syntheticId == _leftOrder.syntheticId &&
_derivative.syntheticId == _rightOrder.syntheticId,
orderError
);
// Validate derivative oracleId
require(
_derivative.oracleId == _leftOrder.oracleId &&
_derivative.oracleId == _rightOrder.oracleId,
orderError
);
// Validate derivative token
require(
_derivative.token == _leftOrder.token &&
_derivative.token == _rightOrder.token,
orderError
);
// Validate derivative params
require(_derivative.params.length >= 20, "MATCH:DERIVATIVE_PARAMS_LENGTH_IS_WRONG");
// Validate left order params
require(_leftOrder.param0 == _derivative.params[0], orderError);
require(_leftOrder.param1 == _derivative.params[1], orderError);
require(_leftOrder.param2 == _derivative.params[2], orderError);
require(_leftOrder.param3 == _derivative.params[3], orderError);
require(_leftOrder.param4 == _derivative.params[4], orderError);
require(_leftOrder.param5 == _derivative.params[5], orderError);
require(_leftOrder.param6 == _derivative.params[6], orderError);
require(_leftOrder.param7 == _derivative.params[7], orderError);
require(_leftOrder.param8 == _derivative.params[8], orderError);
require(_leftOrder.param9 == _derivative.params[9], orderError);
// Validate right order params
require(_rightOrder.param0 == _derivative.params[10], orderError);
require(_rightOrder.param1 == _derivative.params[11], orderError);
require(_rightOrder.param2 == _derivative.params[12], orderError);
require(_rightOrder.param3 == _derivative.params[13], orderError);
require(_rightOrder.param4 == _derivative.params[14], orderError);
require(_rightOrder.param5 == _derivative.params[15], orderError);
require(_rightOrder.param6 == _derivative.params[16], orderError);
require(_rightOrder.param7 == _derivative.params[17], orderError);
require(_rightOrder.param8 == _derivative.params[18], orderError);
require(_rightOrder.param9 == _derivative.params[19], orderError);
}
/// @notice Distributes funds to core
/// @param _leftOrder SwaprateOrder
/// @param _rightOrder SwaprateOrder
/// @param _derivative Derivative
/// @param margins uint256[2] left and right margin
/// @param _fillable uint256 How many positions are fillable
function _distributeFunds(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder, Derivative memory _derivative, uint256[2] memory margins, uint256 _fillable) private {
IERC20 marginToken = IERC20(_derivative.token);
TokenSpender tokenSpender = TokenSpender(registry.getTokenSpender());
// Transfer margin from left to Match and send to Core
if (margins[0] != 0) {
// Check allowance for margins
require(marginToken.allowance(_leftOrder.makerAddress, address(tokenSpender)) >= margins[0].mul(_fillable), "MATCH:NOT_ENOUGH_ALLOWED_MARGIN");
// Transfer margins from buyer to Match
tokenSpender.claimTokens(marginToken, _leftOrder.makerAddress, address(this), margins[0].mul(_fillable));
}
// Transfer margin from right to Match and send to Core
if (margins[1] != 0) {
// Check allowance for premiums + margin
require(marginToken.allowance(_rightOrder.makerAddress, address(tokenSpender)) >= margins[1].mul(_fillable), "MATCH:NOT_ENOUGH_ALLOWED_MARGIN");
// Transfer margins from seller to Match
tokenSpender.claimTokens(marginToken, _rightOrder.makerAddress, address(this), margins[1].mul(_fillable));
}
if (margins[0].add(margins[1]) != 0) {
// Approve margin to Core for derivative creation
require(marginToken.approve(address(tokenSpender), margins[0].add(margins[1]).mul(_fillable)), "MATCH:COULDNT_APPROVE_MARGIN_FOR_CORE");
}
}
} | @notice Getter for dataExist mapping @param oracleId address Address of the `oracleId` smart contract @param timestamp uint256 Timestamp at which data were requested @param result bool Returns whether data were provided already | function hasData(address oracleId, uint256 timestamp) public view returns(bool result) {
return dataExist[oracleId][timestamp];
}
| 1,368,090 | [
1,
8461,
364,
501,
4786,
2874,
225,
20865,
548,
1758,
5267,
434,
326,
1375,
280,
16066,
548,
68,
13706,
6835,
225,
2858,
2254,
5034,
8159,
622,
1492,
501,
4591,
3764,
225,
563,
1426,
2860,
2856,
501,
4591,
2112,
1818,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
711,
751,
12,
2867,
20865,
548,
16,
2254,
5034,
2858,
13,
1071,
1476,
1135,
12,
6430,
563,
13,
288,
203,
3639,
327,
501,
4786,
63,
280,
16066,
548,
6362,
5508,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
/**
* @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 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 {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @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 this function is
* overloaded;
*
* 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 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), currentAllowance - amount);
_burn(account, amount);
}
}
/**
* @dev {ERC20} token, including:
*
* - Preminted initial supply
* - Ability for holders to burn (destroy) their tokens
* - No access control mechanism (for minting/pausing) and hence no governance
*
* This contract uses {ERC20Burnable} to include burn capabilities - head to
* its documentation for details.
*
* _Available since v3.4._
*/
contract ERC20PresetFixedSupply is ERC20Burnable {
/**
* @dev Mints `initialSupply` amount of token and transfers them to `owner`.
*
* See {ERC20-constructor}.
*/
constructor(
string memory name,
string memory symbol,
uint256 initialSupply,
address owner
) ERC20(name, symbol) {
_mint(owner, initialSupply);
}
}
contract TestScaleSwapToken is ERC20PresetFixedSupply {
constructor(uint256 initialSupply, address owner)
ERC20PresetFixedSupply("TestScaleSwapToken", "TSCA", initialSupply, owner)
{}
} | * @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 {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function name() public view virtual returns (string memory) {
return _name;
}
function symbol() public view virtual returns (string memory) {
return _symbol;
}
function decimals() public view virtual 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");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
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);
}
) internal virtual {}
}
| 6,130,882 | [
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,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
203,
565,
3885,
12,
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,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
5024,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
7175,
31,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
5024,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
6549,
31,
203,
565,
289,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
5024,
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,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
70,
26488,
63,
4631,
15533,
203,
565,
289,
203,
203,
565,
445,
7412,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
1071,
5024,
3849,
2
]
|
./partial_match/3/0xb4f5e198Bf6a4Ab4c23305E357b9fdB5Db8105cd/sources/GuessTheNumber.sol | guessed number is correct, cost of attempt is paid and each next attempt should be more expensive than previous send the jack pot | function guess(uint8 number) public payable {
if (keccak256(abi.encode(number)) == secretNumberHash && msg.value >= 0.1 ether && msg.value >= address(this).balance) {
msg.sender.transfer(address(this).balance + msg.value);
}
}
| 5,222,779 | [
1,
75,
3610,
730,
1300,
353,
3434,
16,
6991,
434,
4395,
353,
30591,
471,
1517,
1024,
4395,
1410,
506,
1898,
19326,
2353,
2416,
1366,
326,
525,
484,
5974,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7274,
12,
11890,
28,
1300,
13,
1071,
8843,
429,
288,
203,
3639,
309,
261,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
12,
2696,
3719,
422,
4001,
1854,
2310,
597,
1234,
18,
1132,
1545,
374,
18,
21,
225,
2437,
597,
1234,
18,
1132,
1545,
1758,
12,
2211,
2934,
12296,
13,
288,
203,
5411,
1234,
18,
15330,
18,
13866,
12,
2867,
12,
2211,
2934,
12296,
397,
1234,
18,
1132,
1769,
203,
3639,
289,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.7;
import "../lib/erc20.sol";
import "../lib/safe-math.sol";
import "../interfaces/swap.sol";
import "../interfaces/wavax.sol";
import "./strategy-axial-base.sol";
import "hardhat/console.sol";
abstract contract StrategyAxial3PoolBase is StrategyAxialBase {
address public flashLoan;
// stablecoins
address public pair1;
address public pair2;
address public pair3;
constructor(
address _flashLoan,
address _pair1,
address _pair2,
address _pair3,
uint256 _poolId,
address _lp,
address _governance,
address _strategist,
address _controller,
address _timelock
)
public
StrategyAxialBase(
_poolId,
_lp,
_governance,
_strategist,
_controller,
_timelock
)
{
flashLoan = _flashLoan;
pair1 = _pair1;
pair2 = _pair2;
pair3 = _pair3;
}
// // // **** Views ****
function getMostPremium() public override view returns (address){
uint256[] memory balances = new uint256[](4);
balances[0] = ISwap(flashLoan).getTokenBalance(0);
balances[1] = ISwap(flashLoan).getTokenBalance(1);
balances[2] = ISwap(flashLoan).getTokenBalance(2);
if (
balances[0] < balances[1] &&
balances[0] < balances[2]
) {
return (pair1);
}
if (
balances[1] < balances[0] &&
balances[1] < balances[2]
) {
return (pair2);
}
if (
balances[2] < balances[0] &&
balances[2] < balances[1]
) {
return (pair3);
}
// If they're somehow equal, we just want one
return (pair3);
}
} | If they're somehow equal, we just want one | return (pair3);
| 12,776,206 | [
1,
2047,
2898,
4565,
28578,
3959,
16,
732,
2537,
2545,
1245,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
327,
261,
6017,
23,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x906AF612F8706b384C7351268FfCd9D947A4d92c/sources/CrashGame.sol | * @dev Calculate the amount of tax to apply to a transaction. @param from the sender @param to the receiver @param amount the quantity of tokens being sent @return the amount of tokens to withhold for taxes/ For adding liquidity at the beginning Also for this contract selling the collected tax. Buy from DEX, or adding liquidity. Sell from DEX, or removing liquidity. Sending to other wallets (e.g. OTC) is tax-free. | function calcTax(
address from,
address to,
uint amount
) internal view returns (uint) {
if (from == owner() || to == owner() || from == address(this)) {
return 0;
return (amount * buyTaxBps) / 10_000;
return (amount * sellTaxBps) / 10_000;
return 0;
}
}
| 2,751,578 | [
1,
8695,
326,
3844,
434,
5320,
358,
2230,
358,
279,
2492,
18,
225,
628,
326,
5793,
225,
358,
326,
5971,
225,
3844,
326,
10457,
434,
2430,
3832,
3271,
327,
326,
3844,
434,
2430,
358,
598,
21056,
364,
5320,
281,
19,
2457,
6534,
4501,
372,
24237,
622,
326,
8435,
8080,
364,
333,
6835,
357,
2456,
326,
12230,
5320,
18,
605,
9835,
628,
2030,
60,
16,
578,
6534,
4501,
372,
24237,
18,
348,
1165,
628,
2030,
60,
16,
578,
9427,
4501,
372,
24237,
18,
2479,
310,
358,
1308,
17662,
2413,
261,
73,
18,
75,
18,
531,
15988,
13,
353,
5320,
17,
9156,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7029,
7731,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
3844,
203,
565,
262,
2713,
1476,
1135,
261,
11890,
13,
288,
203,
3639,
309,
261,
2080,
422,
3410,
1435,
747,
358,
422,
3410,
1435,
747,
628,
422,
1758,
12,
2211,
3719,
288,
203,
5411,
327,
374,
31,
203,
5411,
327,
261,
8949,
380,
30143,
7731,
38,
1121,
13,
342,
1728,
67,
3784,
31,
203,
5411,
327,
261,
8949,
380,
357,
80,
7731,
38,
1121,
13,
342,
1728,
67,
3784,
31,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2022-01-15
*/
// Sources flattened with hardhat v2.8.2 https://hardhat.org
// File @openzeppelin/contracts/utils/[email protected]
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File @openzeppelin/contracts/security/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File @openzeppelin/contracts/utils/cryptography/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
// File @openzeppelin/contracts/utils/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface 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]
//
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface 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/extensions/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File @openzeppelin/contracts/utils/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
//
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File contracts/utils/ERC721A.sol
//
// Creators: locationtba.eth, 2pmflow.eth
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Does not support burning tokens to address(0).
*/
contract ERC721A is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex = 0;
uint256 internal immutable maxBatchSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev
* `maxBatchSize` refers to how much a minter can mint at a time.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_
) {
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721A: balance query for the zero address");
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721A: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > currentIndex - 1) {
endIndex = currentIndex - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721A: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// File contracts/utils/Pausable.sol
//
// Creators: poop.eth
pragma solidity ^0.8.0;
// a basic contract to provide modifiers and functions and enable pausing of an inheriting contract
abstract contract Pausable {
bool private _paused;
constructor() {
_paused = true;
}
function paused() public view virtual returns (bool) {
return _paused;
}
modifier whenNotPaused() {
require(!paused(), "Pausable: contract is paused");
_;
}
modifier whenPaused() {
require(paused(), "Pausable: contract is not paused");
_;
}
function _pause() internal virtual whenNotPaused {
_paused = true;
}
function _resume() internal virtual whenPaused {
_paused = false;
}
}
// File contracts/utils/PreSaleAware.sol
//
// Creators: poop.eth
pragma solidity ^0.8.0;
abstract contract PreSaleAware {
bool private _presale;
constructor() {
_presale = true;
}
function preSale() public view virtual returns (bool) {
return _presale;
}
modifier whenNotPreSale() {
require(!preSale(), "PreSaleAware: presale must not be active");
_;
}
modifier whenPreSale() {
require(preSale(), "PreSaleAware: presale must be active");
_;
}
function _enablePreSale() internal virtual whenNotPreSale {
_presale = true;
}
function _disablePreSale() internal virtual whenPreSale {
_presale = false;
}
}
// File contracts/poop.sol
//
// Creators: poop.eth
pragma solidity ^0.8.0;
contract Poop is ERC721A, Ownable, Pausable, PreSaleAware, ReentrancyGuard {
using Strings for uint256;
uint256 public constant COST = 0.08 ether; // the cost per poop
// the merkle root used for verifying proofs during presale
bytes32 public constant PRE_SALE_MERKLE_ROOT = 0x66af55bb5080f8419cce24254502d91589985ca3b2fb85321486f557c1bf9399;
// packing the next variables as uint16 (max 65535, 2 bytes each, less than 32 bytes = 1 slot)
uint16 public constant MAX_SUPPLY = 8888; // the max total supply
uint16 public constant MAX_PUBLIC_SUPPLY = 8388; // the max public supply
uint16 public constant MAX_MINT_AMOUNT = 10; // the max amount an address can mint
uint16 public constant PRE_SALE_MAX_MINT_AMOUNT = 5; // the max amount an address can mint during presale
// the address of the DAO treasury that will receive percentage of all withdrawls
address public constant DAO_TREASURY_ADDRESS = 0xfE379610071D92Effd15CDF689dfccf7318E6602;
string public hiddenMetadataUri;
string public uriPrefix = "";
bool public revealed = false; // determines whether the artwork is revealed
constructor() ERC721A("PoopMasters", "PM", 500) {
setHiddenMetadataUri("ipfs://QmNYVWbKsgwAgG985t4DAYMXyhd7oxZbixdWsUKtFQCGsv/unrevealed");
}
/*
* Base URI for computing {tokenURI}. The resulting URI for each token will be
* the concatenation of the `baseURI` and the `tokenId`.
*/
function _baseURI() internal view override(ERC721A) returns (string memory) {
return uriPrefix;
}
function tokenURI(uint256 _tokenId) public view override(ERC721A) returns (string memory) {
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
if (revealed == false) {
return hiddenMetadataUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString())) : "";
}
// The following functions are available only to the owner
/*
* @dev Pauses the contract.
*/
function pause() public onlyOwner {
_pause();
}
/*
* @dev Resumes the contract.
*/
function resume() public onlyOwner {
_resume();
}
/*
* @dev Disables presale.
*/
function disablePreSale() public onlyOwner {
_disablePreSale();
}
/*
* @dev Enables presale.
*/
function enablePreSale() public onlyOwner {
_enablePreSale();
}
/*
* @dev Withdraws the contracts balance to owner and DAO.
*/
function withdraw() public onlyOwner {
// Reserve 30% for DAO treasury
(bool hs, ) = payable(DAO_TREASURY_ADDRESS).call{ value: (address(this).balance * 30) / 100 }("");
require(hs, "DAO tranfer failed");
// owner only
(bool os, ) = payable(owner()).call{ value: address(this).balance }("");
require(os, "owner transfer failed");
}
/*
* @dev Reveals the artwork.
*/
function reveal() public onlyOwner {
revealed = true;
}
/*
* @dev Hides the artwork.
*/
function hide() public onlyOwner {
revealed = false;
}
/*
* @dev Sets uri prefix for revealed tokens
*/
function setUriPrefix(string memory _uriPrefix) public onlyOwner {
uriPrefix = _uriPrefix;
}
/*
* @dev Sets uri prefix for hidden tokens
*/
function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner {
hiddenMetadataUri = _hiddenMetadataUri;
}
/*
* @dev Mints a poop to an address
*/
function _mintpoop(address to, uint256 quantity) private {
_safeMint(to, quantity);
}
/*
* @dev Mints poops when presale is enabled.
*/
function presaleMintpoop(uint256 quantity, bytes32[] calldata merkleProof)
external
payable
whenNotPaused
whenPreSale
nonReentrant
{
require(totalSupply() + quantity < MAX_SUPPLY, "max supply reached");
if (_msgSender() != owner()) {
require(totalSupply() + quantity < MAX_PUBLIC_SUPPLY, "max public supply reached");
require(
MerkleProof.verify(merkleProof, PRE_SALE_MERKLE_ROOT, keccak256(abi.encodePacked(_msgSender()))),
"Address not on the list"
);
require(_numberMinted(_msgSender()) + quantity <= PRE_SALE_MAX_MINT_AMOUNT, "presale mint limit reached");
require(msg.value >= COST * quantity, "incorrect ether value");
}
_mintpoop(_msgSender(), quantity);
}
/*
* @dev Mints poops when presale is disabled.
*/
function mintpoop(uint256 quantity) external payable whenNotPaused whenNotPreSale nonReentrant {
require(totalSupply() + quantity < MAX_SUPPLY, "max supply reached");
if (_msgSender() != owner()) {
require(totalSupply() + quantity < MAX_PUBLIC_SUPPLY, "max public supply reached");
require(_numberMinted(_msgSender()) + quantity <= MAX_MINT_AMOUNT, "mint limit reached");
require(msg.value >= COST * quantity, "incorrect ether value");
}
_mintpoop(_msgSender(), quantity);
}
/*
* @dev Returns the number of tokens minted by an address
*/
function numberMinted(address _owner) public view returns (uint256) {
return _numberMinted(_owner);
}
// The following functions are overrides required by Solidity.
function supportsInterface(bytes4 interfaceId) public view override(ERC721A) returns (bool) {
return super.supportsInterface(interfaceId);
}
} | @dev Disables presale./ | function disablePreSale() public onlyOwner {
_disablePreSale();
}
| 10,762,914 | [
1,
1669,
1538,
4075,
5349,
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,
202,
915,
4056,
1386,
30746,
1435,
1071,
1338,
5541,
288,
203,
202,
202,
67,
8394,
1386,
30746,
5621,
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,
-100
]
|
./partial_match/56/0xb847D3916b8becbE7b66424dd245940fB7e317a5/sources/MEAT.sol | @notice Indicates if token is locked | modifier validLock {
require(isLocked == 0, "Token is locked");
_;
}
| 11,143,630 | [
1,
23741,
309,
1147,
353,
8586,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
9606,
923,
2531,
288,
203,
3639,
2583,
12,
291,
8966,
422,
374,
16,
315,
1345,
353,
8586,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/*
CACAW - A CHARITY TOKEN HELPING PROTECT WILDLIFE! 📈
Cacaw was created by a team of animal lovers to help protect wildlife, more specifically to help protect the natural habitats of our avian friends.
🖥 Website: http://www.cacawtoken.com
📲 TG: https://t.me/cacawPortal
🐦 Twitter: https://twitter.com/cacawToken
*/
// 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
);
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address ownershipRenounced) public virtual onlyOwner {
require(ownershipRenounced != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, ownershipRenounced);
_owner = ownershipRenounced;
}
}
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 CACAW is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Cacaw";
string private constant _symbol = "CACAW";
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
//Buy Fee
uint256 private _redisFeeOnBuy = 0; //
uint256 private _taxFeeOnBuy = 0; // 0% buy tax
//Sell Fee
uint256 private _redisFeeOnSell = 0; //
uint256 private _taxFeeOnSell = 5; //5% sell tax
//Original Fee
uint256 private _redisFee = _redisFeeOnSell;
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previousredisFee = _redisFee;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
mapping(address => uint256) private cooldown;
address payable private _developmentAddress = payable(0xc159bC5Eae92dd671F37C4a0B4A6baA1d938277d);/////////////////////////////////////////////////
address payable private _marketingAddress = payable(0xc159bC5Eae92dd671F37C4a0B4A6baA1d938277d);///////////////////////////////////////////////////
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = true;
bool private swapEnabled = true;
uint256 public _maxTxAmount = 15000000000 * 10**9; // 1.5%
uint256 public _maxWalletSize = 30000000000 * 10**9; // 3%
uint256 public _swapTokensAtAmount = 15000000000 * 10**9; //
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);/////////////////////////////////////////////////
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_developmentAddress] = true;
_isExcludedFromFee[_marketingAddress] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if (_redisFee == 0 && _taxFee == 0) return;
_previousredisFee = _redisFee;
_previoustaxFee = _taxFee;
_redisFee = 0;
_taxFee = 0;
}
function restoreAllFee() private {
_redisFee = _previousredisFee;
_taxFee = _previoustaxFee;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
//Trade start check
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
//Transfer Tokens
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
} else {
//Set Fee for Buys
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
//Set Fee for Sells
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_developmentAddress.transfer(amount.div(2));
_marketingAddress.transfer(amount.div(2));
}
function setTrading(bool _tradingOpen) public onlyOwner {
tradingOpen = _tradingOpen;
}
function manualswap() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisFee, _taxFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 redisFee,
uint256 taxFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisFee).div(100);
uint256 tTeam = tAmount.mul(taxFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
_redisFeeOnBuy = redisFeeOnBuy;
_redisFeeOnSell = redisFeeOnSell;
_taxFeeOnBuy = taxFeeOnBuy;
_taxFeeOnSell = taxFeeOnSell;
}
//Set minimum tokens required to swap.
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
//Set minimum tokens required to swap.
function toggleSwap(bool _swapEnabled) public onlyOwner {
swapEnabled = _swapEnabled;
}
//Set MAx transaction
function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
_maxWalletSize = maxWalletSize;
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
} | Buy FeeSell FeeOriginal Fee | contract CACAW is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Cacaw";
string private constant _symbol = "CACAW";
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _redisFee = _redisFeeOnSell;
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previousredisFee = _redisFee;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
mapping(address => uint256) private cooldown;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = true;
bool private swapEnabled = true;
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_developmentAddress] = true;
_isExcludedFromFee[_marketingAddress] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if (_redisFee == 0 && _taxFee == 0) return;
_previousredisFee = _redisFee;
_previoustaxFee = _taxFee;
_redisFee = 0;
_taxFee = 0;
}
function restoreAllFee() private {
_redisFee = _previousredisFee;
_taxFee = _previoustaxFee;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
} else {
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_developmentAddress.transfer(amount.div(2));
_marketingAddress.transfer(amount.div(2));
}
function setTrading(bool _tradingOpen) public onlyOwner {
tradingOpen = _tradingOpen;
}
function manualswap() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisFee, _taxFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 redisFee,
uint256 taxFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisFee).div(100);
uint256 tTeam = tAmount.mul(taxFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
_redisFeeOnBuy = redisFeeOnBuy;
_redisFeeOnSell = redisFeeOnSell;
_taxFeeOnBuy = taxFeeOnBuy;
_taxFeeOnSell = taxFeeOnSell;
}
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
function toggleSwap(bool _swapEnabled) public onlyOwner {
swapEnabled = _swapEnabled;
}
function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
_maxWalletSize = maxWalletSize;
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
} | 1,428,284 | [
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,
385,
2226,
12999,
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,
39,
1077,
2219,
14432,
203,
565,
533,
3238,
5381,
389,
7175,
273,
315,
26022,
12999,
14432,
203,
565,
2254,
28,
3238,
5381,
389,
31734,
273,
2468,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
86,
5460,
329,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
88,
5460,
329,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
1265,
14667,
31,
203,
565,
2254,
5034,
3238,
5381,
4552,
273,
4871,
11890,
5034,
12,
20,
1769,
203,
565,
2254,
5034,
3238,
5381,
389,
88,
5269,
273,
15088,
9449,
380,
1728,
636,
29,
31,
203,
565,
2254,
5034,
3238,
389,
86,
5269,
273,
261,
6694,
300,
261,
6694,
738,
389,
88,
5269,
10019,
203,
565,
2254,
5034,
3238,
389,
88,
14667,
5269,
31,
203,
203,
203,
203,
565,
2254,
5034,
3238,
389,
12311,
14667,
273,
389,
12311,
14667,
1398,
55,
1165,
31,
203,
565,
2254,
5034,
3238,
389,
8066,
14667,
273,
389,
8066,
14667,
1398,
55,
1165,
31,
203,
203,
565,
2254,
5034,
3238,
389,
11515,
12311,
14667,
273,
389,
12311,
14667,
31,
203,
565,
2254,
5034,
3238,
389,
1484,
522,
83,
641,
651,
14667,
273,
389,
8066,
14667,
31,
203,
2
]
|
//Address: 0x589891a198195061cb8ad1a75357a3b7dbadd7bc
//Contract name: COSToken
//Balance: 0 Ether
//Verification Date: 6/13/2018
//Transacion Count: 2
// CODE STARTS HERE
pragma solidity ^0.4.18;
// -----------------------------------------------------------------------
// COS Token by Contentos.
// As ERC20 standard
// Release tokens as a temporary measure
// Creator: Asa17
contract ERC20 {
// the total token supply
uint256 public totalSupply;
// Get the account balance of another account with address _owner
function balanceOf(address _owner) public constant returns (uint256 balance);
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value) public returns (bool success);
// transfer _value amount of token approved by address _from
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
// approve an address with _value amount of tokens
function approve(address _spender, uint256 _value) public returns (bool success);
// get remaining token approved by _owner to _spender
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
// Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
// Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// Trigger when the owner resign and transfer his balance to successor.
event TransferOfPower(address indexed _from, address indexed _to);
}
interface TokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external;
}
contract COSAuth {
address public owner;
constructor () public {
owner = msg.sender;
}
modifier auth {
require(isAuthorized(msg.sender) == true);
_;
}
function isAuthorized(address src) internal view returns (bool) {
if(src == owner){
return true;
} else {
return false;
}
}
}
contract COSStop is COSAuth{
bool public stopped;
modifier stoppable {
require(stopped == false);
_;
}
function stop() auth internal {
stopped = true;
}
function start() auth internal {
stopped = false;
}
}
contract Freezeable is COSAuth{
// internal variables
mapping(address => bool) _freezeList;
// events
event Freezed(address indexed freezedAddr);
event UnFreezed(address indexed unfreezedAddr);
// public functions
function freeze(address addr) auth public returns (bool) {
require(true != _freezeList[addr]);
_freezeList[addr] = true;
emit Freezed(addr);
return true;
}
function unfreeze(address addr) auth public returns (bool) {
require(true == _freezeList[addr]);
_freezeList[addr] = false;
emit UnFreezed(addr);
return true;
}
modifier whenNotFreezed(address addr) {
require(true != _freezeList[addr]);
_;
}
function isFreezing(address addr) public view returns (bool) {
if (true == _freezeList[addr]) {
return true;
} else {
return false;
}
}
}
contract COSTokenBase is ERC20, COSStop, Freezeable{
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
//address public administrator;
// 18 decimals is the strongly suggested default, avoid changing it
// Balances
mapping (address => uint256) balances;
// Allowances
mapping (address => mapping (address => uint256)) allowances;
//register map
mapping (address => string) public register_map;
// ----- Events -----
event Burn(address indexed from, uint256 value);
event LogRegister (address indexed user, string key);
event LogStop ();
/**
* Constructor function
*/
constructor(uint256 _initialSupply, string _tokenName, string _tokenSymbol, uint8 _decimals) public {
name = _tokenName; // Set the name for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
decimals = _decimals;
//owner = msg.sender;
totalSupply = _initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balances[owner] = totalSupply; // Give the creator all initial tokens
}
function balanceOf(address _owner) public view returns(uint256) {
return balances[_owner];
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowances[_owner][_spender];
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) whenNotFreezed(_from) internal returns(bool) {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balances[_from] >= _value);
// Check for overflows
require(balances[_to] + _value > balances[_to]);
// Save this for an assertion in the future
uint previousBalances = balances[_from] + balances[_to];
// Subtract from the sender
balances[_from] -= _value;
// Add the same to the recipient
balances[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balances[_from] + balances[_to] == previousBalances);
return true;
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) stoppable public returns(bool) {
return _transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) stoppable public returns(bool) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] -= _value;
return _transfer(_from, _to, _value);
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) stoppable public returns(bool) {
allowances[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData) stoppable public returns(bool) {
if (approve(_spender, _value)) {
TokenRecipient spender = TokenRecipient(_spender);
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
return false;
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) stoppable public returns(bool) {
require(balances[msg.sender] >= _value); // Check if the sender has enough
balances[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Mint tokens
*
* generate more tokens
*
* @param _value amount of money to mint
*/
function mint(uint256 _value) auth stoppable public returns(bool){
require(balances[msg.sender] + _value > balances[msg.sender]);
require(totalSupply + _value > totalSupply);
balances[msg.sender] += _value;
totalSupply += _value;
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) stoppable public returns(bool) {
require(balances[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowances[_from][msg.sender]); // Check allowance
balances[_from] -= _value; // Subtract from the targeted balance
allowances[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
/**
* Transfer owner's power to others
*
* @param _to the address of the successor
*/
function transferOfPower(address _to) auth stoppable public returns (bool) {
require(msg.sender == owner);
uint value = balances[msg.sender];
_transfer(msg.sender, _to, value);
owner = _to;
emit TransferOfPower(msg.sender, _to);
return true;
}
/**
* approve should be called when allowances[_spender] == 0. To increment
* allowances 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) stoppable public returns (bool) {
// Check for overflows
require(allowances[msg.sender][_spender] + _addedValue > allowances[msg.sender][_spender]);
allowances[msg.sender][_spender] += _addedValue;
emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) stoppable public returns (bool) {
uint oldValue = allowances[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowances[msg.sender][_spender] = 0;
} else {
allowances[msg.sender][_spender] = oldValue - _subtractedValue;
}
emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]);
return true;
}
}
contract COSToken is COSTokenBase {
constructor() COSTokenBase(10000000000, "Contentos", "COS", 18) public {
}
function finish() public{
stop();
emit LogStop();
}
function register(string key) public {
require(bytes(key).length <= 64);
require(balances[msg.sender] > 0);
register_map[msg.sender] = key;
emit LogRegister(msg.sender, key);
}
}
| Public variables of the tokenaddress public administrator; 18 decimals is the strongly suggested default, avoid changing it Balances Allowancesregister map ----- Events ----- | contract COSTokenBase is ERC20, COSStop, Freezeable{
string public name;
string public symbol;
uint8 public decimals = 18;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowances;
mapping (address => string) public register_map;
event Burn(address indexed from, uint256 value);
event LogRegister (address indexed user, string key);
event LogStop ();
constructor(uint256 _initialSupply, string _tokenName, string _tokenSymbol, uint8 _decimals) public {
decimals = _decimals;
}
function balanceOf(address _owner) public view returns(uint256) {
return balances[_owner];
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowances[_owner][_spender];
}
function _transfer(address _from, address _to, uint _value) whenNotFreezed(_from) internal returns(bool) {
require(_to != 0x0);
require(balances[_from] >= _value);
require(balances[_to] + _value > balances[_to]);
uint previousBalances = balances[_from] + balances[_to];
balances[_from] -= _value;
balances[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balances[_from] + balances[_to] == previousBalances);
return true;
}
function transfer(address _to, uint256 _value) stoppable public returns(bool) {
return _transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) stoppable public returns(bool) {
allowances[_from][msg.sender] -= _value;
return _transfer(_from, _to, _value);
}
function approve(address _spender, uint256 _value) stoppable public returns(bool) {
allowances[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) stoppable public returns(bool) {
if (approve(_spender, _value)) {
TokenRecipient spender = TokenRecipient(_spender);
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
return false;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) stoppable public returns(bool) {
if (approve(_spender, _value)) {
TokenRecipient spender = TokenRecipient(_spender);
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
return false;
}
function burn(uint256 _value) stoppable public returns(bool) {
emit Burn(msg.sender, _value);
return true;
}
function mint(uint256 _value) auth stoppable public returns(bool){
require(balances[msg.sender] + _value > balances[msg.sender]);
require(totalSupply + _value > totalSupply);
balances[msg.sender] += _value;
totalSupply += _value;
return true;
}
function burnFrom(address _from, uint256 _value) stoppable public returns(bool) {
emit Burn(_from, _value);
return true;
}
function transferOfPower(address _to) auth stoppable public returns (bool) {
require(msg.sender == owner);
uint value = balances[msg.sender];
_transfer(msg.sender, _to, value);
owner = _to;
emit TransferOfPower(msg.sender, _to);
return true;
}
function increaseApproval(address _spender, uint _addedValue) stoppable public returns (bool) {
require(allowances[msg.sender][_spender] + _addedValue > allowances[msg.sender][_spender]);
allowances[msg.sender][_spender] += _addedValue;
emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) stoppable public returns (bool) {
uint oldValue = allowances[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowances[msg.sender][_spender] = 0;
allowances[msg.sender][_spender] = oldValue - _subtractedValue;
}
emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) stoppable public returns (bool) {
uint oldValue = allowances[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowances[msg.sender][_spender] = 0;
allowances[msg.sender][_spender] = oldValue - _subtractedValue;
}
emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]);
return true;
}
} else {
}
| 12,773,800 | [
1,
4782,
3152,
434,
326,
1147,
2867,
1071,
22330,
31,
6549,
15105,
353,
326,
11773,
715,
22168,
805,
16,
4543,
12770,
518,
605,
26488,
7852,
6872,
4861,
852,
9135,
9043,
9135,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
385,
4005,
969,
2171,
353,
4232,
39,
3462,
16,
385,
4618,
4947,
16,
15217,
8489,
429,
95,
203,
565,
533,
1071,
508,
31,
203,
565,
533,
1071,
3273,
31,
203,
565,
2254,
28,
225,
1071,
15105,
273,
6549,
31,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
324,
26488,
31,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
1699,
6872,
31,
203,
565,
2874,
261,
2867,
516,
533,
13,
5375,
1071,
225,
1744,
67,
1458,
31,
203,
565,
871,
605,
321,
12,
2867,
8808,
628,
16,
2254,
5034,
460,
1769,
203,
565,
871,
1827,
3996,
261,
2867,
8808,
729,
16,
533,
498,
1769,
203,
565,
871,
1827,
4947,
282,
261,
1769,
203,
565,
3885,
12,
11890,
5034,
389,
6769,
3088,
1283,
16,
533,
389,
2316,
461,
16,
533,
389,
2316,
5335,
16,
2254,
28,
389,
31734,
13,
1071,
288,
203,
3639,
15105,
273,
389,
31734,
31,
203,
565,
289,
203,
565,
445,
11013,
951,
12,
2867,
389,
8443,
13,
1071,
1476,
1135,
12,
11890,
5034,
13,
288,
203,
3639,
327,
324,
26488,
63,
67,
8443,
15533,
203,
565,
289,
203,
565,
445,
1699,
1359,
12,
2867,
389,
8443,
16,
1758,
389,
87,
1302,
264,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
1699,
6872,
63,
67,
8443,
6362,
67,
87,
1302,
264,
15533,
203,
565,
289,
203,
565,
445,
389,
13866,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
389,
1132,
13,
1347,
1248,
9194,
94,
329,
24899,
2080,
13,
2713,
2
]
|
./partial_match/1/0x5F8ec04FCf7243F21750C83184849A096F386A3F/sources/EFT.sol | * @dev Decrease the amount of tokens that an owner allowed to a spender. approve should be called when allowed[_spender] == 0. To decrement allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) From MonolithDAO Token.sol @param _spender The address which will spend the funds. @param _subtractedValue The amount of tokens to decrease the allowance by./ | function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| 2,707,590 | [
1,
23326,
448,
326,
3844,
434,
2430,
716,
392,
3410,
2935,
358,
279,
17571,
264,
18,
6617,
537,
1410,
506,
2566,
1347,
2935,
63,
67,
87,
1302,
264,
65,
422,
374,
18,
2974,
15267,
2935,
460,
353,
7844,
358,
999,
333,
445,
358,
4543,
576,
4097,
261,
464,
2529,
3180,
326,
1122,
2492,
353,
1131,
329,
13,
6338,
9041,
355,
483,
18485,
3155,
18,
18281,
225,
389,
87,
1302,
264,
1021,
1758,
1492,
903,
17571,
326,
284,
19156,
18,
225,
389,
1717,
1575,
329,
620,
1021,
3844,
434,
2430,
358,
20467,
326,
1699,
1359,
635,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
20467,
23461,
12,
203,
3639,
1758,
389,
87,
1302,
264,
16,
203,
3639,
2254,
5034,
389,
1717,
1575,
329,
620,
203,
565,
262,
203,
565,
1071,
203,
565,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
2254,
5034,
11144,
273,
2935,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
15533,
203,
3639,
309,
261,
67,
1717,
1575,
329,
620,
1545,
11144,
13,
288,
203,
5411,
2935,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
65,
273,
374,
31,
203,
5411,
2935,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
65,
273,
11144,
18,
1717,
24899,
1717,
1575,
329,
620,
1769,
203,
3639,
289,
203,
3639,
3626,
1716,
685,
1125,
12,
3576,
18,
15330,
16,
389,
87,
1302,
264,
16,
2935,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
19226,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/* 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 "../../libraries/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract TokenData is Iupgradable {
using SafeMath for uint;
address payable public walletAddress;
uint public lockTokenTimeAfterCoverExp;
uint public bookTime;
uint public lockCADays;
uint public lockMVDays;
uint public scValidDays;
uint public joiningFee;
uint public stakerCommissionPer;
uint public stakerMaxCommissionPer;
uint public tokenExponent;
uint public priceStep;
struct StakeCommission {
uint commissionEarned;
uint commissionRedeemed;
}
struct Stake {
address stakedContractAddress;
uint stakedContractIndex;
uint dateAdd;
uint stakeAmount;
uint unlockedAmount;
uint burnedAmount;
uint unLockableBeforeLastBurn;
}
struct Staker {
address stakerAddress;
uint stakerIndex;
}
struct CoverNote {
uint amount;
bool isDeposited;
}
/**
* @dev mapping of uw address to array of sc address to fetch
* all staked contract address of underwriter, pushing
* data into this array of Stake returns stakerIndex
*/
mapping(address => Stake[]) public stakerStakedContracts;
/**
* @dev mapping of sc address to array of UW address to fetch
* all underwritters of the staked smart contract
* pushing data into this mapped array returns scIndex
*/
mapping(address => Staker[]) public stakedContractStakers;
/**
* @dev mapping of staked contract Address to the array of StakeCommission
* here index of this array is stakedContractIndex
*/
mapping(address => mapping(uint => StakeCommission)) public stakedContractStakeCommission;
mapping(address => uint) public lastCompletedStakeCommission;
/**
* @dev mapping of the staked contract address to the current
* staker index who will receive commission.
*/
mapping(address => uint) public stakedContractCurrentCommissionIndex;
/**
* @dev mapping of the staked contract address to the
* current staker index to burn token from.
*/
mapping(address => uint) public stakedContractCurrentBurnIndex;
/**
* @dev mapping to return true if Cover Note deposited against coverId
*/
mapping(uint => CoverNote) public depositedCN;
mapping(address => uint) internal isBookedTokens;
event Commission(
address indexed stakedContractAddress,
address indexed stakerAddress,
uint indexed scIndex,
uint commissionAmount
);
constructor(address payable _walletAdd) public {
walletAddress = _walletAdd;
bookTime = 12 hours;
joiningFee = 100000000000000000; // 0.1 BNB
lockTokenTimeAfterCoverExp = 35 days;
scValidDays = 250;
lockCADays = 7 days;
lockMVDays = 2 days;
stakerCommissionPer = 20;
stakerMaxCommissionPer = 50;
tokenExponent = 4;
priceStep = 1000;
}
/**
* @dev Change the wallet address which receive Joining Fee
*/
function changeWalletAddress(address payable _address) external onlyInternal {
walletAddress = _address;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) {
codeVal = code;
if (code == "TOKEXP") {
val = tokenExponent;
} else if (code == "TOKSTEP") {
val = priceStep;
} else if (code == "RALOCKT") {
val = scValidDays;
} else if (code == "RACOMM") {
val = stakerCommissionPer;
} else if (code == "RAMAXC") {
val = stakerMaxCommissionPer;
} else if (code == "CABOOKT") {
val = bookTime / (1 hours);
} else if (code == "CALOCKT") {
val = lockCADays / (1 days);
} else if (code == "MVLOCKT") {
val = lockMVDays / (1 days);
} else if (code == "QUOLOCKT") {
val = lockTokenTimeAfterCoverExp / (1 days);
} else if (code == "JOINFEE") {
val = joiningFee;
}
}
/**
* @dev Just for interface
*/
function changeDependentContractAddress() public { //solhint-disable-line
}
/**
* @dev to get the contract staked by a staker
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return the address of staked contract
*/
function getStakerStakedContractByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (address stakedContractAddress)
{
stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
}
/**
* @dev to get the staker's staked burned
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return amount burned
*/
function getStakerStakedBurnedByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint burnedAmount)
{
burnedAmount = stakerStakedContracts[
_stakerAddress][_stakerIndex].burnedAmount;
}
/**
* @dev to get the staker's staked unlockable before the last burn
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return unlockable staked tokens
*/
function getStakerStakedUnlockableBeforeLastBurnByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint unlockable)
{
unlockable = stakerStakedContracts[
_stakerAddress][_stakerIndex].unLockableBeforeLastBurn;
}
/**
* @dev to get the staker's staked contract index
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return is the index of the smart contract address
*/
function getStakerStakedContractIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint scIndex)
{
scIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
}
/**
* @dev to get the staker index of the staked contract
* @param _stakedContractAddress is the address of the staked contract
* @param _stakedContractIndex is the index of staked contract
* @return is the index of the staker
*/
function getStakedContractStakerIndex(
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns (uint sIndex)
{
sIndex = stakedContractStakers[
_stakedContractAddress][_stakedContractIndex].stakerIndex;
}
/**
* @dev to get the staker's initial staked amount on the contract
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return staked amount
*/
function getStakerInitialStakedAmountOnContract(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint amount)
{
amount = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakeAmount;
}
/**
* @dev to get the staker's staked contract length
* @param _stakerAddress is the address of the staker
* @return length of staked contract
*/
function getStakerStakedContractLength(
address _stakerAddress
)
public
view
returns (uint length)
{
length = stakerStakedContracts[_stakerAddress].length;
}
/**
* @dev to get the staker's unlocked tokens which were staked
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return amount
*/
function getStakerUnlockedStakedTokens(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint amount)
{
amount = stakerStakedContracts[
_stakerAddress][_stakerIndex].unlockedAmount;
}
/**
* @dev pushes the unlocked staked tokens by a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker to distribute commission.
* @param _amount amount to be given as commission.
*/
function pushUnlockedStakedTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unlockedAmount = stakerStakedContracts[_stakerAddress][
_stakerIndex].unlockedAmount.add(_amount);
}
/**
* @dev pushes the Burned tokens for a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be burned.
*/
function pushBurnedTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].burnedAmount = stakerStakedContracts[_stakerAddress][
_stakerIndex].burnedAmount.add(_amount);
}
/**
* @dev pushes the unLockable tokens for a staker before last burn.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be added to unlockable.
*/
function pushUnlockableBeforeLastBurnTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn = stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn.add(_amount);
}
/**
* @dev sets the unLockable tokens for a staker before last burn.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be added to unlockable.
*/
function setUnlockableBeforeLastBurnTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn = _amount;
}
/**
* @dev pushes the earned commission earned by a staker.
* @param _stakerAddress address of staker.
* @param _stakedContractAddress address of smart contract.
* @param _stakedContractIndex index of the staker to distribute commission.
* @param _commissionAmount amount to be given as commission.
*/
function pushEarnedStakeCommissions(
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex,
uint _commissionAmount
)
public
onlyInternal
{
stakedContractStakeCommission[_stakedContractAddress][_stakedContractIndex].
commissionEarned = stakedContractStakeCommission[_stakedContractAddress][
_stakedContractIndex].commissionEarned.add(_commissionAmount);
emit Commission(
_stakerAddress,
_stakedContractAddress,
_stakedContractIndex,
_commissionAmount
);
}
/**
* @dev pushes the redeemed commission redeemed by a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker to distribute commission.
* @param _amount amount to be given as commission.
*/
function pushRedeemedStakeCommissions(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
uint stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
address stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
stakedContractStakeCommission[stakedContractAddress][stakedContractIndex].
commissionRedeemed = stakedContractStakeCommission[
stakedContractAddress][stakedContractIndex].commissionRedeemed.add(_amount);
}
/**
* @dev Gets stake commission given to an underwriter
* for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function getStakerEarnedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint)
{
return _getStakerEarnedStakeCommission(_stakerAddress, _stakerIndex);
}
/**
* @dev Gets stake commission redeemed by an underwriter
* for particular staked contract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
* @return commissionEarned total amount given to staker.
*/
function getStakerRedeemedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint)
{
return _getStakerRedeemedStakeCommission(_stakerAddress, _stakerIndex);
}
/**
* @dev Gets total stake commission given to an underwriter
* @param _stakerAddress address of staker.
* @return totalCommissionEarned total commission earned by staker.
*/
function getStakerTotalEarnedStakeCommission(
address _stakerAddress
)
public
view
returns (uint totalCommissionEarned)
{
totalCommissionEarned = 0;
for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) {
totalCommissionEarned = totalCommissionEarned.
add(_getStakerEarnedStakeCommission(_stakerAddress, i));
}
}
/**
* @dev Gets total stake commission given to an underwriter
* @param _stakerAddress address of staker.
* @return totalCommissionEarned total commission earned by staker.
*/
function getStakerTotalReedmedStakeCommission(
address _stakerAddress
)
public
view
returns(uint totalCommissionRedeemed)
{
totalCommissionRedeemed = 0;
for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) {
totalCommissionRedeemed = totalCommissionRedeemed.add(
_getStakerRedeemedStakeCommission(_stakerAddress, i));
}
}
/**
* @dev set flag to deposit/ undeposit cover note
* against a cover Id
* @param coverId coverId of Cover
* @param flag true/false for deposit/undeposit
*/
function setDepositCN(uint coverId, bool flag) public onlyInternal {
if (flag == true) {
require(!depositedCN[coverId].isDeposited, "Cover note already deposited");
}
depositedCN[coverId].isDeposited = flag;
}
/**
* @dev set locked cover note amount
* against a cover Id
* @param coverId coverId of Cover
* @param amount amount of sote to be locked
*/
function setDepositCNAmount(uint coverId, uint amount) public onlyInternal {
depositedCN[coverId].amount = amount;
}
/**
* @dev to get the staker address on a staked contract
* @param _stakedContractAddress is the address of the staked contract in concern
* @param _stakedContractIndex is the index of staked contract's index
* @return address of staker
*/
function getStakedContractStakerByIndex(
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns (address stakerAddress)
{
stakerAddress = stakedContractStakers[
_stakedContractAddress][_stakedContractIndex].stakerAddress;
}
/**
* @dev to get the length of stakers on a staked contract
* @param _stakedContractAddress is the address of the staked contract in concern
* @return length in concern
*/
function getStakedContractStakersLength(
address _stakedContractAddress
)
public
view
returns (uint length)
{
length = stakedContractStakers[_stakedContractAddress].length;
}
/**
* @dev Adds a new stake record.
* @param _stakerAddress staker address.
* @param _stakedContractAddress smart contract address.
* @param _amount amountof SOTE to be staked.
*/
function addStake(
address _stakerAddress,
address _stakedContractAddress,
uint _amount
)
public
onlyInternal
returns(uint scIndex)
{
scIndex = (stakedContractStakers[_stakedContractAddress].push(
Staker(_stakerAddress, stakerStakedContracts[_stakerAddress].length))).sub(1);
stakerStakedContracts[_stakerAddress].push(
Stake(_stakedContractAddress, scIndex, now, _amount, 0, 0, 0));
}
/**
* @dev books the user's tokens for maintaining Assessor Velocity,
* i.e. once a token is used to cast a vote as a Claims assessor,
* @param _of user's address.
*/
function bookCATokens(address _of) public onlyInternal {
require(!isCATokensBooked(_of), "Tokens already booked");
isBookedTokens[_of] = now.add(bookTime);
}
/**
* @dev to know if claim assessor's tokens are booked or not
* @param _of is the claim assessor's address in concern
* @return boolean representing the status of tokens booked
*/
function isCATokensBooked(address _of) public view returns(bool res) {
if (now < isBookedTokens[_of])
res = true;
}
/**
* @dev Sets the index which will receive commission.
* @param _stakedContractAddress smart contract address.
* @param _index current index.
*/
function setStakedContractCurrentCommissionIndex(
address _stakedContractAddress,
uint _index
)
public
onlyInternal
{
stakedContractCurrentCommissionIndex[_stakedContractAddress] = _index;
}
/**
* @dev Sets the last complete commission index
* @param _stakerAddress smart contract address.
* @param _index current index.
*/
function setLastCompletedStakeCommissionIndex(
address _stakerAddress,
uint _index
)
public
onlyInternal
{
lastCompletedStakeCommission[_stakerAddress] = _index;
}
/**
* @dev Sets the index till which commission is distrubuted.
* @param _stakedContractAddress smart contract address.
* @param _index current index.
*/
function setStakedContractCurrentBurnIndex(
address _stakedContractAddress,
uint _index
)
public
onlyInternal
{
stakedContractCurrentBurnIndex[_stakedContractAddress] = _index;
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "TOKEXP") {
_setTokenExponent(val);
} else if (code == "TOKSTEP") {
_setPriceStep(val);
} else if (code == "RALOCKT") {
_changeSCValidDays(val);
} else if (code == "RACOMM") {
_setStakerCommissionPer(val);
} else if (code == "RAMAXC") {
_setStakerMaxCommissionPer(val);
} else if (code == "CABOOKT") {
_changeBookTime(val * 1 hours);
} else if (code == "CALOCKT") {
_changelockCADays(val * 1 days);
} else if (code == "MVLOCKT") {
_changelockMVDays(val * 1 days);
} else if (code == "QUOLOCKT") {
_setLockTokenTimeAfterCoverExp(val * 1 days);
} else if (code == "JOINFEE") {
_setJoiningFee(val);
} else {
revert("Invalid param code");
}
}
/**
* @dev Internal function to get stake commission given to an
* underwriter for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function _getStakerEarnedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
internal
view
returns (uint amount)
{
uint _stakedContractIndex;
address _stakedContractAddress;
_stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
_stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
amount = stakedContractStakeCommission[
_stakedContractAddress][_stakedContractIndex].commissionEarned;
}
/**
* @dev Internal function to get stake commission redeemed by an
* underwriter for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function _getStakerRedeemedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
internal
view
returns (uint amount)
{
uint _stakedContractIndex;
address _stakedContractAddress;
_stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
_stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
amount = stakedContractStakeCommission[
_stakedContractAddress][_stakedContractIndex].commissionRedeemed;
}
/**
* @dev to set the percentage of staker commission
* @param _val is new percentage value
*/
function _setStakerCommissionPer(uint _val) internal {
stakerCommissionPer = _val;
}
/**
* @dev to set the max percentage of staker commission
* @param _val is new percentage value
*/
function _setStakerMaxCommissionPer(uint _val) internal {
stakerMaxCommissionPer = _val;
}
/**
* @dev to set the token exponent value
* @param _val is new value
*/
function _setTokenExponent(uint _val) internal {
tokenExponent = _val;
}
/**
* @dev to set the price step
* @param _val is new value
*/
function _setPriceStep(uint _val) internal {
priceStep = _val;
}
/**
* @dev Changes number of days for which SOTE needs to staked in case of underwriting
*/
function _changeSCValidDays(uint _days) internal {
scValidDays = _days;
}
/**
* @dev Changes the time period up to which tokens will be locked.
* Used to generate the validity period of tokens booked by
* a user for participating in claim's assessment/claim's voting.
*/
function _changeBookTime(uint _time) internal {
bookTime = _time;
}
/**
* @dev Changes lock CA days - number of days for which tokens
* are locked while submitting a vote.
*/
function _changelockCADays(uint _val) internal {
lockCADays = _val;
}
/**
* @dev Changes lock MV days - number of days for which tokens are locked
* while submitting a vote.
*/
function _changelockMVDays(uint _val) internal {
lockMVDays = _val;
}
/**
* @dev Changes extra lock period for a cover, post its expiry.
*/
function _setLockTokenTimeAfterCoverExp(uint time) internal {
lockTokenTimeAfterCoverExp = time;
}
/**
* @dev Set the joining fee for membership
*/
function _setJoiningFee(uint _amount) internal {
joiningFee = _amount;
}
} | * @dev mapping of the staked contract address to the current staker index to burn token from./ | mapping(address => uint) public stakedContractCurrentBurnIndex;
| 6,447,779 | [
1,
6770,
434,
326,
384,
9477,
6835,
1758,
358,
326,
783,
384,
6388,
770,
358,
18305,
1147,
628,
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
]
| [
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,
565,
2874,
12,
2867,
516,
2254,
13,
1071,
384,
9477,
8924,
3935,
38,
321,
1016,
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
]
|
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../HandlerBase.sol";
import "./IUniswapFactory.sol";
import "./IUniswapExchange.sol";
contract HUniswap is HandlerBase {
using SafeERC20 for IERC20;
// prettier-ignore
address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95;
function getContractName() public pure override returns (string memory) {
return "HUniswap";
}
function addLiquidity(
uint256 value,
address token,
uint256 maxTokens
) external payable returns (uint256 liquidity) {
// if amount == uint256(-1) return balance of Proxy
value = _getBalance(address(0), value);
maxTokens = _getBalance(token, maxTokens);
IUniswapExchange uniswap = _getExchange(token);
IERC20(token).safeApprove(address(uniswap), maxTokens);
try uniswap.addLiquidity{value: value}(1, maxTokens, now + 1) returns (
uint256 ret
) {
liquidity = ret;
} catch Error(string memory reason) {
_revertMsg("addLiquidity", reason);
} catch {
_revertMsg("addLiquidity");
}
IERC20(token).safeApprove(address(uniswap), 0);
// Update involved token
_updateToken(address(uniswap));
}
function removeLiquidity(
address token,
uint256 amount,
uint256 minEth,
uint256 minTokens
) external payable returns (uint256 ethGain, uint256 tokenGain) {
IUniswapExchange uniswap = _getExchange(token);
// if amount == uint256(-1) return balance of Proxy
amount = _getBalance(address(uniswap), amount);
IERC20(address(uniswap)).safeApprove(address(uniswap), amount);
try
uniswap.removeLiquidity(amount, minEth, minTokens, now + 1)
returns (uint256 ret1, uint256 ret2) {
ethGain = ret1;
tokenGain = ret2;
} catch Error(string memory reason) {
_revertMsg("removeLiquidity", reason);
} catch {
_revertMsg("removeLiquidity");
}
IERC20(address(uniswap)).safeApprove(address(uniswap), 0);
// Update involved token
_updateToken(token);
}
function ethToTokenSwapInput(
uint256 value,
address token,
uint256 minTokens
) external payable returns (uint256 tokensBought) {
// if amount == uint256(-1) return balance of Proxy
value = _getBalance(address(0), value);
IUniswapExchange uniswap = _getExchange(token);
try uniswap.ethToTokenSwapInput{value: value}(minTokens, now) returns (
uint256 ret
) {
tokensBought = ret;
} catch Error(string memory reason) {
_revertMsg("ethToTokenSwapInput", reason);
} catch {
_revertMsg("ethToTokenSwapInput");
}
// Update involved token
_updateToken(token);
}
function ethToTokenSwapOutput(
uint256 value,
address token,
uint256 tokensBought
) external payable returns (uint256 ethSold) {
IUniswapExchange uniswap = _getExchange(token);
// if amount == uint256(-1) return balance of Proxy
value = _getBalance(address(0), value);
try
uniswap.ethToTokenSwapOutput{value: value}(tokensBought, now)
returns (uint256 ret) {
ethSold = ret;
} catch Error(string memory reason) {
_revertMsg("ethToTokenSwapOutput", reason);
} catch {
_revertMsg("ethToTokenSwapOutput");
}
// Update involved token
_updateToken(token);
}
function tokenToEthSwapInput(
address token,
uint256 tokensSold,
uint256 minEth
) external payable returns (uint256 ethBought) {
// if amount == uint256(-1) return balance of Proxy
tokensSold = _getBalance(token, tokensSold);
IUniswapExchange uniswap = _getExchange(token);
IERC20(token).safeApprove(address(uniswap), tokensSold);
try uniswap.tokenToEthSwapInput(tokensSold, minEth, now) returns (
uint256 ret
) {
ethBought = ret;
} catch Error(string memory reason) {
_revertMsg("tokenToEthSwapInput", reason);
} catch {
_revertMsg("tokenToEthSwapInput");
}
IERC20(token).safeApprove(address(uniswap), 0);
}
function tokenToEthSwapOutput(
address token,
uint256 ethBought,
uint256 maxTokens
) external payable returns (uint256 tokensSold) {
IUniswapExchange uniswap = _getExchange(token);
// if amount == uint256(-1) return balance of Proxy
maxTokens = _getBalance(token, maxTokens);
IERC20(token).safeApprove(address(uniswap), maxTokens);
try uniswap.tokenToEthSwapOutput(ethBought, maxTokens, now) returns (
uint256 ret
) {
tokensSold = ret;
} catch Error(string memory reason) {
_revertMsg("tokenToEthSwapOutput", reason);
} catch {
_revertMsg("tokenToEthSwapOutput");
}
IERC20(token).safeApprove(address(uniswap), 0);
}
function tokenToTokenSwapInput(
address token,
uint256 tokensSold,
uint256 minTokensBought,
address tokenAddr
) external payable returns (uint256 tokensBought) {
// if amount == uint256(-1) return balance of Proxy
tokensSold = _getBalance(token, tokensSold);
IUniswapExchange uniswap = _getExchange(token);
IERC20(token).safeApprove(address(uniswap), tokensSold);
try
uniswap.tokenToTokenSwapInput(
tokensSold,
minTokensBought,
1,
now,
tokenAddr
)
returns (uint256 ret) {
tokensBought = ret;
} catch Error(string memory reason) {
_revertMsg("tokenToTokenSwapInput", reason);
} catch {
_revertMsg("tokenToTokenSwapInput");
}
IERC20(token).safeApprove(address(uniswap), 0);
// Update involved token
_updateToken(tokenAddr);
}
function tokenToTokenSwapOutput(
address token,
uint256 tokensBought,
uint256 maxTokensSold,
address tokenAddr
) external payable returns (uint256 tokensSold) {
IUniswapExchange uniswap = _getExchange(token);
// if amount == uint256(-1) return balance of Proxy
maxTokensSold = _getBalance(token, maxTokensSold);
IERC20(token).safeApprove(address(uniswap), maxTokensSold);
try
uniswap.tokenToTokenSwapOutput(
tokensBought,
maxTokensSold,
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff,
now,
tokenAddr
)
returns (uint256 ret) {
tokensSold = ret;
} catch Error(string memory reason) {
_revertMsg("tokenToTokenSwapOutput", reason);
} catch {
_revertMsg("tokenToTokenSwapOutput");
}
IERC20(token).safeApprove(address(uniswap), 0);
// Update involved token
_updateToken(tokenAddr);
}
function _getExchange(address token)
internal
view
returns (IUniswapExchange uniswap)
{
IUniswapFactory uniswapFactory = IUniswapFactory(UNISWAP_FACTORY);
uniswap = IUniswapExchange(uniswapFactory.getExchange(token));
}
}
| Update involved token | _updateToken(tokenAddr);
| 1,034,818 | [
1,
1891,
24589,
1147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
389,
2725,
1345,
12,
2316,
3178,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/5/0x0A6d1cF79a3121f54aFFCb3d0D97958EEdB1B087/sources/_manifoldxyz/creator-core-extensions-solidity/contracts/libraries/delegation-registry/DelegationRegistry.sol | * @inheritdoc IDelegationRegistry/ | function checkDelegateForToken(address delegate, address vault, address contract_, uint256 tokenId)
public
view
override
returns (bool)
{
bytes32 delegateHash = keccak256(
abi.encode(delegate, vault, contract_, tokenId, vaultVersion[vault], delegateVersion[vault][delegate])
);
return delegations[vault][vaultVersion[vault]].contains(delegateHash)
? true
: checkDelegateForContract(delegate, vault, contract_);
}
| 1,886,851 | [
1,
36,
10093,
1599,
13451,
367,
4243,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
866,
9586,
1290,
1345,
12,
2867,
7152,
16,
1758,
9229,
16,
1758,
6835,
67,
16,
2254,
5034,
1147,
548,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
3849,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
1731,
1578,
7152,
2310,
273,
417,
24410,
581,
5034,
12,
203,
5411,
24126,
18,
3015,
12,
22216,
16,
9229,
16,
6835,
67,
16,
1147,
548,
16,
9229,
1444,
63,
26983,
6487,
7152,
1444,
63,
26983,
6362,
22216,
5717,
203,
3639,
11272,
203,
3639,
327,
11158,
1012,
63,
26983,
6362,
26983,
1444,
63,
26983,
65,
8009,
12298,
12,
22216,
2310,
13,
203,
5411,
692,
638,
203,
5411,
294,
866,
9586,
1290,
8924,
12,
22216,
16,
9229,
16,
6835,
67,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.4.23;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title 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;
}
}
interface TokenInterface {
function totalSupply() external constant returns (uint);
function balanceOf(address tokenOwner) external constant returns (uint balance);
function allowance(address tokenOwner, address spender) external constant 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 burn(uint256 _value) external;
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
event Burn(address indexed burner, uint256 value);
}
contract URUNCrowdsale is Ownable{
using SafeMath for uint256;
// The token being sold
TokenInterface public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// how many token units a buyer gets per wei
uint256 public ratePerWei = 800;
// amount of raised money in wei
uint256 public weiRaised;
uint256 public TOKENS_SOLD;
uint256 minimumContributionPresalePhase1 = 2 * 10 ** 18; //2 eth is the minimum contribution in presale phase 1
uint256 minimumContributionPresalePhase2 = 1 * 10 ** 18; //1 eth is the minimum contribution in presale phase 2
uint256 maxTokensToSaleInClosedPreSale;
uint256 bonusInPreSalePhase1;
uint256 bonusInPreSalePhase2;
bool isCrowdsalePaused = false;
uint256 totalDurationInDays = 31 days;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
constructor(uint256 _startTime, address _wallet, address _tokenAddress) public
{
require(_wallet != 0x0);
require(_startTime >=now);
startTime = _startTime;
endTime = startTime + totalDurationInDays;
require(endTime >= startTime);
owner = _wallet;
maxTokensToSaleInClosedPreSale = 60000000 * 10 ** 18;
bonusInPreSalePhase1 = 50;
bonusInPreSalePhase2 = 40;
token = TokenInterface(_tokenAddress);
}
// fallback function can be used to buy tokens
function () public payable {
buyTokens(msg.sender);
}
function determineBonus(uint tokens) internal view returns (uint256 bonus)
{
uint256 timeElapsed = now - startTime;
uint256 timeElapsedInDays = timeElapsed.div(1 days);
//Closed pre-sale phase 1 (15 days)
if (timeElapsedInDays <15)
{
bonus = tokens.mul(bonusInPreSalePhase1);
bonus = bonus.div(100);
require (TOKENS_SOLD.add(tokens.add(bonus)) <= maxTokensToSaleInClosedPreSale);
}
//Closed pre-sale phase 2 (16 days)
else if (timeElapsedInDays >=15 && timeElapsedInDays <31)
{
bonus = tokens.mul(bonusInPreSalePhase2);
bonus = bonus.div(100);
require (TOKENS_SOLD.add(tokens.add(bonus)) <= maxTokensToSaleInClosedPreSale);
}
else
{
bonus = 0;
}
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != 0x0);
require(isCrowdsalePaused == false);
require(validPurchase());
require(isWithinContributionRange());
require(TOKENS_SOLD<maxTokensToSaleInClosedPreSale);
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(ratePerWei);
uint256 bonus = determineBonus(tokens);
tokens = tokens.add(bonus);
// update state
weiRaised = weiRaised.add(weiAmount);
token.transfer(beneficiary,tokens);
emit TokenPurchase(owner, beneficiary, weiAmount, tokens);
TOKENS_SOLD = TOKENS_SOLD.add(tokens);
forwardFunds();
}
// send ether to the fund collection wallet
function forwardFunds() internal {
owner.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
return now > endTime;
}
/**
* function to change the end timestamp of the ico
* can only be called by owner wallet
**/
function changeEndDate(uint256 endTimeUnixTimestamp) public onlyOwner{
endTime = endTimeUnixTimestamp;
}
/**
* function to change the start timestamp of the ico
* can only be called by owner wallet
**/
function changeStartDate(uint256 startTimeUnixTimestamp) public onlyOwner{
startTime = startTimeUnixTimestamp;
}
/**
* function to change the rate of tokens
* can only be called by owner wallet
**/
function setPriceRate(uint256 newPrice) public onlyOwner {
ratePerWei = newPrice;
}
/**
* function to pause the crowdsale
* can only be called from owner wallet
**/
function pauseCrowdsale() public onlyOwner {
isCrowdsalePaused = true;
}
/**
* function to resume the crowdsale if it is paused
* can only be called from owner wallet
**/
function resumeCrowdsale() public onlyOwner {
isCrowdsalePaused = false;
}
/**
* function to check whether the sent amount is within contribution range or not
**/
function isWithinContributionRange() internal constant returns (bool)
{
uint timePassed = now.sub(startTime);
timePassed = timePassed.div(1 days);
if (timePassed<15)
require(msg.value>=minimumContributionPresalePhase1);
else if (timePassed>=15 && timePassed<31)
require(msg.value>=minimumContributionPresalePhase2);
else
revert(); // off time - no sales during other time periods
return true;
}
/**
* function through which owner can take back the tokens from the contract
**/
function takeTokensBack() public onlyOwner
{
uint remainingTokensInTheContract = token.balanceOf(address(this));
token.transfer(owner,remainingTokensInTheContract);
}
/**
* function through which owner can transfer the tokens to any address
* use this which to properly display the tokens that have been sold via ether or other payments
**/
function manualTokenTransfer(address receiver, uint value) public onlyOwner
{
value = value * 10 ** 18;
token.transfer(receiver,value);
TOKENS_SOLD = TOKENS_SOLD.add(value);
}
} | The token being sold start and end timestamps where investments are allowed (both inclusive) how many token units a buyer gets per wei amount of raised money in wei | contract URUNCrowdsale is Ownable{
using SafeMath for uint256;
TokenInterface public token;
uint256 public startTime;
uint256 public endTime;
uint256 public ratePerWei = 800;
uint256 public weiRaised;
uint256 public TOKENS_SOLD;
uint256 maxTokensToSaleInClosedPreSale;
uint256 bonusInPreSalePhase1;
uint256 bonusInPreSalePhase2;
bool isCrowdsalePaused = false;
uint256 totalDurationInDays = 31 days;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
constructor(uint256 _startTime, address _wallet, address _tokenAddress) public
{
require(_wallet != 0x0);
require(_startTime >=now);
startTime = _startTime;
endTime = startTime + totalDurationInDays;
require(endTime >= startTime);
owner = _wallet;
maxTokensToSaleInClosedPreSale = 60000000 * 10 ** 18;
bonusInPreSalePhase1 = 50;
bonusInPreSalePhase2 = 40;
token = TokenInterface(_tokenAddress);
}
function () public payable {
buyTokens(msg.sender);
}
function determineBonus(uint tokens) internal view returns (uint256 bonus)
{
uint256 timeElapsed = now - startTime;
uint256 timeElapsedInDays = timeElapsed.div(1 days);
if (timeElapsedInDays <15)
{
bonus = tokens.mul(bonusInPreSalePhase1);
bonus = bonus.div(100);
require (TOKENS_SOLD.add(tokens.add(bonus)) <= maxTokensToSaleInClosedPreSale);
}
{
bonus = tokens.mul(bonusInPreSalePhase2);
bonus = bonus.div(100);
require (TOKENS_SOLD.add(tokens.add(bonus)) <= maxTokensToSaleInClosedPreSale);
}
else
{
bonus = 0;
}
}
function determineBonus(uint tokens) internal view returns (uint256 bonus)
{
uint256 timeElapsed = now - startTime;
uint256 timeElapsedInDays = timeElapsed.div(1 days);
if (timeElapsedInDays <15)
{
bonus = tokens.mul(bonusInPreSalePhase1);
bonus = bonus.div(100);
require (TOKENS_SOLD.add(tokens.add(bonus)) <= maxTokensToSaleInClosedPreSale);
}
{
bonus = tokens.mul(bonusInPreSalePhase2);
bonus = bonus.div(100);
require (TOKENS_SOLD.add(tokens.add(bonus)) <= maxTokensToSaleInClosedPreSale);
}
else
{
bonus = 0;
}
}
else if (timeElapsedInDays >=15 && timeElapsedInDays <31)
function determineBonus(uint tokens) internal view returns (uint256 bonus)
{
uint256 timeElapsed = now - startTime;
uint256 timeElapsedInDays = timeElapsed.div(1 days);
if (timeElapsedInDays <15)
{
bonus = tokens.mul(bonusInPreSalePhase1);
bonus = bonus.div(100);
require (TOKENS_SOLD.add(tokens.add(bonus)) <= maxTokensToSaleInClosedPreSale);
}
{
bonus = tokens.mul(bonusInPreSalePhase2);
bonus = bonus.div(100);
require (TOKENS_SOLD.add(tokens.add(bonus)) <= maxTokensToSaleInClosedPreSale);
}
else
{
bonus = 0;
}
}
function determineBonus(uint tokens) internal view returns (uint256 bonus)
{
uint256 timeElapsed = now - startTime;
uint256 timeElapsedInDays = timeElapsed.div(1 days);
if (timeElapsedInDays <15)
{
bonus = tokens.mul(bonusInPreSalePhase1);
bonus = bonus.div(100);
require (TOKENS_SOLD.add(tokens.add(bonus)) <= maxTokensToSaleInClosedPreSale);
}
{
bonus = tokens.mul(bonusInPreSalePhase2);
bonus = bonus.div(100);
require (TOKENS_SOLD.add(tokens.add(bonus)) <= maxTokensToSaleInClosedPreSale);
}
else
{
bonus = 0;
}
}
function buyTokens(address beneficiary) public payable {
require(beneficiary != 0x0);
require(isCrowdsalePaused == false);
require(validPurchase());
require(isWithinContributionRange());
require(TOKENS_SOLD<maxTokensToSaleInClosedPreSale);
uint256 weiAmount = msg.value;
uint256 tokens = weiAmount.mul(ratePerWei);
uint256 bonus = determineBonus(tokens);
tokens = tokens.add(bonus);
weiRaised = weiRaised.add(weiAmount);
token.transfer(beneficiary,tokens);
emit TokenPurchase(owner, beneficiary, weiAmount, tokens);
TOKENS_SOLD = TOKENS_SOLD.add(tokens);
forwardFunds();
}
function forwardFunds() internal {
owner.transfer(msg.value);
}
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
function hasEnded() public constant returns (bool) {
return now > endTime;
}
function changeEndDate(uint256 endTimeUnixTimestamp) public onlyOwner{
endTime = endTimeUnixTimestamp;
}
function changeStartDate(uint256 startTimeUnixTimestamp) public onlyOwner{
startTime = startTimeUnixTimestamp;
}
function setPriceRate(uint256 newPrice) public onlyOwner {
ratePerWei = newPrice;
}
function pauseCrowdsale() public onlyOwner {
isCrowdsalePaused = true;
}
function resumeCrowdsale() public onlyOwner {
isCrowdsalePaused = false;
}
function isWithinContributionRange() internal constant returns (bool)
{
uint timePassed = now.sub(startTime);
timePassed = timePassed.div(1 days);
if (timePassed<15)
require(msg.value>=minimumContributionPresalePhase1);
else if (timePassed>=15 && timePassed<31)
require(msg.value>=minimumContributionPresalePhase2);
else
return true;
}
function takeTokensBack() public onlyOwner
{
uint remainingTokensInTheContract = token.balanceOf(address(this));
token.transfer(owner,remainingTokensInTheContract);
}
function manualTokenTransfer(address receiver, uint value) public onlyOwner
{
value = value * 10 ** 18;
token.transfer(receiver,value);
TOKENS_SOLD = TOKENS_SOLD.add(value);
}
} | 15,098,178 | [
1,
1986,
1147,
3832,
272,
1673,
787,
471,
679,
11267,
1625,
2198,
395,
1346,
854,
2935,
261,
18237,
13562,
13,
3661,
4906,
1147,
4971,
279,
27037,
5571,
1534,
732,
77,
3844,
434,
11531,
15601,
316,
732,
77,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
6835,
1618,
21163,
492,
2377,
5349,
353,
14223,
6914,
95,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
7010,
225,
29938,
1071,
1147,
31,
203,
203,
225,
2254,
5034,
1071,
8657,
31,
203,
225,
2254,
5034,
1071,
13859,
31,
203,
203,
203,
225,
2254,
5034,
1071,
4993,
2173,
3218,
77,
273,
1725,
713,
31,
203,
203,
225,
2254,
5034,
1071,
732,
77,
12649,
5918,
31,
203,
203,
225,
2254,
5034,
1071,
14275,
55,
67,
55,
11846,
31,
203,
21281,
21281,
225,
2254,
5034,
943,
5157,
774,
30746,
382,
7395,
1386,
30746,
31,
203,
21281,
225,
2254,
5034,
324,
22889,
382,
1386,
30746,
11406,
21,
31,
203,
225,
2254,
5034,
324,
22889,
382,
1386,
30746,
11406,
22,
31,
203,
21281,
225,
1426,
25249,
492,
2377,
5349,
28590,
273,
629,
31,
203,
21281,
225,
2254,
5034,
2078,
5326,
382,
9384,
273,
8231,
4681,
31,
203,
21281,
225,
871,
3155,
23164,
12,
2867,
8808,
5405,
343,
14558,
16,
1758,
8808,
27641,
74,
14463,
814,
16,
2254,
5034,
460,
16,
2254,
5034,
3844,
1769,
203,
203,
225,
3885,
12,
11890,
5034,
389,
1937,
950,
16,
1758,
389,
19177,
16,
1758,
389,
2316,
1887,
13,
1071,
7010,
225,
288,
203,
377,
203,
565,
2583,
24899,
19177,
480,
374,
92,
20,
1769,
203,
565,
2583,
24899,
1937,
950,
1545,
3338,
1769,
203,
565,
8657,
273,
389,
1937,
950,
31,
21281,
203,
565,
13859,
273,
8657,
397,
2078,
5326,
382,
9384,
31,
203,
565,
2583,
12,
409,
950,
1545,
8657,
1769,
203,
27699,
565,
3410,
273,
389,
19177,
31,
2
]
|
// GoGoPay Token
// Symbol : GoGoPay
// Name : GoPay
// Total supply: 16,000,000,000
// Decimals : 18
//
//
// GoGoPay - Technology Which Will Change The World
//
// GoGopay.com // GoPayForum.com
//
//
contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
//if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
//if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract GoGoPay is StandardToken { // CHANGE THIS. Update the contract name.
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; // Token Name
uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18
string public symbol; // An identifier: eg SBX, XPR etc..
string public version = 'H1.0';
uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH?
uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here.
address public fundsWallet; // Where should the raised ETH go?
// This is a constructor function
// which means the following function name has to match the contract name declared above
function GoGoPay() {
balances[msg.sender] = 16000000000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS)
totalSupply = 16000000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS)
name = "GoGoPay"; // Set the name for display purposes (CHANGE THIS)
decimals = 18; // Amount of decimals for display purposes (CHANGE THIS)
symbol = "GoPay"; // Set the symbol for display purposes (CHANGE THIS)
unitsOneEthCanBuy = 20000000; // Set the price of your token for the ICO (CHANGE THIS)
fundsWallet = msg.sender; // The owner of the contract gets ETH
}
function() payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
require(balances[fundsWallet] >= amount);
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain
//Transfer ether to fundsWallet
fundsWallet.transfer(msg.value);
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | Update total supply (1000 for example) (CHANGE THIS)
| totalSupply = 16000000000000000000000000000; | 4,810,970 | [
1,
1891,
2078,
14467,
261,
18088,
364,
3454,
13,
261,
14473,
20676,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2078,
3088,
1283,
273,
2872,
12648,
12648,
12648,
3784,
31,
7682,
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/97/0x1BC5eecb949b117E703e62B21F2fFA04127c3526/sources/project_/contracts/MuonNodeManager.sol | * @dev Returns list of all nodes./ | function getAllNodes() public view returns(
Node[] memory allNodes
){
allNodes = new Node[](lastNodeId);
for(uint256 i = 1; i <= lastNodeId; i++){
allNodes[i-1] = nodes[i];
}
}
| 5,023,705 | [
1,
1356,
666,
434,
777,
2199,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
5514,
3205,
1435,
1071,
1476,
1135,
12,
203,
3639,
2029,
8526,
3778,
777,
3205,
203,
565,
262,
95,
203,
3639,
777,
3205,
273,
394,
2029,
8526,
12,
2722,
15883,
1769,
203,
3639,
364,
12,
11890,
5034,
277,
273,
404,
31,
277,
1648,
1142,
15883,
31,
277,
27245,
95,
203,
5411,
777,
3205,
63,
77,
17,
21,
65,
273,
2199,
63,
77,
15533,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/137/0x7C328a6097F5707171992f53C1e48564E5EB7b36/sources/contracts/MarshmallowMatic.sol | * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea./ | function _msgSender()
internal
override
view
returns (address payable sender)
{
return ContextMixin.msgSender();
}
| 4,666,958 | [
1,
2503,
353,
1399,
3560,
434,
1234,
18,
15330,
487,
8938,
8462,
1404,
506,
3271,
635,
326,
2282,
1147,
3410,
16,
1496,
635,
3502,
1761,
69,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
389,
3576,
12021,
1435,
203,
565,
2713,
203,
565,
3849,
203,
565,
1476,
203,
565,
1135,
261,
2867,
8843,
429,
5793,
13,
203,
225,
288,
203,
565,
327,
1772,
14439,
18,
3576,
12021,
5621,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
/// @title Simple NFT Minter
/// @author Gianluca Toffoletto
/// @notice Mint NFTs from uploaded images.
/// Developed for the final project for the Consensys Academy's 2021 blockchain developer bootcamp
/// @dev The contract leverages on OpenZeppelin smart contract libraries
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
contract SimpleNFT is ERC721, ERC721URIStorage, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
/// @dev this role is not needed to use the mint function
/// @notice creates a role to identify "patrons" who made a donation (might be used to reward with "patron badges", e.g.)
mapping(address => bool) public patronRole;
/// @notice a getter function to check if an account is a patron, not currently used
/// @param _account the account to query
function getPatronRole(address _account) public view returns (bool) {
return patronRole[_account];
}
modifier minumumDonation() {
require(msg.value >= 2000000000, "Donation should be at least 2 gwei.");
_;
}
/// @notice function to donate at least 2 gweis, assigns the "patron" role
/// @param _patron the account to add as a patron
/// change to donate
function Donate(address _patron) public payable minumumDonation {
require(_patron != address(0));
patronRole[_patron] = true;
}
/// @dev constructor for the SimpleNFT contract
constructor() ERC721("SimpleNFT", "SNFT") {}
/// @notice Will be concatenated with token IDs to generate the token URIs (from OpenZeppelin ERC721)
function _baseURI() internal pure override returns (string memory) {
return "ipfs://";
}
/// @dev Mints the token to the msg.sender
/// @param uri token's URI
/// @param to address the NFT is minted to
function safeMint(address to, string memory uri) public {
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(to, tokenId);
_setTokenURI(tokenId, uri);
}
/// @dev Override required by Solidity, recommeded by OpenZeppelin
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
/// @dev Override required by Solidity, recommeded by OpenZeppelin
/// @return tokenId
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
/// @dev receive and fallback to allow the contract to receive data/messages
receive() external payable {
}
fallback() external payable {
}
/// @dev Function to withdraw ether from contract address
/// @notice only the owner can withdraw the donations
function withdrawDonations() public onlyOwner {
(bool success, ) = msg.sender.call{value: address(this).balance}("");
require(success, "Withdrawal failed");
}
} | @dev Function to withdraw ether from contract address @notice only the owner can withdraw the donations | function withdrawDonations() public onlyOwner {
require(success, "Withdrawal failed");
}
| 5,400,311 | [
1,
2083,
358,
598,
9446,
225,
2437,
628,
6835,
1758,
225,
1338,
326,
3410,
848,
598,
9446,
326,
2727,
1012,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
565,
445,
598,
9446,
22293,
1012,
1435,
1071,
1338,
5541,
288,
203,
3639,
2583,
12,
4768,
16,
315,
1190,
9446,
287,
2535,
8863,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xd81b3000D6Cad7af85E9939AfAb1243B56618EA9/sources/VFIN.sol | * @dev Initialize ERC1400. @param newOwner Address whom contract ownership shall be transferred to. @param seller Address who will sell tokens./ | {
require(newOwner != address(0), "VFIN: wrong address");
require(seller != address(0), "VFIN: wrong address");
transferOwnership(newOwner);
_issueByPartition(VFIN_DEFAULT_PARTITION, msg.sender, newOwner, ISSUED_TOKENS, "");
_isIssuable = false;
_transferByDefaultPartitions(msg.sender, newOwner, seller, FOR_SALE_TOKENS, "");
}
| 4,032,189 | [
1,
7520,
4232,
39,
3461,
713,
18,
225,
394,
5541,
5267,
600,
362,
6835,
23178,
24315,
506,
906,
4193,
358,
18,
225,
29804,
5267,
10354,
903,
357,
80,
2430,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
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,
288,
203,
3639,
2583,
12,
2704,
5541,
480,
1758,
12,
20,
3631,
315,
58,
7263,
30,
7194,
1758,
8863,
203,
3639,
2583,
12,
1786,
749,
480,
1758,
12,
20,
3631,
315,
58,
7263,
30,
7194,
1758,
8863,
203,
203,
3639,
7412,
5460,
12565,
12,
2704,
5541,
1769,
203,
203,
3639,
389,
13882,
858,
7003,
12,
58,
7263,
67,
5280,
67,
15055,
7022,
16,
1234,
18,
15330,
16,
394,
5541,
16,
467,
1260,
1821,
40,
67,
8412,
55,
16,
1408,
1769,
203,
3639,
389,
291,
7568,
89,
429,
273,
629,
31,
203,
203,
3639,
389,
13866,
858,
1868,
13738,
12,
3576,
18,
15330,
16,
394,
5541,
16,
29804,
16,
12108,
67,
5233,
900,
67,
8412,
55,
16,
1408,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract SimpleStorage {
struct Person {
uint256 favoriteNumber;
string name;
}
uint256 public favoriteNumber;
Person[] public people;
mapping(string => uint256) public nameToFavoriteNumber;
function store(uint256 _favoriteNumber) public {
favoriteNumber = _favoriteNumber;
}
// View functions just read state and can do math and return stuff.
function retrieve() public view returns(uint256) {
return favoriteNumber;
}
// Pure functions just do math and return stuff. Don't read state
function addTwo(uint256 _input) public pure returns(uint256) {
return _input + 2;
}
function addPerson(uint256 _number, string memory _name) public {
people.push(Person(_number, _name));
nameToFavoriteNumber[_name] = _number;
}
}
| View functions just read state and can do math and return stuff. | function retrieve() public view returns(uint256) {
return favoriteNumber;
}
| 5,413,975 | [
1,
1767,
4186,
2537,
855,
919,
471,
848,
741,
4233,
471,
327,
10769,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
4614,
1435,
1071,
1476,
1135,
12,
11890,
5034,
13,
288,
203,
565,
327,
30705,
1854,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
import "./USDSatMetadata.sol";
import "./Ownable.sol";
import "./ERC721.sol";
import "./ReentrancyGuard.sol";
import "./ERC721Enumerable.sol";
/// ``..
/// `.` `````.``.-````-`` `.`
/// ` ``````.`..///.-..----. --..--`.-....`..-.```` ```
/// `` `.`..--...`:::/::-``..``..:-.://///---..-....-----
/// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-``
/// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.`
/// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.````
/// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. `
/// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. ``
/// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..`
/// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````...
/// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` `
/// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `.
/// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .`
/// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` `
/// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.`
/// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--.
/// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/
/// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-`
/// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:`
/// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--:
/// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/
/// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -`
/// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.-
/// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::`
/// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:`
/// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.`
/// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-``
/// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-`
/// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-``
/// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/`
/// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s-
/// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so
/// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o`
/// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+-
/// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs.
/// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh`
/// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms`
/// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy:
/// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-`
/// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+`
/// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:.
/// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/`
/// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://`
/// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++
/// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+
/// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/-
/// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/://
/// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:-
/// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-`
/// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-`
/// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//`
/// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++
/// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+
/// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy.
/// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+.
/// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+.
/// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.`
/// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.`
/// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ```
/// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.``
/// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` `
/// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` `
/// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. `
/// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` `
/// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.``
/// @title Dollars Nakamoto by Pascal Boyart
/// @author jolan.eth
/// @notice This contract will allow you to yield farm Dollars Nakamoto NFT.
/// During epoch 0 you will be able to mint a Genesis NFT,
/// Over time, epoch will increment allowing you to mint more editions.
/// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT.
/// Generations editions do not allow you to mint other generations.
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard {
string SYMBOL = "USDSat";
string NAME = "Dollars Nakamoto";
string ContractCID;
/// @notice Address used to sign NFT on mint
address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902;
/// @notice Ether shareholder address
address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3;
/// @notice Ether shareholder address
address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2;
/// @notice Equity per shareholder in %
uint256 public SHARE_PBOY = 90;
/// @notice Equity per shareholder in %
uint256 public SHARE_JOLAN = 10;
/// @notice Mapping used to represent allowed addresses to call { mintGenesis }
mapping (address => bool) public _allowList;
/// @notice Represent the current epoch
uint256 public epoch = 0;
/// @notice Represent the maximum epoch possible
uint256 public epochMax = 10;
/// @notice Represent the block length of an epoch
uint256 public epochLen = 41016;
/// @notice Index of the NFT
/// @dev Start at 1 because var++
uint256 public tokenId = 1;
/// @notice Index of the Genesis NFT
/// @dev Start at 0 because ++var
uint256 public genesisId = 0;
/// @notice Index of the Generation NFT
/// @dev Start at 0 because ++var
uint256 public generationId = 0;
/// @notice Maximum total supply
uint256 public maxTokenSupply = 2100;
/// @notice Maximum Genesis supply
uint256 public maxGenesisSupply = 210;
/// @notice Maximum supply per generation
uint256 public maxGenerationSupply = 210;
/// @notice Price of the Genesis NFT (Generations NFT are free)
uint256 public genesisPrice = 0.5 ether;
/// @notice Define the ending block
uint256 public blockOmega;
/// @notice Define the starting block
uint256 public blockGenesis;
/// @notice Define in which block the Meta must occur
uint256 public blockMeta;
/// @notice Used to inflate blockMeta each epoch incrementation
uint256 public inflateRatio = 2;
/// @notice Open Genesis mint when true
bool public genesisMintAllowed = false;
/// @notice Open Generation mint when true
bool public generationMintAllowed = false;
/// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch
mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry;
event Omega(uint256 _blockNumber);
event Genesis(uint256 indexed _epoch, uint256 _blockNumber);
event Meta(uint256 indexed _epoch, uint256 _blockNumber);
event Withdraw(uint256 indexed _share, address _shareholder);
event Shareholder(uint256 indexed _sharePercent, address _shareholder);
event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio);
event PermanentURI(string _value, uint256 indexed _id);
event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner);
event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber);
constructor() ERC721(NAME, SYMBOL) {}
// Withdraw functions *************************************************
/// @notice Allow Pboy to modify ADDRESS_PBOY
/// This function is dedicated to the represented shareholder according to require().
function setPboy(address PBOY)
public {
require(msg.sender == ADDRESS_PBOY, "error msg.sender");
ADDRESS_PBOY = PBOY;
emit Shareholder(SHARE_PBOY, ADDRESS_PBOY);
}
/// @notice Allow Jolan to modify ADDRESS_JOLAN
/// This function is dedicated to the represented shareholder according to require().
function setJolan(address JOLAN)
public {
require(msg.sender == ADDRESS_JOLAN, "error msg.sender");
ADDRESS_JOLAN = JOLAN;
emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN);
}
/// @notice Used to withdraw ETH balance of the contract, this function is dedicated
/// to contract owner according to { onlyOwner } modifier.
function withdrawEquity()
public onlyOwner nonReentrant {
uint256 balance = address(this).balance;
address[2] memory shareholders = [
ADDRESS_PBOY,
ADDRESS_JOLAN
];
uint256[2] memory _shares = [
SHARE_PBOY * balance / 100,
SHARE_JOLAN * balance / 100
];
uint i = 0;
while (i < 2) {
require(payable(shareholders[i]).send(_shares[i]));
emit Withdraw(_shares[i], shareholders[i]);
i++;
}
}
// Epoch functions ****************************************************
/// @notice Used to manage authorization and reentrancy of the genesis NFT mint
/// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry }
function genesisController(uint256 _genesisId)
private {
require(epoch == 0, "error epoch");
require(genesisId <= maxGenesisSupply, "error genesisId");
require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry");
/// @dev Set { _genesisId } for { epoch } as true
epochMintingRegistry[epoch][_genesisId] = true;
/// @dev When { genesisId } reaches { maxGenesisSupply } the function
/// will compute the data to increment the epoch according
///
/// { blockGenesis } is set only once, at this time
/// { blockMeta } is set to { blockGenesis } because epoch=0
/// Then it is computed into the function epochRegulator()
///
/// Once the epoch is regulated, the new generation start
/// straight away, { generationMintAllowed } is set to true
if (genesisId == maxGenesisSupply) {
blockGenesis = block.number;
blockMeta = blockGenesis;
emit Genesis(epoch, blockGenesis);
epochRegulator();
}
}
/// @notice Used to manage authorization and reentrancy of the Generation NFT mint
/// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance
function generationController(uint256 _genesisId)
private {
require(blockGenesis > 0, "error blockGenesis");
require(blockMeta > 0, "error blockMeta");
require(blockOmega > 0, "error blockOmega");
/// @dev If { block.number } >= { blockMeta } the function
/// will compute the data to increment the epoch according
///
/// Once the epoch is regulated, the new generation start
/// straight away, { generationMintAllowed } is set to true
///
/// { generationId } is reset to 1
if (block.number >= blockMeta) {
epochRegulator();
generationId = 1;
}
/// @dev Be sure the mint is open if condition are favorable
if (block.number < blockMeta && generationId <= maxGenerationSupply) {
generationMintAllowed = true;
}
require(maxTokenSupply >= tokenId, "error maxTokenSupply");
require(epoch > 0 && epoch < epochMax, "error epoch");
require(ownerOf(_genesisId) == msg.sender, "error ownerOf");
require(generationMintAllowed, "error generationMintAllowed");
require(generationId <= maxGenerationSupply, "error generationId");
require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry");
require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry");
/// @dev Set { _genesisId } for { epoch } as true
epochMintingRegistry[epoch][_genesisId] = true;
/// @dev If { generationId } reaches { maxGenerationSupply } the modifier
/// will set { generationMintAllowed } to false to stop the mint
/// on this generation
///
/// { generationId } is reset to 0
///
/// This condition will not block the function because as long as
/// { block.number } >= { blockMeta } minting will reopen
/// according and this condition will become obsolete until
/// the condition is reached again
if (generationId == maxGenerationSupply) {
generationMintAllowed = false;
generationId = 0;
}
}
/// @notice Used to protect epoch block length from difficulty bomb of the
/// Ethereum network. A difficulty bomb heavily increases the difficulty
/// on the network, likely also causing an increase in block time.
/// If the block time increases too much, the epoch generation could become
/// exponentially higher than what is desired, ending with an undesired Ice-Age.
/// To protect against this, the emergencySecure() function is allowed to
/// manually reconfigure the epoch block length and the block Meta
/// to match the network conditions if necessary.
///
/// It can also be useful if the block time decreases for some reason with consensus change.
///
/// This function is dedicated to contract owner according to { onlyOwner } modifier
function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio)
public onlyOwner {
require(epoch > 0, "error epoch");
require(_epoch > 0, "error _epoch");
require(maxTokenSupply >= tokenId, "error maxTokenSupply");
epoch = _epoch;
epochLen = _epochLen;
blockMeta = _blockMeta;
inflateRatio = _inflateRatio;
computeBlockOmega();
emit Securized(epoch, epochLen, blockMeta, inflateRatio);
}
/// @notice Used to compute blockOmega() function, { blockOmega } represents
/// the block when it won't ever be possible to mint another Dollars Nakamoto NFT.
/// It is possible to be computed because of the deterministic state of the current protocol
/// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega
function computeBlockOmega()
private {
uint256 i = 0;
uint256 _blockMeta = 0;
uint256 _epochLen = epochLen;
while (i < epochMax) {
if (i > 0) _epochLen *= inflateRatio;
if (i == 9) {
blockOmega = blockGenesis + _blockMeta;
emit Omega(blockOmega);
break;
}
_blockMeta += _epochLen;
i++;
}
}
/// @notice Used to regulate the epoch incrementation and block computation, known as Metas
/// @dev When epoch=0, the { blockOmega } will be computed
/// When epoch!=0 the block length { epochLen } will be multiplied
/// by { inflateRatio } thus making the block length required for each
/// epoch longer according
///
/// { blockMeta } += { epochLen } result the exact block of the next Meta
/// Allow generation mint after incrementing the epoch
function epochRegulator()
private {
if (epoch == 0) computeBlockOmega();
if (epoch > 0) epochLen *= inflateRatio;
blockMeta += epochLen;
emit Meta(epoch, blockMeta);
epoch++;
if (block.number >= blockMeta && epoch < epochMax) {
epochRegulator();
}
generationMintAllowed = true;
}
// Mint functions *****************************************************
/// @notice Used to add/remove address from { _allowList }
function setBatchGenesisAllowance(address[] memory batch)
public onlyOwner {
uint len = batch.length;
require(len > 0, "error len");
uint i = 0;
while (i < len) {
_allowList[batch[i]] = _allowList[batch[i]] ?
false : true;
i++;
}
}
/// @notice Used to transfer { _allowList } slot to another address
function transferListSlot(address to)
public {
require(epoch == 0, "error epoch");
require(_allowList[msg.sender], "error msg.sender");
require(!_allowList[to], "error to");
_allowList[msg.sender] = false;
_allowList[to] = true;
}
/// @notice Used to open the mint of Genesis NFT
function setGenesisMint()
public onlyOwner {
genesisMintAllowed = true;
}
/// @notice Used to gift Genesis NFT, this function is dedicated
/// to contract owner according to { onlyOwner } modifier
function giftGenesis(address to)
public onlyOwner {
uint256 _genesisId = ++genesisId;
setMetadata(tokenId, _genesisId, epoch);
genesisController(_genesisId);
mintUSDSat(to, tokenId++);
}
/// @notice Used to mint Genesis NFT, this function is payable
/// the price of this function is equal to { genesisPrice },
/// require to be present on { _allowList } to call
function mintGenesis()
public payable {
uint256 _genesisId = ++genesisId;
setMetadata(tokenId, _genesisId, epoch);
genesisController(_genesisId);
require(genesisMintAllowed, "error genesisMintAllowed");
require(_allowList[msg.sender], "error allowList");
require(genesisPrice == msg.value, "error genesisPrice");
_allowList[msg.sender] = false;
mintUSDSat(msg.sender, tokenId++);
}
/// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function
function giftGenerations(uint256 _genesisId, address to)
public {
++generationId;
generationController(_genesisId);
setMetadata(tokenId, _genesisId, epoch);
mintUSDSat(to, tokenId++);
}
/// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function
function mintGenerations(uint256 _genesisId)
public {
++generationId;
generationController(_genesisId);
setMetadata(tokenId, _genesisId, epoch);
mintUSDSat(msg.sender, tokenId++);
}
/// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to },
/// this is to ensure the token creation is signed with { ADDRESS_SIGN }
/// This function is private and can be only called by the contract
function mintUSDSat(address to, uint256 _tokenId)
private {
emit PermanentURI(_compileMetadata(_tokenId), _tokenId);
_safeMint(ADDRESS_SIGN, _tokenId);
emit Signed(epoch, _tokenId, block.number);
_safeTransfer(ADDRESS_SIGN, to, _tokenId, "");
emit Minted(epoch, _tokenId, to);
}
// Contract URI functions *********************************************
/// @notice Used to set the { ContractCID } metadata from ipfs,
/// this function is dedicated to contract owner according
/// to { onlyOwner } modifier
function setContractCID(string memory CID)
public onlyOwner {
ContractCID = string(abi.encodePacked("ipfs://", CID));
}
/// @notice Used to render { ContractCID } as { contractURI } according to
/// Opensea contract metadata standard
function contractURI()
public view virtual returns (string memory) {
return ContractCID;
}
// Utilitaries functions **********************************************
/// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry }
function getMapRegisteryForEpoch(uint256 _epoch)
public view returns (bool[210] memory result) {
uint i = 1;
while (i <= maxGenesisSupply) {
result[i] = epochMintingRegistry[_epoch][i];
i++;
}
}
/// @notice Used to fetch all { tokenIds } from { owner }
function exposeHeldIds(address owner)
public view returns(uint[] memory) {
uint tokenCount = balanceOf(owner);
uint[] memory tokenIds = new uint[](tokenCount);
uint i = 0;
while (i < tokenCount) {
tokenIds[i] = tokenOfOwnerByIndex(owner, i);
i++;
}
return tokenIds;
}
// ERC721 Spec functions **********************************************
/// @notice Used to render metadata as { tokenURI } according to ERC721 standard
function tokenURI(uint256 _tokenId)
public view virtual override returns (string memory) {
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
return _compileMetadata(_tokenId);
}
/// @dev ERC721 required override
function _beforeTokenTransfer(address from, address to, uint256 _tokenId)
internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, _tokenId);
}
/// @dev ERC721 required override
function supportsInterface(bytes4 interfaceId)
public view override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
} | @notice Used to manage authorization and reentrancy of the genesis NFT mint @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } @dev Set { _genesisId } for { epoch } as true @dev When { genesisId } reaches { maxGenesisSupply } the function will compute the data to increment the epoch according { blockGenesis } is set only once, at this time { blockMeta } is set to { blockGenesis } because epoch=0 Then it is computed into the function epochRegulator() Once the epoch is regulated, the new generation start straight away, { generationMintAllowed } is set to true | function genesisController(uint256 _genesisId)
private {
require(epoch == 0, "error epoch");
require(genesisId <= maxGenesisSupply, "error genesisId");
require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry");
epochMintingRegistry[epoch][_genesisId] = true;
if (genesisId == maxGenesisSupply) {
blockGenesis = block.number;
blockMeta = blockGenesis;
emit Genesis(epoch, blockGenesis);
epochRegulator();
}
}
| 5,878,538 | [
1,
6668,
358,
10680,
6093,
471,
283,
8230,
12514,
434,
326,
21906,
423,
4464,
312,
474,
282,
389,
4507,
16786,
548,
10286,
358,
5504,
288,
21906,
548,
289,
471,
1045,
288,
7632,
49,
474,
310,
4243,
289,
225,
1000,
288,
389,
4507,
16786,
548,
289,
364,
288,
7632,
289,
487,
638,
225,
5203,
288,
21906,
548,
289,
30093,
288,
943,
7642,
16786,
3088,
1283,
289,
326,
445,
1377,
903,
3671,
326,
501,
358,
5504,
326,
7632,
4888,
1377,
288,
1203,
7642,
16786,
289,
353,
444,
1338,
3647,
16,
622,
333,
813,
1377,
288,
1203,
2781,
289,
353,
444,
358,
288,
1203,
7642,
16786,
289,
2724,
7632,
33,
20,
1377,
9697,
518,
353,
8470,
1368,
326,
445,
7632,
1617,
11775,
1435,
1377,
12419,
326,
7632,
353,
960,
11799,
16,
326,
394,
9377,
787,
1377,
21251,
10804,
16,
288,
9377,
49,
474,
5042,
289,
353,
444,
358,
638,
2,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0
]
| [
1,
565,
445,
21906,
2933,
12,
11890,
5034,
389,
4507,
16786,
548,
13,
203,
565,
3238,
288,
203,
3639,
2583,
12,
12015,
422,
374,
16,
315,
1636,
7632,
8863,
203,
3639,
2583,
12,
4507,
16786,
548,
1648,
943,
7642,
16786,
3088,
1283,
16,
315,
1636,
21906,
548,
8863,
203,
3639,
2583,
12,
5,
12015,
49,
474,
310,
4243,
63,
12015,
6362,
67,
4507,
16786,
548,
6487,
315,
1636,
7632,
49,
474,
310,
4243,
8863,
203,
203,
3639,
7632,
49,
474,
310,
4243,
63,
12015,
6362,
67,
4507,
16786,
548,
65,
273,
638,
31,
203,
203,
3639,
309,
261,
4507,
16786,
548,
422,
943,
7642,
16786,
3088,
1283,
13,
288,
203,
5411,
1203,
7642,
16786,
273,
1203,
18,
2696,
31,
203,
5411,
1203,
2781,
273,
1203,
7642,
16786,
31,
203,
2398,
203,
5411,
3626,
31637,
12,
12015,
16,
1203,
7642,
16786,
1769,
203,
5411,
7632,
1617,
11775,
5621,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
/**
* @dev Extends standard ERC20 contract from OpenZeppelin
*/
abstract contract RareRhinoNFTs {
function ownerOf(uint256 tokenId) public view virtual returns (address);
function walletOfOwner(address _owner) public view virtual returns (uint256[] memory);
}
contract RareToken is ERC20("Rare", "RARE"), ReentrancyGuard, Ownable {
// state variables (no constructor)
address private _rrAddress; // Rare Rhinos holders contract address
RareRhinoNFTs rrn;
// Begin functions
function setRrAddress(address rrAddress) external onlyOwner {
require(_nftAddress == address(0), "Already set");
_nftAddress = nftAddress;
}
function payout() external nonReentrant returns (uint256) {
uint256 totalPayoutQty = 0;
tokenListV1 = cfd1.walletOfOwner(msg.sender);
uint256 numTokens = tokenIndices.length
for (uint256 ii = 0; ii < numTokens; ii++) {
uint256 tokenIndex = tokenIndices[ii];
require(ERC721Enumerable(_rrAddress).ownerOf(tokenIndex) == msg.sender, "Sender is not the owner");
// Make sure there are no duplicate tokens!
if (ii == 0) {
for (uint256 jj = 1; jj < numTokens; jj++) {
require(tokenIndices[ii] != tokenIndices[jj], "Duplicate token index");
}
}
uint256 claimQty = getClaimableFromLastOwed(tokenIndex);
if (claimQty != 0) {
totalClaimQty = totalClaimQty + claimQty;
_lastClaim[tokenIndex] = getTime();
}
}
require(totalClaimQty != 0, "No accumulated SMOKE");
_mint(_msgSender(), totalClaimQty);
return totalClaimQty;
}
function perToken() internal pure virtual returns (uint256) {
return 1 ether;
}
function claim(uint256 tokenId) external nonReentrant returns (uint256){
require(ERC721Enumerable(_nftAddress).ownerOf(tokenId) == _msgSender(), "Sender is not the owner");
uint256 owed = getClaimableFromLastOwed(tokenId);
_mint(_msgSender(), owed);
_lastClaim[tokenId] = getTime();
return owed;
}
/**
@dev
to find owed = total owed since start - claimed tokens
*/
function caclulateOwed(uint256 lastClaimed, uint256 totalDays) public pure returns (uint256) {
uint256 accrued = totalDays - lastClaimed;
if(accrued >= 1800) {
return totalEmissions(1800) - totalEmissions(lastClaimed);
}
return totalEmissions(totalDays) - totalEmissions(lastClaimed);
}
function getTime() internal view virtual returns (uint256) {
return block.timestamp;
}
function getInterval(uint qty) internal pure virtual returns (uint256) {
return qty * 1 days;
}
/**
@dev
10 Smokes a day for 180 days = 1800 (180 days)
8 Smokes a day for 180 days = 1440 (360 days)
6 Smokes a day for 180 days = 1080 (540 days)
4 Smokes a day for 180 days = 720 (720 days)
2 Smokes a day for 180 days = 360 (900 days)
Total = 5400 smoke per dragon
5400 * 5000 (no. of NFTs) = 27,000,000
2 smokes a day for 900 more days
900 * 2 * 5000 = 9,000,000
36,000,000 total smokes created
*/
function totalEmissions(uint256 totalDays) public pure returns (uint256) {
require(totalDays <= 1800, "Exceeds timeline");
if(totalDays <= 180) return 10 * (totalDays);
// 10 * 180 + 8 * (totalDays - 180);
if(totalDays <= 360) return 1800 + 8 * (totalDays - 180);
// 10 * 180 + 8 * 180 + 6 * (totalDays - 360);
if(totalDays <= 540) return 3240 + 6 * (totalDays - 360);
// 10 * 180 + 8 * 180 + 6 * 180 + 4 * (totalDays - 540);
if(totalDays <= 720) return 4320 + 4 * (totalDays - 540);
// 10 * 180 + 8 * 180 + 6 * 180 + 4 * 180 + 2 * (totalDays - 720);
return 5040 + 2 * (totalDays - 720);
}
}
| Make sure there are no duplicate tokens! | function payout() external nonReentrant returns (uint256) {
uint256 totalPayoutQty = 0;
tokenListV1 = cfd1.walletOfOwner(msg.sender);
uint256 numTokens = tokenIndices.length
for (uint256 ii = 0; ii < numTokens; ii++) {
uint256 tokenIndex = tokenIndices[ii];
require(ERC721Enumerable(_rrAddress).ownerOf(tokenIndex) == msg.sender, "Sender is not the owner");
if (ii == 0) {
for (uint256 jj = 1; jj < numTokens; jj++) {
require(tokenIndices[ii] != tokenIndices[jj], "Duplicate token index");
}
}
uint256 claimQty = getClaimableFromLastOwed(tokenIndex);
if (claimQty != 0) {
totalClaimQty = totalClaimQty + claimQty;
_lastClaim[tokenIndex] = getTime();
}
}
require(totalClaimQty != 0, "No accumulated SMOKE");
_mint(_msgSender(), totalClaimQty);
return totalClaimQty;
}
| 918,004 | [
1,
6464,
3071,
1915,
854,
1158,
6751,
2430,
5,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
293,
2012,
1435,
3903,
1661,
426,
8230,
970,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
2078,
52,
2012,
53,
4098,
273,
374,
31,
203,
203,
3639,
1147,
682,
58,
21,
273,
6080,
72,
21,
18,
19177,
951,
5541,
12,
3576,
18,
15330,
1769,
203,
203,
3639,
2254,
5034,
818,
5157,
273,
1147,
8776,
18,
2469,
203,
203,
3639,
364,
261,
11890,
5034,
6072,
273,
374,
31,
6072,
411,
818,
5157,
31,
6072,
27245,
288,
203,
5411,
2254,
5034,
1147,
1016,
273,
1147,
8776,
63,
2835,
15533,
203,
5411,
2583,
12,
654,
39,
27,
5340,
3572,
25121,
24899,
523,
1887,
2934,
8443,
951,
12,
2316,
1016,
13,
422,
1234,
18,
15330,
16,
315,
12021,
353,
486,
326,
3410,
8863,
203,
203,
5411,
309,
261,
2835,
422,
374,
13,
288,
203,
7734,
364,
261,
11890,
5034,
10684,
273,
404,
31,
10684,
411,
818,
5157,
31,
10684,
27245,
288,
203,
10792,
2583,
12,
2316,
8776,
63,
2835,
65,
480,
1147,
8776,
63,
78,
78,
6487,
315,
11826,
1147,
770,
8863,
203,
7734,
289,
203,
5411,
289,
5375,
203,
5411,
2254,
5034,
7516,
53,
4098,
273,
13674,
4581,
429,
1265,
3024,
3494,
329,
12,
2316,
1016,
1769,
203,
5411,
309,
261,
14784,
53,
4098,
480,
374,
13,
288,
203,
7734,
2078,
9762,
53,
4098,
273,
2078,
9762,
53,
4098,
397,
7516,
53,
4098,
31,
203,
7734,
389,
2722,
9762,
63,
2316,
1016,
65,
273,
6135,
5621,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
2583,
12,
4963,
9762,
53,
4098,
480,
374,
2
]
|
./full_match/1/0x82a7b5842085f434c6584A8c44b6A1C15c25a512/sources/contracts/test/filters/TestRangedCollectionCollateralFilter.sol | *************************************************************************/ Constructor */*************************************************************************/ | constructor(address token, uint256 startTokenId, uint256 endTokenId) {
_initialize(token, startTokenId, endTokenId);
}
| 9,659,570 | [
1,
19,
11417,
368,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
12,
2867,
1147,
16,
2254,
5034,
787,
1345,
548,
16,
2254,
5034,
679,
1345,
548,
13,
288,
203,
3639,
389,
11160,
12,
2316,
16,
787,
1345,
548,
16,
679,
1345,
548,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../interfaces/IYearn.sol";
import "../../interfaces/IYvault.sol";
import "../../interfaces/IDAOVault.sol";
/// @title Contract for yield token in Yearn Finance contracts
/// @dev This contract should not be reused after vesting state
contract YearnFarmerDAIv2 is ERC20, Ownable {
/**
* @dev Inherit from Ownable contract enable contract ownership transferable
* Function: transferOwnership(newOwnerAddress)
* Only current owner is able to call the function
*/
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
IERC20 public token;
IYearn public earn;
IYvault public vault;
uint256 private constant MAX_UNIT = 2**256 - 2;
mapping (address => uint256) private earnDepositBalance;
mapping (address => uint256) private vaultDepositBalance;
uint256 public pool;
// Address to collect fees
address public treasuryWallet = 0x59E83877bD248cBFe392dbB5A8a29959bcb48592;
address public communityWallet = 0xdd6c35aFF646B2fB7d8A8955Ccbe0994409348d0;
uint256[] public networkFeeTier2 = [50000e18+1, 100000e18]; // Represent [tier2 minimun, tier2 maximun], initial value represent Tier 2 from 50001 to 100000
uint256 public customNetworkFeeTier = 1000000e18;
uint256 public constant DENOMINATOR = 10000;
uint256[] public networkFeePercentage = [100, 75, 50]; // Represent [Tier 1, Tier 2, Tier 3], initial value represent [1%, 0.75%, 0.5%]
uint256 public customNetworkFeePercentage = 25;
uint256 public profileSharingFeePercentage = 1000;
uint256 public constant treasuryFee = 5000; // 50% on profile sharing fee
uint256 public constant communityFee = 5000; // 50% on profile sharing fee
bool public isVesting;
IDAOVault public daoVault;
event SetTreasuryWallet(address indexed oldTreasuryWallet, address indexed newTreasuryWallet);
event SetCommunityWallet(address indexed oldCommunityWallet, address indexed newCommunityWallet);
event SetNetworkFeeTier2(uint256[] oldNetworkFeeTier2, uint256[] newNetworkFeeTier2);
event SetNetworkFeePercentage(uint256[] oldNetworkFeePercentage, uint256[] newNetworkFeePercentage);
event SetCustomNetworkFeeTier(uint256 indexed oldCustomNetworkFeeTier, uint256 indexed newCustomNetworkFeeTier);
event SetCustomNetworkFeePercentage(uint256 indexed oldCustomNetworkFeePercentage, uint256 indexed newCustomNetworkFeePercentage);
event SetProfileSharingFeePercentage(uint256 indexed oldProfileSharingFeePercentage, uint256 indexed newProfileSharingFeePercentage);
constructor(address _token, address _earn, address _vault)
ERC20("Yearn Farmer v2 DAI", "yfDAIv2") {
_setupDecimals(18);
token = IERC20(_token);
earn = IYearn(_earn);
vault = IYvault(_vault);
_approvePooling();
}
/**
* @notice Set Vault that interact with this contract
* @dev This function call after deploy Vault contract and only able to call once
* @dev This function is needed only if this is the first strategy to connect with Vault
* @param _address Address of Vault
* Requirements:
* - Only owner of this contract can call this function
* - Vault is not set yet
*/
function setVault(address _address) external onlyOwner {
require(address(daoVault) == address(0), "Vault set");
daoVault = IDAOVault(_address);
}
/**
* @notice Set new treasury wallet address in contract
* @param _treasuryWallet Address of new treasury wallet
* Requirements:
* - Only owner of this contract can call this function
*/
function setTreasuryWallet(address _treasuryWallet) external onlyOwner {
address oldTreasuryWallet = treasuryWallet;
treasuryWallet = _treasuryWallet;
emit SetTreasuryWallet(oldTreasuryWallet, _treasuryWallet);
}
/**
* @notice Set new community wallet address in contract
* @param _communityWallet Address of new community wallet
* Requirements:
* - Only owner of this contract can call this function
*/
function setCommunityWallet(address _communityWallet) external onlyOwner {
address oldCommunityWallet = communityWallet;
communityWallet = _communityWallet;
emit SetCommunityWallet(oldCommunityWallet, _communityWallet);
}
/**
* @notice Set network fee tier
* @notice Details for network fee tier can view at deposit() function below
* @param _networkFeeTier2 Array [tier2 minimun, tier2 maximun], view additional info below
* Requirements:
* - Only owner of this contract can call this function
* - First element in array must greater than 0
* - Second element must greater than first element
*/
function setNetworkFeeTier2(uint256[] calldata _networkFeeTier2) external onlyOwner {
require(_networkFeeTier2[0] != 0, "Minimun amount cannot be 0");
require(_networkFeeTier2[1] > _networkFeeTier2[0], "Maximun amount must greater than minimun amount");
/**
* Network fees have three tier, but it is sufficient to have minimun and maximun amount of tier 2
* Tier 1: deposit amount < minimun amount of tier 2
* Tier 2: minimun amount of tier 2 <= deposit amount <= maximun amount of tier 2
* Tier 3: amount > maximun amount of tier 2
*/
uint256[] memory oldNetworkFeeTier2 = networkFeeTier2;
networkFeeTier2 = _networkFeeTier2;
emit SetNetworkFeeTier2(oldNetworkFeeTier2, _networkFeeTier2);
}
/**
* @notice Set network fee in percentage
* @param _networkFeePercentage An array of integer, view additional info below
* Requirements:
* - Only owner of this contract can call this function
* - Each of the element in the array must less than 4000 (40%)
*/
function setNetworkFeePercentage(uint256[] calldata _networkFeePercentage) external onlyOwner {
/**
* _networkFeePercentage content a array of 3 element, representing network fee of tier 1, tier 2 and tier 3
* For example networkFeePercentage is [100, 75, 50]
* which mean network fee for Tier 1 = 1%, Tier 2 = 0.75% and Tier 3 = 0.5%
*/
require(
_networkFeePercentage[0] < 4000 &&
_networkFeePercentage[1] < 4000 &&
_networkFeePercentage[2] < 4000, "Network fee percentage cannot be more than 40%"
);
uint256[] memory oldNetworkFeePercentage = networkFeePercentage;
networkFeePercentage = _networkFeePercentage;
emit SetNetworkFeePercentage(oldNetworkFeePercentage, _networkFeePercentage);
}
/**
* @notice Set network fee tier
* @param _customNetworkFeeTier Integar
* @dev Custom network fee tier is checked before network fee tier 3. Please check networkFeeTier[1] before set.
* Requirements:
* - Only owner of this contract can call this function
* - Custom network fee tier must greater than network fee tier 2
*/
function setCustomNetworkFeeTier(uint256 _customNetworkFeeTier) external onlyOwner {
require(_customNetworkFeeTier > networkFeeTier2[1], "Custom network fee tier must greater than tier 2");
uint256 oldCustomNetworkFeeTier = customNetworkFeeTier;
customNetworkFeeTier = _customNetworkFeeTier;
emit SetCustomNetworkFeeTier(oldCustomNetworkFeeTier, _customNetworkFeeTier);
}
/**
* @notice Set custom network fee
* @param _percentage Integar (100 = 1%)
* Requirements:
* - Only owner of this contract can call this function
* - Amount set must less than network fee for tier 2
*/
function setCustomNetworkFeePercentage(uint256 _percentage) public onlyOwner {
require(_percentage < networkFeePercentage[2], "Custom network fee percentage cannot be more than tier 2");
uint256 oldCustomNetworkFeePercentage = customNetworkFeePercentage;
customNetworkFeePercentage = _percentage;
emit SetCustomNetworkFeePercentage(oldCustomNetworkFeePercentage, _percentage);
}
/**
* @notice Set profile sharing fee
* @param _percentage Integar (100 = 1%)
* Requirements:
* - Only owner of this contract can call this function
* - Amount set must less than 4000 (40%)
*/
function setProfileSharingFeePercentage(uint256 _percentage) public onlyOwner {
require(_percentage < 4000, "Profile sharing fee percentage cannot be more than 40%");
uint256 oldProfileSharingFeePercentage = profileSharingFeePercentage;
profileSharingFeePercentage = _percentage;
emit SetProfileSharingFeePercentage(oldProfileSharingFeePercentage, _percentage);
}
/**
* @notice Approve Yearn Finance contracts to deposit token from this contract
* @dev This function only need execute once in contract contructor
*/
function _approvePooling() private {
uint256 earnAllowance = token.allowance(address(this), address(earn));
if (earnAllowance == uint256(0)) {
token.safeApprove(address(earn), MAX_UNIT);
}
uint256 vaultAllowance = token.allowance(address(this), address(vault));
if (vaultAllowance == uint256(0)) {
token.safeApprove(address(vault), MAX_UNIT);
}
}
/**
* @notice Get Yearn Earn current total deposit amount of account (after network fee)
* @param _address Address of account to check
* @return result Current total deposit amount of account in Yearn Earn. 0 if contract is in vesting state.
*/
function getEarnDepositBalance(address _address) external view returns (uint256 result) {
result = isVesting ? 0 : earnDepositBalance[_address];
}
/**
* @notice Get Yearn Vault current total deposit amount of account (after network fee)
* @param _address Address of account to check
* @return result Current total deposit amount of account in Yearn Vault. 0 if contract is in vesting state.
*/
function getVaultDepositBalance(address _address) external view returns (uint256 result) {
result = isVesting ? 0 : vaultDepositBalance[_address];
}
/**
* @notice Deposit token into Yearn Earn and Vault contracts
* @param _amounts amount of earn and vault to deposit in list: [earn deposit amount, vault deposit amount]
* Requirements:
* - Sender must approve this contract to transfer token from sender to this contract
* - This contract is not in vesting state
* - Only Vault can call this function
* - Either first element(earn deposit) or second element(earn deposit) in list must greater than 0
*/
function deposit(uint256[] memory _amounts) public {
require(!isVesting, "Contract in vesting state");
require(msg.sender == address(daoVault), "Only can call from Vault");
require(_amounts[0] > 0 || _amounts[1] > 0, "Amount must > 0");
uint256 _earnAmount = _amounts[0];
uint256 _vaultAmount = _amounts[1];
uint256 _depositAmount = _earnAmount.add(_vaultAmount);
token.safeTransferFrom(tx.origin, address(this), _depositAmount);
uint256 _earnNetworkFee;
uint256 _vaultNetworkFee;
uint256 _networkFeePercentage;
/**
* Network fees
* networkFeeTier2 is used to set each tier minimun and maximun
* For example networkFeeTier2 is [50000, 100000],
* Tier 1 = _depositAmount < 50001
* Tier 2 = 50001 <= _depositAmount <= 100000
* Tier 3 = _depositAmount > 100000
*
* networkFeePercentage is used to set each tier network fee percentage
* For example networkFeePercentage is [100, 75, 50]
* which mean network fee for Tier 1 = 1%, Tier 2 = 0.75%, Tier 3 = 0.5%
*
* customNetworkFeeTier is set before network fee tier 3
* customNetworkFeepercentage will be used if _depositAmount over customNetworkFeeTier before network fee tier 3
*/
if (_depositAmount < networkFeeTier2[0]) {
// Tier 1
_networkFeePercentage = networkFeePercentage[0];
} else if (_depositAmount >= networkFeeTier2[0] && _depositAmount <= networkFeeTier2[1]) {
// Tier 2
_networkFeePercentage = networkFeePercentage[1];
} else if (_depositAmount >= customNetworkFeeTier) {
// Custom tier
_networkFeePercentage = customNetworkFeePercentage;
} else {
// Tier 3
_networkFeePercentage = networkFeePercentage[2];
}
// Deposit to Yearn Earn after fee
if (_earnAmount > 0) {
_earnNetworkFee = _earnAmount.mul(_networkFeePercentage).div(DENOMINATOR);
_earnAmount = _earnAmount.sub(_earnNetworkFee);
earn.deposit(_earnAmount);
earnDepositBalance[tx.origin] = earnDepositBalance[tx.origin].add(_earnAmount);
}
// Deposit to Yearn Vault after fee
if (_vaultAmount > 0) {
_vaultNetworkFee = _vaultAmount.mul(_networkFeePercentage).div(DENOMINATOR);
_vaultAmount = _vaultAmount.sub(_vaultNetworkFee);
vault.deposit(_vaultAmount);
vaultDepositBalance[tx.origin] = vaultDepositBalance[tx.origin].add(_vaultAmount);
}
// Transfer network fee to treasury and community wallet
uint _totalNetworkFee = _earnNetworkFee.add(_vaultNetworkFee);
token.safeTransfer(treasuryWallet, _totalNetworkFee.mul(treasuryFee).div(DENOMINATOR));
token.safeTransfer(communityWallet, _totalNetworkFee.mul(treasuryFee).div(DENOMINATOR));
uint256 _totalAmount = _earnAmount.add(_vaultAmount);
uint256 _shares;
_shares = totalSupply() == 0 ? _totalAmount : _totalAmount.mul(totalSupply()).div(pool);
_mint(address(daoVault), _shares);
pool = pool.add(_totalAmount);
}
/**
* @notice Withdraw from Yearn Earn and Vault contracts
* @param _shares amount of earn and vault to withdraw in list: [earn withdraw amount, vault withdraw amount]
* Requirements:
* - This contract is not in vesting state
* - Only Vault can call this function
*/
function withdraw(uint256[] memory _shares) external {
require(!isVesting, "Contract in vesting state");
require(msg.sender == address(daoVault), "Only can call from Vault");
if (_shares[0] > 0) {
_withdrawEarn(_shares[0]);
}
if (_shares[1] > 0) {
_withdrawVault(_shares[1]);
}
}
/**
* @notice Withdraw from Yearn Earn contract
* @dev Only call within function withdraw()
* @param _shares Amount of shares to withdraw
* Requirements:
* - Amount input must less than or equal to sender current total amount of earn deposit in contract
*/
function _withdrawEarn(uint256 _shares) private {
uint256 _d = pool.mul(_shares).div(totalSupply()); // Initial Deposit Amount
require(earnDepositBalance[tx.origin] >= _d, "Insufficient balance");
uint256 _earnShares = (_d.mul(earn.totalSupply())).div(earn.calcPoolValueInToken()); // Find earn shares based on deposit amount
uint256 _r = ((earn.calcPoolValueInToken()).mul(_earnShares)).div(earn.totalSupply()); // Actual earn withdraw amount
earn.withdraw(_earnShares);
earnDepositBalance[tx.origin] = earnDepositBalance[tx.origin].sub(_d);
_burn(address(daoVault), _shares);
pool = pool.sub(_d);
if (_r > _d) {
uint256 _p = _r.sub(_d); // Profit
uint256 _fee = _p.mul(profileSharingFeePercentage).div(DENOMINATOR);
token.safeTransfer(tx.origin, _r.sub(_fee));
token.safeTransfer(treasuryWallet, _fee.mul(treasuryFee).div(DENOMINATOR));
token.safeTransfer(communityWallet, _fee.mul(communityFee).div(DENOMINATOR));
} else {
token.safeTransfer(tx.origin, _r);
}
}
/**
* @notice Withdraw from Yearn Vault contract
* @dev Only call within function withdraw()
* @param _shares Amount of shares to withdraw
* Requirements:
* - Amount input must less than or equal to sender current total amount of vault deposit in contract
*/
function _withdrawVault(uint256 _shares) private {
uint256 _d = pool.mul(_shares).div(totalSupply()); // Initial Deposit Amount
require(vaultDepositBalance[tx.origin] >= _d, "Insufficient balance");
uint256 _vaultShares = (_d.mul(vault.totalSupply())).div(vault.balance()); // Find vault shares based on deposit amount
uint256 _r = ((vault.balance()).mul(_vaultShares)).div(vault.totalSupply()); // Actual vault withdraw amount
vault.withdraw(_vaultShares);
vaultDepositBalance[tx.origin] = vaultDepositBalance[tx.origin].sub(_d);
_burn(address(daoVault), _shares);
pool = pool.sub(_d);
if (_r > _d) {
uint256 _p = _r.sub(_d); // Profit
uint256 _fee = _p.mul(profileSharingFeePercentage).div(DENOMINATOR);
token.safeTransfer(tx.origin, _r.sub(_fee));
token.safeTransfer(treasuryWallet, _fee.mul(treasuryFee).div(DENOMINATOR));
token.safeTransfer(communityWallet, _fee.mul(communityFee).div(DENOMINATOR));
} else {
token.safeTransfer(tx.origin, _r);
}
}
/**
* @notice Vesting this contract, withdraw all the token from Yearn contracts
* @notice Disabled the deposit and withdraw functions for public, only allowed users to do refund from this contract
* Requirements:
* - Only owner of this contract can call this function
* - This contract is not in vesting state
*/
function vesting() external onlyOwner {
require(!isVesting, "Already in vesting state");
// Withdraw all funds from Yearn Earn and Vault contracts
isVesting = true;
uint256 _earnBalance = earn.balanceOf(address(this));
uint256 _vaultBalance = vault.balanceOf(address(this));
if (_earnBalance > 0) {
earn.withdraw(_earnBalance);
}
if (_vaultBalance > 0) {
vault.withdraw(_vaultBalance);
}
// Collect all profits
uint256 balance_ = token.balanceOf(address(this));
if (balance_ > pool) {
uint256 _profit = balance_.sub(pool);
uint256 _fee = _profit.mul(profileSharingFeePercentage).div(DENOMINATOR);
token.safeTransfer(treasuryWallet, _fee.mul(treasuryFee).div(DENOMINATOR));
token.safeTransfer(communityWallet, _fee.mul(communityFee).div(DENOMINATOR));
}
pool = 0;
}
/**
* @notice Get token amount based on daoToken hold by account after contract in vesting state
* @param _address Address of account to check
* @return Token amount based on on daoToken hold by account. 0 if contract is not in vesting state
*/
function getSharesValue(address _address) external view returns (uint256) {
if (!isVesting) {
return 0;
} else {
uint256 _shares = daoVault.balanceOf(_address);
if (_shares > 0) {
return token.balanceOf(address(this)).mul(_shares).div(daoVault.totalSupply());
} else {
return 0;
}
}
}
/**
* @notice Refund all tokens based on daoToken hold by sender
* @notice Only available after contract in vesting state
* Requirements:
* - This contract is in vesting state
* - Only Vault can call this function
*/
function refund(uint256 _shares) external {
require(isVesting, "Not in vesting state");
require(msg.sender == address(daoVault), "Only can call from Vault");
uint256 _refundAmount = token.balanceOf(address(this)).mul(_shares).div(daoVault.totalSupply());
token.safeTransfer(tx.origin, _refundAmount);
_burn(address(daoVault), _shares);
}
/**
* @notice Approve Vault to migrate funds from this contract
* @notice Only available after contract in vesting state
* Requirements:
* - Only owner of this contract can call this function
* - This contract is in vesting state
*/
function approveMigrate() external onlyOwner {
require(isVesting, "Not in vesting state");
if (token.allowance(address(this), address(daoVault)) == 0) {
token.safeApprove(address(daoVault), MAX_UNIT);
}
}
} | * @notice Get token amount based on daoToken hold by account after contract in vesting state @param _address Address of account to check @return Token amount based on on daoToken hold by account. 0 if contract is not in vesting state/ | function getSharesValue(address _address) external view returns (uint256) {
if (!isVesting) {
return 0;
uint256 _shares = daoVault.balanceOf(_address);
if (_shares > 0) {
return token.balanceOf(address(this)).mul(_shares).div(daoVault.totalSupply());
return 0;
}
}
}
| 1,781,764 | [
1,
967,
1147,
3844,
2511,
603,
15229,
1345,
6887,
635,
2236,
1839,
6835,
316,
331,
10100,
919,
225,
389,
2867,
5267,
434,
2236,
358,
866,
327,
3155,
3844,
2511,
603,
603,
15229,
1345,
6887,
635,
2236,
18,
374,
309,
6835,
353,
486,
316,
331,
10100,
919,
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,
225,
445,
1322,
3395,
455,
620,
12,
2867,
389,
2867,
13,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
309,
16051,
291,
58,
10100,
13,
288,
203,
1377,
327,
374,
31,
203,
1377,
2254,
5034,
389,
30720,
273,
15229,
12003,
18,
12296,
951,
24899,
2867,
1769,
203,
1377,
309,
261,
67,
30720,
405,
374,
13,
288,
203,
3639,
327,
1147,
18,
12296,
951,
12,
2867,
12,
2211,
13,
2934,
16411,
24899,
30720,
2934,
2892,
12,
2414,
83,
12003,
18,
4963,
3088,
1283,
10663,
203,
3639,
327,
374,
31,
203,
1377,
289,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xe35aC90D3BD1009977c989F3eb0c0d3E9F171817/sources/contracts/core/DaoRegistry.sol | * @notice Updates the delegate key of a member @param memberAddr The member doing the delegation @param newDelegateKey The member who is being delegated to/ skip checks if member is setting the delegate key to their member address newDelegate must not be delegated to | function updateDelegateKey(address memberAddr, address newDelegateKey)
external
hasAccess(this, AclFlag.UPDATE_DELEGATE_KEY)
{
require(newDelegateKey != address(0x0), "newDelegateKey cannot be 0");
if (newDelegateKey != memberAddr) {
require(
memberAddressesByDelegatedKey[newDelegateKey] == address(0x0),
"cannot overwrite existing delegated keys"
);
require(
memberAddressesByDelegatedKey[memberAddr] == address(0x0),
"address already taken as delegated key"
);
}
Member storage member = members[memberAddr];
require(
DaoHelper.getFlag(member.flags, uint8(MemberFlag.EXISTS)),
"member does not exist"
);
getCurrentDelegateKey(memberAddr)
] = address(0x0);
memberAddressesByDelegatedKey[newDelegateKey] = memberAddr;
_createNewDelegateCheckpoint(memberAddr, newDelegateKey);
emit UpdateDelegateKey(memberAddr, newDelegateKey);
}
| 15,956,530 | [
1,
5121,
326,
7152,
498,
434,
279,
3140,
225,
3140,
3178,
1021,
3140,
9957,
326,
23595,
225,
394,
9586,
653,
1021,
3140,
10354,
353,
3832,
30055,
358,
19,
2488,
4271,
309,
3140,
353,
3637,
326,
7152,
498,
358,
3675,
3140,
1758,
394,
9586,
1297,
486,
506,
30055,
358,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1089,
9586,
653,
12,
2867,
3140,
3178,
16,
1758,
394,
9586,
653,
13,
203,
3639,
3903,
203,
3639,
24836,
12,
2211,
16,
23887,
4678,
18,
8217,
67,
1639,
19384,
1777,
67,
3297,
13,
203,
565,
288,
203,
3639,
2583,
12,
2704,
9586,
653,
480,
1758,
12,
20,
92,
20,
3631,
315,
2704,
9586,
653,
2780,
506,
374,
8863,
203,
203,
3639,
309,
261,
2704,
9586,
653,
480,
3140,
3178,
13,
288,
203,
5411,
2583,
12,
203,
7734,
3140,
7148,
858,
15608,
690,
653,
63,
2704,
9586,
653,
65,
422,
1758,
12,
20,
92,
20,
3631,
203,
7734,
315,
12892,
6156,
2062,
30055,
1311,
6,
203,
5411,
11272,
203,
5411,
2583,
12,
203,
7734,
3140,
7148,
858,
15608,
690,
653,
63,
5990,
3178,
65,
422,
1758,
12,
20,
92,
20,
3631,
203,
7734,
315,
2867,
1818,
9830,
487,
30055,
498,
6,
203,
5411,
11272,
203,
3639,
289,
203,
203,
3639,
8596,
2502,
3140,
273,
4833,
63,
5990,
3178,
15533,
203,
3639,
2583,
12,
203,
5411,
463,
6033,
2276,
18,
588,
4678,
12,
5990,
18,
7133,
16,
2254,
28,
12,
4419,
4678,
18,
21205,
13,
3631,
203,
5411,
315,
5990,
1552,
486,
1005,
6,
203,
3639,
11272,
203,
203,
5411,
5175,
9586,
653,
12,
5990,
3178,
13,
203,
3639,
308,
273,
1758,
12,
20,
92,
20,
1769,
203,
203,
3639,
3140,
7148,
858,
15608,
690,
653,
63,
2704,
9586,
653,
65,
273,
3140,
3178,
31,
203,
203,
3639,
389,
2640,
1908,
9586,
14431,
12,
5990,
3178,
16,
394,
9586,
653,
1769,
203,
3639,
3626,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/* Interface Imports */
import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol";
/**
* @title OVM_StateManager
* @dev The State Manager contract holds all storage values for contracts in the OVM. It can only be written to by the
* the Execution Manager and State Transitioner. It runs on L1 during the setup and execution of a fraud proof.
* The same logic runs on L2, but has been implemented as a precompile in the L2 go-ethereum client
* (see https://github.com/ethereum-optimism/go-ethereum/blob/master/core/vm/ovm_state_manager.go).
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_StateManager is iOVM_StateManager {
/*************
* Constants *
*************/
bytes32 constant internal EMPTY_ACCOUNT_STORAGE_ROOT = 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421;
bytes32 constant internal EMPTY_ACCOUNT_CODE_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
bytes32 constant internal STORAGE_XOR_VALUE = 0xFEEDFACECAFEBEEFFEEDFACECAFEBEEFFEEDFACECAFEBEEFFEEDFACECAFEBEEF;
/*************
* Variables *
*************/
address override public owner;
address override public ovmExecutionManager;
mapping (address => Lib_OVMCodec.Account) internal accounts;
mapping (address => mapping (bytes32 => bytes32)) internal contractStorage;
mapping (address => mapping (bytes32 => bool)) internal verifiedContractStorage;
mapping (bytes32 => ItemState) internal itemStates;
uint256 internal totalUncommittedAccounts;
uint256 internal totalUncommittedContractStorage;
/***************
* Constructor *
***************/
/**
* @param _owner Address of the owner of this contract.
*/
constructor(
address _owner
)
{
owner = _owner;
}
/**********************
* Function Modifiers *
**********************/
/**
* Simple authentication, this contract should only be accessible to the owner (which is expected to be the State Transitioner during `PRE_EXECUTION`
* or the OVM_ExecutionManager during transaction execution.
*/
modifier authenticated() {
// owner is the State Transitioner
require(
msg.sender == owner || msg.sender == ovmExecutionManager,
"Function can only be called by authenticated addresses"
);
_;
}
/********************
* Public Functions *
********************/
/**
* Checks whether a given address is allowed to modify this contract.
* @param _address Address to check.
* @return Whether or not the address can modify this contract.
*/
function isAuthenticated(
address _address
)
override
public
view
returns (
bool
)
{
return (_address == owner || _address == ovmExecutionManager);
}
/**
* Sets the address of the OVM_ExecutionManager.
* @param _ovmExecutionManager Address of the OVM_ExecutionManager.
*/
function setExecutionManager(
address _ovmExecutionManager
)
override
public
authenticated
{
ovmExecutionManager = _ovmExecutionManager;
}
/**
* Inserts an account into the state.
* @param _address Address of the account to insert.
* @param _account Account to insert for the given address.
*/
function putAccount(
address _address,
Lib_OVMCodec.Account memory _account
)
override
public
authenticated
{
accounts[_address] = _account;
}
/**
* Marks an account as empty.
* @param _address Address of the account to mark.
*/
function putEmptyAccount(
address _address
)
override
public
authenticated
{
Lib_OVMCodec.Account storage account = accounts[_address];
account.storageRoot = EMPTY_ACCOUNT_STORAGE_ROOT;
account.codeHash = EMPTY_ACCOUNT_CODE_HASH;
}
/**
* Retrieves an account from the state.
* @param _address Address of the account to retrieve.
* @return Account for the given address.
*/
function getAccount(
address _address
)
override
public
view
returns (
Lib_OVMCodec.Account memory
)
{
return accounts[_address];
}
/**
* Checks whether the state has a given account.
* @param _address Address of the account to check.
* @return Whether or not the state has the account.
*/
function hasAccount(
address _address
)
override
public
view
returns (
bool
)
{
return accounts[_address].codeHash != bytes32(0);
}
/**
* Checks whether the state has a given known empty account.
* @param _address Address of the account to check.
* @return Whether or not the state has the empty account.
*/
function hasEmptyAccount(
address _address
)
override
public
view
returns (
bool
)
{
return (
accounts[_address].codeHash == EMPTY_ACCOUNT_CODE_HASH
&& accounts[_address].nonce == 0
);
}
/**
* Sets the nonce of an account.
* @param _address Address of the account to modify.
* @param _nonce New account nonce.
*/
function setAccountNonce(
address _address,
uint256 _nonce
)
override
public
authenticated
{
accounts[_address].nonce = _nonce;
}
/**
* Gets the nonce of an account.
* @param _address Address of the account to access.
* @return Nonce of the account.
*/
function getAccountNonce(
address _address
)
override
public
view
returns (
uint256
)
{
return accounts[_address].nonce;
}
/**
* Retrieves the Ethereum address of an account.
* @param _address Address of the account to access.
* @return Corresponding Ethereum address.
*/
function getAccountEthAddress(
address _address
)
override
public
view
returns (
address
)
{
return accounts[_address].ethAddress;
}
/**
* Retrieves the storage root of an account.
* @param _address Address of the account to access.
* @return Corresponding storage root.
*/
function getAccountStorageRoot(
address _address
)
override
public
view
returns (
bytes32
)
{
return accounts[_address].storageRoot;
}
/**
* Initializes a pending account (during CREATE or CREATE2) with the default values.
* @param _address Address of the account to initialize.
*/
function initPendingAccount(
address _address
)
override
public
authenticated
{
Lib_OVMCodec.Account storage account = accounts[_address];
account.nonce = 1;
account.storageRoot = EMPTY_ACCOUNT_STORAGE_ROOT;
account.codeHash = EMPTY_ACCOUNT_CODE_HASH;
account.isFresh = true;
}
/**
* Finalizes the creation of a pending account (during CREATE or CREATE2).
* @param _address Address of the account to finalize.
* @param _ethAddress Address of the account's associated contract on Ethereum.
* @param _codeHash Hash of the account's code.
*/
function commitPendingAccount(
address _address,
address _ethAddress,
bytes32 _codeHash
)
override
public
authenticated
{
Lib_OVMCodec.Account storage account = accounts[_address];
account.ethAddress = _ethAddress;
account.codeHash = _codeHash;
}
/**
* Checks whether an account has already been retrieved, and marks it as retrieved if not.
* @param _address Address of the account to check.
* @return Whether or not the account was already loaded.
*/
function testAndSetAccountLoaded(
address _address
)
override
public
authenticated
returns (
bool
)
{
return _testAndSetItemState(
_getItemHash(_address),
ItemState.ITEM_LOADED
);
}
/**
* Checks whether an account has already been modified, and marks it as modified if not.
* @param _address Address of the account to check.
* @return Whether or not the account was already modified.
*/
function testAndSetAccountChanged(
address _address
)
override
public
authenticated
returns (
bool
)
{
return _testAndSetItemState(
_getItemHash(_address),
ItemState.ITEM_CHANGED
);
}
/**
* Attempts to mark an account as committed.
* @param _address Address of the account to commit.
* @return Whether or not the account was committed.
*/
function commitAccount(
address _address
)
override
public
authenticated
returns (
bool
)
{
bytes32 item = _getItemHash(_address);
if (itemStates[item] != ItemState.ITEM_CHANGED) {
return false;
}
itemStates[item] = ItemState.ITEM_COMMITTED;
totalUncommittedAccounts -= 1;
return true;
}
/**
* Increments the total number of uncommitted accounts.
*/
function incrementTotalUncommittedAccounts()
override
public
authenticated
{
totalUncommittedAccounts += 1;
}
/**
* Gets the total number of uncommitted accounts.
* @return Total uncommitted accounts.
*/
function getTotalUncommittedAccounts()
override
public
view
returns (
uint256
)
{
return totalUncommittedAccounts;
}
/**
* Checks whether a given account was changed during execution.
* @param _address Address to check.
* @return Whether or not the account was changed.
*/
function wasAccountChanged(
address _address
)
override
public
view
returns (
bool
)
{
bytes32 item = _getItemHash(_address);
return itemStates[item] >= ItemState.ITEM_CHANGED;
}
/**
* Checks whether a given account was committed after execution.
* @param _address Address to check.
* @return Whether or not the account was committed.
*/
function wasAccountCommitted(
address _address
)
override
public
view
returns (
bool
)
{
bytes32 item = _getItemHash(_address);
return itemStates[item] >= ItemState.ITEM_COMMITTED;
}
/************************************
* Public Functions: Storage Access *
************************************/
/**
* Changes a contract storage slot value.
* @param _contract Address of the contract to modify.
* @param _key 32 byte storage slot key.
* @param _value 32 byte storage slot value.
*/
function putContractStorage(
address _contract,
bytes32 _key,
bytes32 _value
)
override
public
authenticated
{
// A hilarious optimization. `SSTORE`ing a value of `bytes32(0)` is common enough that it's
// worth populating this with a non-zero value in advance (during the fraud proof
// initialization phase) to cut the execution-time cost down to 5000 gas.
contractStorage[_contract][_key] = _value ^ STORAGE_XOR_VALUE;
// Only used when initially populating the contract storage. OVM_ExecutionManager will
// perform a `hasContractStorage` INVALID_STATE_ACCESS check before putting any contract
// storage because writing to zero when the actual value is nonzero causes a gas
// discrepancy. Could be moved into a new `putVerifiedContractStorage` function, or
// something along those lines.
if (verifiedContractStorage[_contract][_key] == false) {
verifiedContractStorage[_contract][_key] = true;
}
}
/**
* Retrieves a contract storage slot value.
* @param _contract Address of the contract to access.
* @param _key 32 byte storage slot key.
* @return 32 byte storage slot value.
*/
function getContractStorage(
address _contract,
bytes32 _key
)
override
public
view
returns (
bytes32
)
{
// Storage XOR system doesn't work for newly created contracts that haven't set this
// storage slot value yet.
if (
verifiedContractStorage[_contract][_key] == false
&& accounts[_contract].isFresh
) {
return bytes32(0);
}
// See `putContractStorage` for more information about the XOR here.
return contractStorage[_contract][_key] ^ STORAGE_XOR_VALUE;
}
/**
* Checks whether a contract storage slot exists in the state.
* @param _contract Address of the contract to access.
* @param _key 32 byte storage slot key.
* @return Whether or not the key was set in the state.
*/
function hasContractStorage(
address _contract,
bytes32 _key
)
override
public
view
returns (
bool
)
{
return verifiedContractStorage[_contract][_key] || accounts[_contract].isFresh;
}
/**
* Checks whether a storage slot has already been retrieved, and marks it as retrieved if not.
* @param _contract Address of the contract to check.
* @param _key 32 byte storage slot key.
* @return Whether or not the slot was already loaded.
*/
function testAndSetContractStorageLoaded(
address _contract,
bytes32 _key
)
override
public
authenticated
returns (
bool
)
{
return _testAndSetItemState(
_getItemHash(_contract, _key),
ItemState.ITEM_LOADED
);
}
/**
* Checks whether a storage slot has already been modified, and marks it as modified if not.
* @param _contract Address of the contract to check.
* @param _key 32 byte storage slot key.
* @return Whether or not the slot was already modified.
*/
function testAndSetContractStorageChanged(
address _contract,
bytes32 _key
)
override
public
authenticated
returns (
bool
)
{
return _testAndSetItemState(
_getItemHash(_contract, _key),
ItemState.ITEM_CHANGED
);
}
/**
* Attempts to mark a storage slot as committed.
* @param _contract Address of the account to commit.
* @param _key 32 byte slot key to commit.
* @return Whether or not the slot was committed.
*/
function commitContractStorage(
address _contract,
bytes32 _key
)
override
public
authenticated
returns (
bool
)
{
bytes32 item = _getItemHash(_contract, _key);
if (itemStates[item] != ItemState.ITEM_CHANGED) {
return false;
}
itemStates[item] = ItemState.ITEM_COMMITTED;
totalUncommittedContractStorage -= 1;
return true;
}
/**
* Increments the total number of uncommitted storage slots.
*/
function incrementTotalUncommittedContractStorage()
override
public
authenticated
{
totalUncommittedContractStorage += 1;
}
/**
* Gets the total number of uncommitted storage slots.
* @return Total uncommitted storage slots.
*/
function getTotalUncommittedContractStorage()
override
public
view
returns (
uint256
)
{
return totalUncommittedContractStorage;
}
/**
* Checks whether a given storage slot was changed during execution.
* @param _contract Address to check.
* @param _key Key of the storage slot to check.
* @return Whether or not the storage slot was changed.
*/
function wasContractStorageChanged(
address _contract,
bytes32 _key
)
override
public
view
returns (
bool
)
{
bytes32 item = _getItemHash(_contract, _key);
return itemStates[item] >= ItemState.ITEM_CHANGED;
}
/**
* Checks whether a given storage slot was committed after execution.
* @param _contract Address to check.
* @param _key Key of the storage slot to check.
* @return Whether or not the storage slot was committed.
*/
function wasContractStorageCommitted(
address _contract,
bytes32 _key
)
override
public
view
returns (
bool
)
{
bytes32 item = _getItemHash(_contract, _key);
return itemStates[item] >= ItemState.ITEM_COMMITTED;
}
/**********************
* Internal Functions *
**********************/
/**
* Generates a unique hash for an address.
* @param _address Address to generate a hash for.
* @return Unique hash for the given address.
*/
function _getItemHash(
address _address
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(_address));
}
/**
* Generates a unique hash for an address/key pair.
* @param _contract Address to generate a hash for.
* @param _key Key to generate a hash for.
* @return Unique hash for the given pair.
*/
function _getItemHash(
address _contract,
bytes32 _key
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(
_contract,
_key
));
}
/**
* Checks whether an item is in a particular state (ITEM_LOADED or ITEM_CHANGED) and sets the
* item to the provided state if not.
* @param _item 32 byte item ID to check.
* @param _minItemState Minimum state that must be satisfied by the item.
* @return Whether or not the item was already in the state.
*/
function _testAndSetItemState(
bytes32 _item,
ItemState _minItemState
)
internal
returns (
bool
)
{
bool wasItemState = itemStates[_item] >= _minItemState;
if (wasItemState == false) {
itemStates[_item] = _minItemState;
}
return wasItemState;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Interface Imports */
import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol";
import { iOVM_StateManagerFactory } from "../../iOVM/execution/iOVM_StateManagerFactory.sol";
/* Contract Imports */
import { OVM_StateManager } from "./OVM_StateManager.sol";
/**
* @title OVM_StateManagerFactory
* @dev The State Manager Factory is called by a State Transitioner's init code, to create a new
* State Manager for use in the Fraud Verification process.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_StateManagerFactory is iOVM_StateManagerFactory {
/********************
* Public Functions *
********************/
/**
* Creates a new OVM_StateManager
* @param _owner Owner of the created contract.
* @return New OVM_StateManager instance.
*/
function create(
address _owner
)
override
public
returns (
iOVM_StateManager
)
{
return new OVM_StateManager(_owner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/**
* @title iOVM_StateManager
*/
interface iOVM_StateManager {
/*******************
* Data Structures *
*******************/
enum ItemState {
ITEM_UNTOUCHED,
ITEM_LOADED,
ITEM_CHANGED,
ITEM_COMMITTED
}
/***************************
* Public Functions: Misc *
***************************/
function isAuthenticated(address _address) external view returns (bool);
/***************************
* Public Functions: Setup *
***************************/
function owner() external view returns (address _owner);
function ovmExecutionManager() external view returns (address _ovmExecutionManager);
function setExecutionManager(address _ovmExecutionManager) external;
/************************************
* Public Functions: Account Access *
************************************/
function putAccount(address _address, Lib_OVMCodec.Account memory _account) external;
function putEmptyAccount(address _address) external;
function getAccount(address _address) external view returns (Lib_OVMCodec.Account memory _account);
function hasAccount(address _address) external view returns (bool _exists);
function hasEmptyAccount(address _address) external view returns (bool _exists);
function setAccountNonce(address _address, uint256 _nonce) external;
function getAccountNonce(address _address) external view returns (uint256 _nonce);
function getAccountEthAddress(address _address) external view returns (address _ethAddress);
function getAccountStorageRoot(address _address) external view returns (bytes32 _storageRoot);
function initPendingAccount(address _address) external;
function commitPendingAccount(address _address, address _ethAddress, bytes32 _codeHash) external;
function testAndSetAccountLoaded(address _address) external returns (bool _wasAccountAlreadyLoaded);
function testAndSetAccountChanged(address _address) external returns (bool _wasAccountAlreadyChanged);
function commitAccount(address _address) external returns (bool _wasAccountCommitted);
function incrementTotalUncommittedAccounts() external;
function getTotalUncommittedAccounts() external view returns (uint256 _total);
function wasAccountChanged(address _address) external view returns (bool);
function wasAccountCommitted(address _address) external view returns (bool);
/************************************
* Public Functions: Storage Access *
************************************/
function putContractStorage(address _contract, bytes32 _key, bytes32 _value) external;
function getContractStorage(address _contract, bytes32 _key) external view returns (bytes32 _value);
function hasContractStorage(address _contract, bytes32 _key) external view returns (bool _exists);
function testAndSetContractStorageLoaded(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyLoaded);
function testAndSetContractStorageChanged(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyChanged);
function commitContractStorage(address _contract, bytes32 _key) external returns (bool _wasContractStorageCommitted);
function incrementTotalUncommittedContractStorage() external;
function getTotalUncommittedContractStorage() external view returns (uint256 _total);
function wasContractStorageChanged(address _contract, bytes32 _key) external view returns (bool);
function wasContractStorageCommitted(address _contract, bytes32 _key) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Contract Imports */
import { iOVM_StateManager } from "./iOVM_StateManager.sol";
/**
* @title iOVM_StateManagerFactory
*/
interface iOVM_StateManagerFactory {
/***************************************
* Public Functions: Contract Creation *
***************************************/
function create(
address _owner
)
external
returns (
iOVM_StateManager _ovmStateManager
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol";
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol";
import { Lib_Bytes32Utils } from "../utils/Lib_Bytes32Utils.sol";
import { Lib_SafeExecutionManagerWrapper } from "../../libraries/wrappers/Lib_SafeExecutionManagerWrapper.sol";
/**
* @title Lib_OVMCodec
*/
library Lib_OVMCodec {
/*********
* Enums *
*********/
enum EOASignatureType {
EIP155_TRANSACTION,
ETH_SIGNED_MESSAGE
}
enum QueueOrigin {
SEQUENCER_QUEUE,
L1TOL2_QUEUE
}
/***********
* Structs *
***********/
struct Account {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
address ethAddress;
bool isFresh;
}
struct EVMAccount {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
struct ChainBatchHeader {
uint256 batchIndex;
bytes32 batchRoot;
uint256 batchSize;
uint256 prevTotalElements;
bytes extraData;
}
struct ChainInclusionProof {
uint256 index;
bytes32[] siblings;
}
struct Transaction {
uint256 timestamp;
uint256 blockNumber;
QueueOrigin l1QueueOrigin;
address l1TxOrigin;
address entrypoint;
uint256 gasLimit;
bytes data;
}
struct TransactionChainElement {
bool isSequenced;
uint256 queueIndex; // QUEUED TX ONLY
uint256 timestamp; // SEQUENCER TX ONLY
uint256 blockNumber; // SEQUENCER TX ONLY
bytes txData; // SEQUENCER TX ONLY
}
struct QueueElement {
bytes32 transactionHash;
uint40 timestamp;
uint40 blockNumber;
}
struct EIP155Transaction {
uint256 nonce;
uint256 gasPrice;
uint256 gasLimit;
address to;
uint256 value;
bytes data;
uint256 chainId;
}
/**********************
* Internal Functions *
**********************/
/**
* Decodes an EOA transaction (i.e., native Ethereum RLP encoding).
* @param _transaction Encoded EOA transaction.
* @return Transaction decoded into a struct.
*/
function decodeEIP155Transaction(
bytes memory _transaction,
bool _isEthSignedMessage
)
internal
pure
returns (
EIP155Transaction memory
)
{
if (_isEthSignedMessage) {
(
uint256 _nonce,
uint256 _gasLimit,
uint256 _gasPrice,
uint256 _chainId,
address _to,
bytes memory _data
) = abi.decode(
_transaction,
(uint256, uint256, uint256, uint256, address ,bytes)
);
return EIP155Transaction({
nonce: _nonce,
gasPrice: _gasPrice,
gasLimit: _gasLimit,
to: _to,
value: 0,
data: _data,
chainId: _chainId
});
} else {
Lib_RLPReader.RLPItem[] memory decoded = Lib_RLPReader.readList(_transaction);
return EIP155Transaction({
nonce: Lib_RLPReader.readUint256(decoded[0]),
gasPrice: Lib_RLPReader.readUint256(decoded[1]),
gasLimit: Lib_RLPReader.readUint256(decoded[2]),
to: Lib_RLPReader.readAddress(decoded[3]),
value: Lib_RLPReader.readUint256(decoded[4]),
data: Lib_RLPReader.readBytes(decoded[5]),
chainId: Lib_RLPReader.readUint256(decoded[6])
});
}
}
/**
* Decompresses a compressed EIP155 transaction.
* @param _transaction Compressed EIP155 transaction bytes.
* @return Transaction parsed into a struct.
*/
function decompressEIP155Transaction(
bytes memory _transaction
)
internal
returns (
EIP155Transaction memory
)
{
return EIP155Transaction({
gasLimit: Lib_BytesUtils.toUint24(_transaction, 0),
gasPrice: uint256(Lib_BytesUtils.toUint24(_transaction, 3)) * 1000000,
nonce: Lib_BytesUtils.toUint24(_transaction, 6),
to: Lib_BytesUtils.toAddress(_transaction, 9),
data: Lib_BytesUtils.slice(_transaction, 29),
chainId: Lib_SafeExecutionManagerWrapper.safeCHAINID(),
value: 0
});
}
/**
* Encodes an EOA transaction back into the original transaction.
* @param _transaction EIP155transaction to encode.
* @param _isEthSignedMessage Whether or not this was an eth signed message.
* @return Encoded transaction.
*/
function encodeEIP155Transaction(
EIP155Transaction memory _transaction,
bool _isEthSignedMessage
)
internal
pure
returns (
bytes memory
)
{
if (_isEthSignedMessage) {
return abi.encode(
_transaction.nonce,
_transaction.gasLimit,
_transaction.gasPrice,
_transaction.chainId,
_transaction.to,
_transaction.data
);
} else {
bytes[] memory raw = new bytes[](9);
raw[0] = Lib_RLPWriter.writeUint(_transaction.nonce);
raw[1] = Lib_RLPWriter.writeUint(_transaction.gasPrice);
raw[2] = Lib_RLPWriter.writeUint(_transaction.gasLimit);
if (_transaction.to == address(0)) {
raw[3] = Lib_RLPWriter.writeBytes('');
} else {
raw[3] = Lib_RLPWriter.writeAddress(_transaction.to);
}
raw[4] = Lib_RLPWriter.writeUint(0);
raw[5] = Lib_RLPWriter.writeBytes(_transaction.data);
raw[6] = Lib_RLPWriter.writeUint(_transaction.chainId);
raw[7] = Lib_RLPWriter.writeBytes(bytes(''));
raw[8] = Lib_RLPWriter.writeBytes(bytes(''));
return Lib_RLPWriter.writeList(raw);
}
}
/**
* Encodes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Encoded transaction bytes.
*/
function encodeTransaction(
Transaction memory _transaction
)
internal
pure
returns (
bytes memory
)
{
return abi.encodePacked(
_transaction.timestamp,
_transaction.blockNumber,
_transaction.l1QueueOrigin,
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
);
}
/**
* Hashes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Hashed transaction
*/
function hashTransaction(
Transaction memory _transaction
)
internal
pure
returns (
bytes32
)
{
return keccak256(encodeTransaction(_transaction));
}
/**
* Converts an OVM account to an EVM account.
* @param _in OVM account to convert.
* @return Converted EVM account.
*/
function toEVMAccount(
Account memory _in
)
internal
pure
returns (
EVMAccount memory
)
{
return EVMAccount({
nonce: _in.nonce,
balance: _in.balance,
storageRoot: _in.storageRoot,
codeHash: _in.codeHash
});
}
/**
* @notice RLP-encodes an account state struct.
* @param _account Account state struct.
* @return RLP-encoded account state.
*/
function encodeEVMAccount(
EVMAccount memory _account
)
internal
pure
returns (
bytes memory
)
{
bytes[] memory raw = new bytes[](4);
// Unfortunately we can't create this array outright because
// Lib_RLPWriter.writeList will reject fixed-size arrays. Assigning
// index-by-index circumvents this issue.
raw[0] = Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(
bytes32(_account.nonce)
)
);
raw[1] = Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(
bytes32(_account.balance)
)
);
raw[2] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.storageRoot));
raw[3] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.codeHash));
return Lib_RLPWriter.writeList(raw);
}
/**
* @notice Decodes an RLP-encoded account state into a useful struct.
* @param _encoded RLP-encoded account state.
* @return Account state struct.
*/
function decodeEVMAccount(
bytes memory _encoded
)
internal
pure
returns (
EVMAccount memory
)
{
Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded);
return EVMAccount({
nonce: Lib_RLPReader.readUint256(accountState[0]),
balance: Lib_RLPReader.readUint256(accountState[1]),
storageRoot: Lib_RLPReader.readBytes32(accountState[2]),
codeHash: Lib_RLPReader.readBytes32(accountState[3])
});
}
/**
* Calculates a hash for a given batch header.
* @param _batchHeader Header to hash.
* @return Hash of the header.
*/
function hashBatchHeader(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
internal
pure
returns (
bytes32
)
{
return keccak256(
abi.encode(
_batchHeader.batchRoot,
_batchHeader.batchSize,
_batchHeader.prevTotalElements,
_batchHeader.extraData
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_RLPReader
* @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]).
*/
library Lib_RLPReader {
/*************
* Constants *
*************/
uint256 constant internal MAX_LIST_LENGTH = 32;
/*********
* Enums *
*********/
enum RLPItemType {
DATA_ITEM,
LIST_ITEM
}
/***********
* Structs *
***********/
struct RLPItem {
uint256 length;
uint256 ptr;
}
/**********************
* Internal Functions *
**********************/
/**
* Converts bytes to a reference to memory position and length.
* @param _in Input bytes to convert.
* @return Output memory reference.
*/
function toRLPItem(
bytes memory _in
)
internal
pure
returns (
RLPItem memory
)
{
uint256 ptr;
assembly {
ptr := add(_in, 32)
}
return RLPItem({
length: _in.length,
ptr: ptr
});
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(
RLPItem memory _in
)
internal
pure
returns (
RLPItem[] memory
)
{
(
uint256 listOffset,
,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.LIST_ITEM,
"Invalid RLP list value."
);
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over
// the entire input, we'd have to loop twice to accurately size this array. It's easier to
// simply set a reasonable maximum list length and decrease the size before we finish.
RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH);
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
require(
itemCount < MAX_LIST_LENGTH,
"Provided RLP list exceeds max list length."
);
(
uint256 itemOffset,
uint256 itemLength,
) = _decodeLength(RLPItem({
length: _in.length - offset,
ptr: _in.ptr + offset
}));
out[itemCount] = RLPItem({
length: itemLength + itemOffset,
ptr: _in.ptr + offset
});
itemCount += 1;
offset += itemOffset + itemLength;
}
// Decrease the array size to match the actual item count.
assembly {
mstore(out, itemCount)
}
return out;
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(
bytes memory _in
)
internal
pure
returns (
RLPItem[] memory
)
{
return readList(
toRLPItem(_in)
);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(
RLPItem memory _in
)
internal
pure
returns (
bytes memory
)
{
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes value."
);
return _copy(_in.ptr, itemOffset, itemLength);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(
bytes memory _in
)
internal
pure
returns (
bytes memory
)
{
return readBytes(
toRLPItem(_in)
);
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(
RLPItem memory _in
)
internal
pure
returns (
string memory
)
{
return string(readBytes(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(
bytes memory _in
)
internal
pure
returns (
string memory
)
{
return readString(
toRLPItem(_in)
);
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(
RLPItem memory _in
)
internal
pure
returns (
bytes32
)
{
require(
_in.length <= 33,
"Invalid RLP bytes32 value."
);
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes32 value."
);
uint256 ptr = _in.ptr + itemOffset;
bytes32 out;
assembly {
out := mload(ptr)
// Shift the bytes over to match the item size.
if lt(itemLength, 32) {
out := div(out, exp(256, sub(32, itemLength)))
}
}
return out;
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(
bytes memory _in
)
internal
pure
returns (
bytes32
)
{
return readBytes32(
toRLPItem(_in)
);
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(
RLPItem memory _in
)
internal
pure
returns (
uint256
)
{
return uint256(readBytes32(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(
bytes memory _in
)
internal
pure
returns (
uint256
)
{
return readUint256(
toRLPItem(_in)
);
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(
RLPItem memory _in
)
internal
pure
returns (
bool
)
{
require(
_in.length == 1,
"Invalid RLP boolean value."
);
uint256 ptr = _in.ptr;
uint256 out;
assembly {
out := byte(0, mload(ptr))
}
require(
out == 0 || out == 1,
"Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1"
);
return out != 0;
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(
bytes memory _in
)
internal
pure
returns (
bool
)
{
return readBool(
toRLPItem(_in)
);
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(
RLPItem memory _in
)
internal
pure
returns (
address
)
{
if (_in.length == 1) {
return address(0);
}
require(
_in.length == 21,
"Invalid RLP address value."
);
return address(readUint256(_in));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(
bytes memory _in
)
internal
pure
returns (
address
)
{
return readAddress(
toRLPItem(_in)
);
}
/**
* Reads the raw bytes of an RLP item.
* @param _in RLP item to read.
* @return Raw RLP bytes.
*/
function readRawBytes(
RLPItem memory _in
)
internal
pure
returns (
bytes memory
)
{
return _copy(_in);
}
/*********************
* Private Functions *
*********************/
/**
* Decodes the length of an RLP item.
* @param _in RLP item to decode.
* @return Offset of the encoded data.
* @return Length of the encoded data.
* @return RLP item type (LIST_ITEM or DATA_ITEM).
*/
function _decodeLength(
RLPItem memory _in
)
private
pure
returns (
uint256,
uint256,
RLPItemType
)
{
require(
_in.length > 0,
"RLP item cannot be null."
);
uint256 ptr = _in.ptr;
uint256 prefix;
assembly {
prefix := byte(0, mload(ptr))
}
if (prefix <= 0x7f) {
// Single byte.
return (0, 1, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xb7) {
// Short string.
uint256 strLen = prefix - 0x80;
require(
_in.length > strLen,
"Invalid RLP short string."
);
return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) {
// Long string.
uint256 lenOfStrLen = prefix - 0xb7;
require(
_in.length > lenOfStrLen,
"Invalid RLP long string length."
);
uint256 strLen;
assembly {
// Pick out the string length.
strLen := div(
mload(add(ptr, 1)),
exp(256, sub(32, lenOfStrLen))
)
}
require(
_in.length > lenOfStrLen + strLen,
"Invalid RLP long string."
);
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) {
// Short list.
uint256 listLen = prefix - 0xc0;
require(
_in.length > listLen,
"Invalid RLP short list."
);
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
// Long list.
uint256 lenOfListLen = prefix - 0xf7;
require(
_in.length > lenOfListLen,
"Invalid RLP long list length."
);
uint256 listLen;
assembly {
// Pick out the list length.
listLen := div(
mload(add(ptr, 1)),
exp(256, sub(32, lenOfListLen))
)
}
require(
_in.length > lenOfListLen + listLen,
"Invalid RLP long list."
);
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
}
}
/**
* Copies the bytes from a memory location.
* @param _src Pointer to the location to read from.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Copied bytes.
*/
function _copy(
uint256 _src,
uint256 _offset,
uint256 _length
)
private
pure
returns (
bytes memory
)
{
bytes memory out = new bytes(_length);
if (out.length == 0) {
return out;
}
uint256 src = _src + _offset;
uint256 dest;
assembly {
dest := add(out, 32)
}
// Copy over as many complete words as we can.
for (uint256 i = 0; i < _length / 32; i++) {
assembly {
mstore(dest, mload(src))
}
src += 32;
dest += 32;
}
// Pick out the remaining bytes.
uint256 mask = 256 ** (32 - (_length % 32)) - 1;
assembly {
mstore(
dest,
or(
and(mload(src), not(mask)),
and(mload(dest), mask)
)
)
}
return out;
}
/**
* Copies an RLP item into bytes.
* @param _in RLP item to copy.
* @return Copied bytes.
*/
function _copy(
RLPItem memory _in
)
private
pure
returns (
bytes memory
)
{
return _copy(_in.ptr, 0, _in.length);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol";
/**
* @title Lib_RLPWriter
* @author Bakaoh (with modifications)
*/
library Lib_RLPWriter {
/**********************
* Internal Functions *
**********************/
/**
* RLP encodes a byte string.
* @param _in The byte string to encode.
* @return _out The RLP encoded string in bytes.
*/
function writeBytes(
bytes memory _in
)
internal
pure
returns (
bytes memory _out
)
{
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* RLP encodes a list of RLP encoded byte byte strings.
* @param _in The list of RLP encoded byte strings.
* @return _out The RLP encoded list of items in bytes.
*/
function writeList(
bytes[] memory _in
)
internal
pure
returns (
bytes memory _out
)
{
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* RLP encodes a string.
* @param _in The string to encode.
* @return _out The RLP encoded string in bytes.
*/
function writeString(
string memory _in
)
internal
pure
returns (
bytes memory _out
)
{
return writeBytes(bytes(_in));
}
/**
* RLP encodes an address.
* @param _in The address to encode.
* @return _out The RLP encoded address in bytes.
*/
function writeAddress(
address _in
)
internal
pure
returns (
bytes memory _out
)
{
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a uint.
* @param _in The uint256 to encode.
* @return _out The RLP encoded uint256 in bytes.
*/
function writeUint(
uint256 _in
)
internal
pure
returns (
bytes memory _out
)
{
return writeBytes(_toBinary(_in));
}
/**
* RLP encodes a bool.
* @param _in The bool to encode.
* @return _out The RLP encoded bool in bytes.
*/
function writeBool(
bool _in
)
internal
pure
returns (
bytes memory _out
)
{
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/*********************
* Private Functions *
*********************/
/**
* Encode the first byte, followed by the `len` in binary form if `length` is more than 55.
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
* @return _encoded RLP encoded bytes.
*/
function _writeLength(
uint256 _len,
uint256 _offset
)
private
pure
returns (
bytes memory _encoded
)
{
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = byte(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = byte(uint8(lenLen) + uint8(_offset) + 55);
for(i = 1; i <= lenLen; i++) {
encoded[i] = byte(uint8((_len / (256**(lenLen-i))) % 256));
}
}
return encoded;
}
/**
* Encode integer in big endian binary form with no leading zeroes.
* @notice TODO: This should be optimized with assembly to save gas costs.
* @param _x The integer to encode.
* @return _binary RLP encoded bytes.
*/
function _toBinary(
uint256 _x
)
private
pure
returns (
bytes memory _binary
)
{
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* Copies a piece of memory to another location.
* @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol.
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
)
private
pure
{
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* Flattens a list of byte strings into one byte string.
* @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol.
* @param _list List of byte strings to flatten.
* @return _flattened The flattened byte string.
*/
function _flatten(
bytes[] memory _list
)
private
pure
returns (
bytes memory _flattened
)
{
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly { flattenedPtr := add(flattened, 0x20) }
for(i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly { listPtr := add(item, 0x20)}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_Byte32Utils
*/
library Lib_Bytes32Utils {
/**********************
* Internal Functions *
**********************/
/**
* Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true."
* @param _in Input bytes32 value.
* @return Bytes32 as a boolean.
*/
function toBool(
bytes32 _in
)
internal
pure
returns (
bool
)
{
return _in != 0;
}
/**
* Converts a boolean to a bytes32 value.
* @param _in Input boolean value.
* @return Boolean as a bytes32.
*/
function fromBool(
bool _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(_in ? 1 : 0));
}
/**
* Converts a bytes32 value to an address. Takes the *last* 20 bytes.
* @param _in Input bytes32 value.
* @return Bytes32 as an address.
*/
function toAddress(
bytes32 _in
)
internal
pure
returns (
address
)
{
return address(uint160(uint256(_in)));
}
/**
* Converts an address to a bytes32.
* @param _in Input address value.
* @return Address as a bytes32.
*/
function fromAddress(
address _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(_in));
}
/**
* Removes the leading zeros from a bytes32 value and returns a new (smaller) bytes value.
* @param _in Input bytes32 value.
* @return Bytes32 without any leading zeros.
*/
function removeLeadingZeros(
bytes32 _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory out;
assembly {
// Figure out how many leading zero bytes to remove.
let shift := 0
for { let i := 0 } and(lt(i, 32), eq(byte(i, _in), 0)) { i := add(i, 1) } {
shift := add(shift, 1)
}
// Reserve some space for our output and fix the free memory pointer.
out := mload(0x40)
mstore(0x40, add(out, 0x40))
// Shift the value and store it into the output bytes.
mstore(add(out, 0x20), shl(mul(shift, 8), _in))
// Store the new size (with leading zero bytes removed) in the output byte size.
mstore(out, sub(32, shift))
}
return out;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_BytesUtils
*/
library Lib_BytesUtils {
/**********************
* Internal Functions *
**********************/
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
)
internal
pure
returns (bytes memory)
{
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function slice(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (bytes memory)
{
if (_bytes.length - _start == 0) {
return bytes('');
}
return slice(_bytes, _start, _bytes.length - _start);
}
function toBytes32PadLeft(
bytes memory _bytes
)
internal
pure
returns (bytes32)
{
bytes32 ret;
uint256 len = _bytes.length <= 32 ? _bytes.length : 32;
assembly {
ret := shr(mul(sub(32, len), 8), mload(add(_bytes, 32)))
}
return ret;
}
function toBytes32(
bytes memory _bytes
)
internal
pure
returns (bytes32)
{
if (_bytes.length < 32) {
bytes32 ret;
assembly {
ret := mload(add(_bytes, 32))
}
return ret;
}
return abi.decode(_bytes,(bytes32)); // will truncate if input length > 32 bytes
}
function toUint256(
bytes memory _bytes
)
internal
pure
returns (uint256)
{
return uint256(toBytes32(_bytes));
}
function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {
require(_start + 3 >= _start, "toUint24_overflow");
require(_bytes.length >= _start + 3 , "toUint24_outOfBounds");
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
require(_start + 1 >= _start, "toUint8_overflow");
require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_start + 20 >= _start, "toAddress_overflow");
require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toNibbles(
bytes memory _bytes
)
internal
pure
returns (bytes memory)
{
bytes memory nibbles = new bytes(_bytes.length * 2);
for (uint256 i = 0; i < _bytes.length; i++) {
nibbles[i * 2] = _bytes[i] >> 4;
nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16);
}
return nibbles;
}
function fromNibbles(
bytes memory _bytes
)
internal
pure
returns (bytes memory)
{
bytes memory ret = new bytes(_bytes.length / 2);
for (uint256 i = 0; i < ret.length; i++) {
ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]);
}
return ret;
}
function equal(
bytes memory _bytes,
bytes memory _other
)
internal
pure
returns (bool)
{
return keccak256(_bytes) == keccak256(_other);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/**
* @title Lib_ErrorUtils
*/
library Lib_ErrorUtils {
/**********************
* Internal Functions *
**********************/
/**
* Encodes an error string into raw solidity-style revert data.
* (i.e. ascii bytes, prefixed with bytes4(keccak("Error(string))"))
* Ref: https://docs.soliditylang.org/en/v0.8.2/control-structures.html?highlight=Error(string)#panic-via-assert-and-error-via-require
* @param _reason Reason for the reversion.
* @return Standard solidity revert data for the given reason.
*/
function encodeRevertString(
string memory _reason
)
internal
pure
returns (
bytes memory
)
{
return abi.encodeWithSignature(
"Error(string)",
_reason
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_ErrorUtils } from "../utils/Lib_ErrorUtils.sol";
/**
* @title Lib_SafeExecutionManagerWrapper
* @dev The Safe Execution Manager Wrapper provides functions which facilitate writing OVM safe
* code using the standard solidity compiler, by routing all its operations through the Execution
* Manager.
*
* Compiler used: solc
* Runtime target: OVM
*/
library Lib_SafeExecutionManagerWrapper {
/**********************
* Internal Functions *
**********************/
/**
* Performs a safe ovmCALL.
* @param _gasLimit Gas limit for the call.
* @param _target Address to call.
* @param _calldata Data to send to the call.
* @return _success Whether or not the call reverted.
* @return _returndata Data returned by the call.
*/
function safeCALL(
uint256 _gasLimit,
address _target,
bytes memory _calldata
)
internal
returns (
bool _success,
bytes memory _returndata
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmCALL(uint256,address,bytes)",
_gasLimit,
_target,
_calldata
)
);
return abi.decode(returndata, (bool, bytes));
}
/**
* Performs a safe ovmDELEGATECALL.
* @param _gasLimit Gas limit for the call.
* @param _target Address to call.
* @param _calldata Data to send to the call.
* @return _success Whether or not the call reverted.
* @return _returndata Data returned by the call.
*/
function safeDELEGATECALL(
uint256 _gasLimit,
address _target,
bytes memory _calldata
)
internal
returns (
bool _success,
bytes memory _returndata
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmDELEGATECALL(uint256,address,bytes)",
_gasLimit,
_target,
_calldata
)
);
return abi.decode(returndata, (bool, bytes));
}
/**
* Performs a safe ovmCREATE call.
* @param _gasLimit Gas limit for the creation.
* @param _bytecode Code for the new contract.
* @return _contract Address of the created contract.
*/
function safeCREATE(
uint256 _gasLimit,
bytes memory _bytecode
)
internal
returns (
address,
bytes memory
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
_gasLimit,
abi.encodeWithSignature(
"ovmCREATE(bytes)",
_bytecode
)
);
return abi.decode(returndata, (address, bytes));
}
/**
* Performs a safe ovmEXTCODESIZE call.
* @param _contract Address of the contract to query the size of.
* @return _EXTCODESIZE Size of the requested contract in bytes.
*/
function safeEXTCODESIZE(
address _contract
)
internal
returns (
uint256 _EXTCODESIZE
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmEXTCODESIZE(address)",
_contract
)
);
return abi.decode(returndata, (uint256));
}
/**
* Performs a safe ovmCHAINID call.
* @return _CHAINID Result of calling ovmCHAINID.
*/
function safeCHAINID()
internal
returns (
uint256 _CHAINID
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmCHAINID()"
)
);
return abi.decode(returndata, (uint256));
}
/**
* Performs a safe ovmCALLER call.
* @return _CALLER Result of calling ovmCALLER.
*/
function safeCALLER()
internal
returns (
address _CALLER
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmCALLER()"
)
);
return abi.decode(returndata, (address));
}
/**
* Performs a safe ovmADDRESS call.
* @return _ADDRESS Result of calling ovmADDRESS.
*/
function safeADDRESS()
internal
returns (
address _ADDRESS
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmADDRESS()"
)
);
return abi.decode(returndata, (address));
}
/**
* Performs a safe ovmGETNONCE call.
* @return _nonce Result of calling ovmGETNONCE.
*/
function safeGETNONCE()
internal
returns (
uint256 _nonce
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmGETNONCE()"
)
);
return abi.decode(returndata, (uint256));
}
/**
* Performs a safe ovmINCREMENTNONCE call.
*/
function safeINCREMENTNONCE()
internal
{
_safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmINCREMENTNONCE()"
)
);
}
/**
* Performs a safe ovmCREATEEOA call.
* @param _messageHash Message hash which was signed by EOA
* @param _v v value of signature (0 or 1)
* @param _r r value of signature
* @param _s s value of signature
*/
function safeCREATEEOA(
bytes32 _messageHash,
uint8 _v,
bytes32 _r,
bytes32 _s
)
internal
{
_safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmCREATEEOA(bytes32,uint8,bytes32,bytes32)",
_messageHash,
_v,
_r,
_s
)
);
}
/**
* Performs a safe REVERT.
* @param _reason String revert reason to pass along with the REVERT.
*/
function safeREVERT(
string memory _reason
)
internal
{
_safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmREVERT(bytes)",
Lib_ErrorUtils.encodeRevertString(
_reason
)
)
);
}
/**
* Performs a safe "require".
* @param _condition Boolean condition that must be true or will revert.
* @param _reason String revert reason to pass along with the REVERT.
*/
function safeREQUIRE(
bool _condition,
string memory _reason
)
internal
{
if (!_condition) {
safeREVERT(
_reason
);
}
}
/**
* Performs a safe ovmSLOAD call.
*/
function safeSLOAD(
bytes32 _key
)
internal
returns (
bytes32
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmSLOAD(bytes32)",
_key
)
);
return abi.decode(returndata, (bytes32));
}
/**
* Performs a safe ovmSSTORE call.
*/
function safeSSTORE(
bytes32 _key,
bytes32 _value
)
internal
{
_safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmSSTORE(bytes32,bytes32)",
_key,
_value
)
);
}
/*********************
* Private Functions *
*********************/
/**
* Performs an ovm interaction and the necessary safety checks.
* @param _gasLimit Gas limit for the interaction.
* @param _calldata Data to send to the OVM_ExecutionManager (encoded with sighash).
* @return _returndata Data sent back by the OVM_ExecutionManager.
*/
function _safeExecutionManagerInteraction(
uint256 _gasLimit,
bytes memory _calldata
)
private
returns (
bytes memory _returndata
)
{
address ovmExecutionManager = msg.sender;
(
bool success,
bytes memory returndata
) = ovmExecutionManager.call{gas: _gasLimit}(_calldata);
if (success == false) {
assembly {
revert(add(returndata, 0x20), mload(returndata))
}
} else if (returndata.length == 1) {
assembly {
return(0, 1)
}
} else {
return returndata;
}
}
function _safeExecutionManagerInteraction(
bytes memory _calldata
)
private
returns (
bytes memory _returndata
)
{
return _safeExecutionManagerInteraction(
gasleft(),
_calldata
);
}
}
| * Retrieves the Ethereum address of an account. @param _address Address of the account to access. @return Corresponding Ethereum address./ | function getAccountEthAddress(
address _address
)
override
public
view
returns (
address
)
{
return accounts[_address].ethAddress;
}
| 6,068,971 | [
1,
6960,
326,
512,
18664,
379,
1758,
434,
392,
2236,
18,
225,
389,
2867,
5267,
434,
326,
2236,
358,
2006,
18,
327,
9557,
17863,
310,
512,
18664,
379,
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,
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,
445,
23393,
41,
451,
1887,
12,
203,
3639,
1758,
389,
2867,
203,
565,
262,
203,
3639,
3849,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
203,
5411,
1758,
203,
3639,
262,
203,
565,
288,
203,
3639,
327,
9484,
63,
67,
2867,
8009,
546,
1887,
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
]
|
./full_match/1/0xEb5D0a9268d3412F274f90D44aF3957501D3E315/sources/lib/USBT/src/USBT.sol | -------------------------------------- ERC165 -------------------------------------- | function supportsInterface(bytes4 interfaceId) external view virtual returns (bool) {
return type(IERC721Metadata).interfaceId == interfaceId || type(IERC721).interfaceId == interfaceId
|| type(IERC165).interfaceId == interfaceId;
}
| 2,926,780 | [
1,
2443,
13093,
2868,
4232,
39,
28275,
5375,
19134,
13465,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
3903,
1476,
5024,
1135,
261,
6430,
13,
288,
203,
3639,
327,
618,
12,
45,
654,
39,
27,
5340,
2277,
2934,
5831,
548,
422,
1560,
548,
747,
618,
12,
45,
654,
39,
27,
5340,
2934,
5831,
548,
422,
1560,
548,
203,
5411,
747,
618,
12,
45,
654,
39,
28275,
2934,
5831,
548,
422,
1560,
548,
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
]
|
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
uint256 num_reg_airlines = 0;
uint256 insuranceId = 0;
address private firstAirline; // First registered Airline
struct Airline {
bool isRegistered;
bool isAproved;
bool isFunded;
}
struct VoteSystem {
address[] addresses;
uint256 numVotes;
uint256 requiredVotes;
}
struct Flight {
address airline;
string flightCode;
uint256 timestamp;
uint8 statusCode;
bool isRegistered;
}
struct FlightInsurance {
address airline;
string flightCode;
bytes32 flightKey;
uint256 amountPayed;
uint256 amountToPay;
bool isRegistered;
bool isRefunded;
}
struct Passanger {
uint256 balance;
bool isRegistered;
uint256[] insuranceIds;
}
mapping(address => Airline) airlines; // Mapping for storing airlines
mapping(bytes32 => Flight) private flights;
mapping(address => VoteSystem) votes; // Mapping for the votes
mapping(address => uint256) airlineBalances; // Mapping for the balance of the airlines
mapping(address => uint256) private authorizedContracts;
mapping(address => Passanger) private passengers;
mapping(uint256 => FlightInsurance) private insurances;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
event AirlineRegistered(address _address);
event AirlineFunded(address _address, uint amount);
event AirlineAproved(address _address);
event AirlineVoted(address newAirline, address voter);
event FlightRegistered(address _address, string _flightCode, uint256 _timestamp);
event VotingRoundAdded(address _address);
event InsurancePurchased(address passenger, address airline, string flightCode, uint amountPayed);
event FlightStatusUpdated(address _address, string _flightCode, uint256 _timestamp, uint _statusCode);
event FlightInsuranceUpdated(uint insuranceId, address airline, string flightCode, uint amountToPay);
event InsuranceCredited(address passenger, string flightCode, uint amount);
event InsureeWithdrawn(address passenger, uint amount);
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
(
address airline
)
public
{
contractOwner = msg.sender;
_registerAirline(airline, true, true, false);
firstAirline = airline;
//_registerAirline(firstAirline);
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
modifier requireIsCallerAuthorized()
{
require(authorizedContracts[msg.sender] == 1, "Caller is not contract owner");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
requireContractOwner
{
operational = mode;
}
function isAirlineRegistered
(
address airline
)
external
requireIsOperational
returns(bool)
{
return airlines[airline].isRegistered;
}
function isAirlineAproved
(
address airline
)
external
requireIsOperational
returns(bool)
{
return airlines[airline].isAproved;
}
function isFlightRegistered
(
bytes32 flightKey
)
external
requireIsOperational
returns(bool)
{
return flights[flightKey].isRegistered;
}
function isPassengerRegistered
(
address passenger
)
external
requireIsOperational
returns(bool)
{
return passengers[passenger].isRegistered;
}
function authorizeCaller
(
address contractAddress
)
external
requireContractOwner
{
authorizedContracts[contractAddress] = 1;
}
function getAirlineStatus
(
address airline
)
external
requireIsOperational
returns
(
bool isRegistered,
bool isAproved,
bool isFunded
)
{
isRegistered = airlines[airline].isRegistered;
isAproved = airlines[airline].isAproved;
isFunded = airlines[airline].isFunded;
return (
isRegistered,
isAproved,
isFunded
);
}
function getFlightStatus
(
address airline,
string flightCode,
uint256 timestamp
)
returns(uint8)
{
bytes32 flightKey = _getFlightKey(airline, flightCode, timestamp);
return flights[flightKey].statusCode;
}
function getFirstAirline()
external
requireIsOperational
returns(address)
{
return firstAirline;
}
function isInsuranceFromFlight
(
bytes32 flightKey,
uint index
)
external
requireIsOperational
returns(bool)
{
return (insurances[index].flightKey == flightKey);
}
function getNumInsurances()
external
requireIsOperational
returns(uint)
{
return insuranceId;
}
function isPassengerEligibleForPayout
(
address passenger
)
external
constant
requireIsOperational
returns(bool)
{
bool isEligible = false;
for (uint i=0; i < passengers[passenger].insuranceIds.length; i++) {
uint insuranceId = passengers[passenger].insuranceIds[i];
if (insurances[insuranceId].amountToPay > 0)
{
isEligible = true;
break;
}
}
return isEligible;
}
function getInsurancePayedAmount
(
uint insuranceId
)
external
requireIsOperational
returns(uint)
{
return insurances[insuranceId].amountPayed;
}
function getPassengerBalance
(
address passenger
)
external
constant
requireIsOperational
returns(uint)
{
return passengers[passenger].balance;
}
function isAirlineFunded
(
address airline
)
external
requireIsOperational
returns(bool)
{
return airlines[airline].isFunded;
}
function getNumRegAirlines()
external
requireIsOperational
returns(uint)
{
return num_reg_airlines;
}
function getVotesInfo
(
address airline
)
external
requireIsOperational
returns
(
uint256 requiredVotes,
uint256 approvedVotes
)
{
requiredVotes = votes[airline].requiredVotes;
approvedVotes = votes[airline].numVotes;
return(
requiredVotes,
approvedVotes
);
}
function getInsuranceInfo
(
address passenger,
string flightCode
)
external
requireIsOperational
returns
(
address airline,
uint256 amount,
uint256 amountToPay,
bool isRegistered,
bool isRefunded
)
{
for(uint i=0; i < passengers[passenger].insuranceIds.length; i++) {
uint insuranceId = passengers[passenger].insuranceIds[i];
if (keccak256(bytes(insurances[insuranceId].flightCode)) == keccak256(bytes(flightCode))) {
airline = insurances[insuranceId].airline;
amount = insurances[insuranceId].amountPayed;
amountToPay = insurances[insuranceId].amountToPay;
isRegistered = insurances[insuranceId].isRegistered;
isRefunded = insurances[insuranceId].isRefunded;
break;
}
}
return
(
airline,
amount,
amountToPay,
isRegistered,
isRefunded
);
}
function isEligibleToWithdraw
(
address passenger,
uint amount
)
external
constant
requireIsOperational
returns(bool)
{
return (passengers[passenger].balance >= amount);
}
function getAirlineBalane
(
address airline
)
external
constant
requireIsOperational
returns(uint)
{
return airlineBalances[airline];
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline
(
address wallet,
bool isRegistered,
bool isAproved,
bool isFunded
)
external
requireIsOperational
{
_registerAirline(wallet, isRegistered, isAproved, isFunded);
// _registerAirline(wallet);
}
function registerFlight
(
string flightCode,
uint timestamp,
address airline
)
external
requireIsOperational
{
bytes32 flightKey = _getFlightKey(airline, flightCode, timestamp);
flights[flightKey] = Flight({
airline: airline,
isRegistered: true,
flightCode: flightCode,
timestamp: timestamp,
statusCode: 0
});
// Emit event
emit FlightRegistered(msg.sender, flightCode, timestamp);
}
function updateFlightStatus
(
bytes32 flightKey,
uint8 status
)
external
view
requireIsOperational
{
flights[flightKey].statusCode = status;
emit FlightStatusUpdated(flights[flightKey].airline, flights[flightKey].flightCode, flights[flightKey].timestamp, status);
}
function addVotingRound
(
address airline,
uint requiredVotes
)
external
requireIsOperational
{
votes[airline] = VoteSystem({
addresses: new address[](0),
numVotes: 0,
requiredVotes: requiredVotes
});
emit VotingRoundAdded(airline);
}
function updateFlightInsurance
(
uint insuranceId,
uint amountToPay
)
external
requireIsOperational
{
insurances[insuranceId].amountToPay = amountToPay;
emit FlightInsuranceUpdated(insuranceId, insurances[insuranceId].airline, insurances[insuranceId].flightCode, insurances[insuranceId].amountToPay);
}
function _registerAirline
(
address wallet,
bool isRegistered,
bool isAproved,
bool isFunded
)
internal
requireIsOperational
{
airlines[wallet] = Airline({
isRegistered: isRegistered,
isAproved: isAproved,
isFunded: isFunded
});
num_reg_airlines++;
// Emit event
emit AirlineRegistered(wallet);
if (isAproved) {
emit AirlineAproved(wallet);
}
}
function aproveAirline
(
address airlineWallet,
bool aproved,
address voter
)
external
requireIsOperational
{
//equire(airlines[msg.sender].isFunded, "Voting airline is not funded");
//require(!airlines[airlineWallet].isAproved, "Airline already approved");
bool alreadyVoted = false;
for (uint c=0; c<votes[airlineWallet].addresses.length; c++)
{
if (votes[airlineWallet].addresses[c] == voter) {
alreadyVoted = true;
break;
}
}
require(!alreadyVoted, "This airline has already voted");
votes[airlineWallet].addresses.push(voter);
if (aproved) {
votes[airlineWallet].numVotes++;
}
emit AirlineVoted(airlineWallet, voter);
if (votes[airlineWallet].numVotes >= votes[airlineWallet].requiredVotes) {
airlines[airlineWallet].isAproved = true;
// Delete register from the votes variable
//delete votes[airlineWallet];
// Emit events
emit AirlineAproved(airlineWallet);
}
}
/**
* @dev Buy insurance for a flight
*
*/
function buy
(
bytes32 flightKey,
address passenger,
uint amount
)
external
requireIsOperational
{
string flightCode = flights[flightKey].flightCode;
address airline = flights[flightKey].airline;
passengers[passenger] = Passanger({
isRegistered: true,
balance: 0,
insuranceIds: new uint256[](0)
});
insurances[insuranceId] = FlightInsurance({
airline: airline,
flightCode: flightCode,
flightKey: flightKey,
amountPayed: amount,
amountToPay: 0,
isRegistered: true,
isRefunded: false
});
passengers[passenger].insuranceIds.push(insuranceId);
insuranceId++;
emit InsurancePurchased(passenger, airline, flightCode, amount);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees
(
address passenger
)
external
requireIsOperational
{
for (uint i=0; i < passengers[passenger].insuranceIds.length; i++) {
uint insuranceId = passengers[passenger].insuranceIds[i];
uint amount = insurances[insuranceId].amountToPay;
require(airlineBalances[insurances[insuranceId].airline] >= amount, "Airline has not enought funds to pay");
insurances[insuranceId].isRefunded = true;
airlineBalances[insurances[insuranceId].airline] = airlineBalances[insurances[insuranceId].airline].sub(amount);
passengers[passenger].balance = passengers[passenger].balance.add(amount);
emit InsuranceCredited(passenger, insurances[insuranceId].flightCode, amount);
}
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay
(
address passenger,
uint amount
)
external
payable
requireIsOperational
{
passengers[passenger].balance = passengers[passenger].balance.sub(amount);
passenger.transfer(amount);
emit InsureeWithdrawn(passenger, amount);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fundAirline
(
address airline,
uint amount
)
external
requireIsOperational
{
airlines[airline].isFunded = true;
airlineBalances[airline] = airlineBalances[airline].add(amount);
// Emit event
emit AirlineFunded(airline, amount);
}
function fund
(
)
public
payable
{
}
function getFlightKey
(
address airline,
string flight,
uint256 timestamp
)
external
view
requireIsOperational
returns(bytes32)
{
return _getFlightKey(airline, flight, timestamp);
}
function _getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
internal
pure
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
{
fund();
}
}
| * @dev Add an airline to the registration queue Can only be called from FlightSuretyApp contract/ _registerAirline(wallet); | function registerAirline
(
address wallet,
bool isRegistered,
bool isAproved,
bool isFunded
)
external
requireIsOperational
{
_registerAirline(wallet, isRegistered, isAproved, isFunded);
}
| 14,074,050 | [
1,
986,
392,
23350,
1369,
358,
326,
7914,
2389,
1377,
4480,
1338,
506,
2566,
628,
3857,
750,
55,
594,
4098,
3371,
6835,
19,
389,
4861,
29752,
1369,
12,
19177,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1744,
29752,
1369,
203,
18701,
261,
203,
27573,
1758,
9230,
16,
203,
27573,
1426,
353,
10868,
16,
203,
27573,
1426,
25997,
685,
2155,
16,
203,
27573,
1426,
17646,
12254,
540,
203,
18701,
262,
203,
18701,
3903,
203,
18701,
2583,
2520,
2988,
287,
203,
565,
288,
203,
3639,
389,
4861,
29752,
1369,
12,
19177,
16,
353,
10868,
16,
25997,
685,
2155,
16,
17646,
12254,
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
]
|
pragma solidity ^0.6.6;
pragma experimental ABIEncoderV2;
import './Ownable.sol';
import './SafeMath.sol';
import './Address.sol';
import './ACONameFormatter.sol';
import './ACOAssetHelper.sol';
import './ERC20.sol';
import './IACOPool.sol';
import './IACOFactory.sol';
import './IACOStrategy.sol';
import './IACOToken.sol';
import './IACOFlashExercise.sol';
import './IUniswapV2Router02.sol';
import './IChiToken.sol';
/**
* @title ACOPool
* @dev A pool contract to trade ACO tokens.
*/
contract ACOPool is Ownable, ERC20, IACOPool {
using Address for address;
using SafeMath for uint256;
uint256 internal constant POOL_PRECISION = 1000000000000000000; // 18 decimals
uint256 internal constant MAX_UINT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
/**
* @dev Struct to store an ACO token trade data.
*/
struct ACOTokenData {
/**
* @dev Amount of tokens sold by the pool.
*/
uint256 amountSold;
/**
* @dev Amount of tokens purchased by the pool.
*/
uint256 amountPurchased;
/**
* @dev Index of the ACO token on the stored array.
*/
uint256 index;
}
/**
* @dev Emitted when the strategy address has been changed.
* @param oldStrategy Address of the previous strategy.
* @param newStrategy Address of the new strategy.
*/
event SetStrategy(address indexed oldStrategy, address indexed newStrategy);
/**
* @dev Emitted when the base volatility has been changed.
* @param oldBaseVolatility Value of the previous base volatility.
* @param newBaseVolatility Value of the new base volatility.
*/
event SetBaseVolatility(uint256 indexed oldBaseVolatility, uint256 indexed newBaseVolatility);
/**
* @dev Emitted when a collateral has been deposited on the pool.
* @param account Address of the account.
* @param amount Amount deposited.
*/
event CollateralDeposited(address indexed account, uint256 amount);
/**
* @dev Emitted when the collateral and premium have been redeemed on the pool.
* @param account Address of the account.
* @param underlyingAmount Amount of underlying asset redeemed.
* @param strikeAssetAmount Amount of strike asset redeemed.
*/
event Redeem(address indexed account, uint256 underlyingAmount, uint256 strikeAssetAmount);
/**
* @dev Emitted when the collateral has been restored on the pool.
* @param amountOut Amount of the premium sold.
* @param collateralIn Amount of collateral restored.
*/
event RestoreCollateral(uint256 amountOut, uint256 collateralIn);
/**
* @dev Emitted when an ACO token has been redeemed.
* @param acoToken Address of the ACO token.
* @param collateralIn Amount of collateral redeemed.
* @param amountSold Total amount of ACO token sold by the pool.
* @param amountPurchased Total amount of ACO token purchased by the pool.
*/
event ACORedeem(address indexed acoToken, uint256 collateralIn, uint256 amountSold, uint256 amountPurchased);
/**
* @dev Emitted when an ACO token has been exercised.
* @param acoToken Address of the ACO token.
* @param tokenAmount Amount of ACO tokens exercised.
* @param collateralIn Amount of collateral received.
*/
event ACOExercise(address indexed acoToken, uint256 tokenAmount, uint256 collateralIn);
/**
* @dev Emitted when an ACO token has been bought or sold by the pool.
* @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying.
* @param account Address of the account that is doing the swap.
* @param acoToken Address of the ACO token.
* @param tokenAmount Amount of ACO tokens swapped.
* @param price Value of the premium paid in strike asset.
* @param protocolFee Value of the protocol fee paid in strike asset.
* @param underlyingPrice The underlying price in strike asset.
*/
event Swap(
bool indexed isPoolSelling,
address indexed account,
address indexed acoToken,
uint256 tokenAmount,
uint256 price,
uint256 protocolFee,
uint256 underlyingPrice
);
/**
* @dev UNIX timestamp that the pool can start to trade ACO tokens.
*/
uint256 public poolStart;
/**
* @dev The protocol fee percentage. (100000 = 100%)
*/
uint256 public fee;
/**
* @dev Address of the ACO flash exercise contract.
*/
IACOFlashExercise public acoFlashExercise;
/**
* @dev Address of the ACO factory contract.
*/
IACOFactory public acoFactory;
/**
* @dev Address of the Uniswap V2 router.
*/
IUniswapV2Router02 public uniswapRouter;
/**
* @dev Address of the Chi gas token.
*/
IChiToken public chiToken;
/**
* @dev Address of the protocol fee destination.
*/
address public feeDestination;
/**
* @dev Address of the underlying asset accepts by the pool.
*/
address public underlying;
/**
* @dev Address of the strike asset accepts by the pool.
*/
address public strikeAsset;
/**
* @dev Value of the minimum strike price on ACO token that the pool accept to trade.
*/
uint256 public minStrikePrice;
/**
* @dev Value of the maximum strike price on ACO token that the pool accept to trade.
*/
uint256 public maxStrikePrice;
/**
* @dev Value of the minimum UNIX expiration on ACO token that the pool accept to trade.
*/
uint256 public minExpiration;
/**
* @dev Value of the maximum UNIX expiration on ACO token that the pool accept to trade.
*/
uint256 public maxExpiration;
/**
* @dev True whether the pool accepts CALL options, otherwise the pool accepts only PUT options.
*/
bool public isCall;
/**
* @dev True whether the pool can also buy ACO tokens, otherwise the pool only sells ACO tokens.
*/
bool public canBuy;
/**
* @dev Address of the strategy.
*/
IACOStrategy public strategy;
/**
* @dev Percentage value for the base volatility. (100000 = 100%)
*/
uint256 public baseVolatility;
/**
* @dev Total amount of collateral deposited.
*/
uint256 public collateralDeposited;
/**
* @dev Total amount in strike asset spent buying ACO tokens.
*/
uint256 public strikeAssetSpentBuying;
/**
* @dev Total amount in strike asset earned selling ACO tokens.
*/
uint256 public strikeAssetEarnedSelling;
/**
* @dev Array of ACO tokens currently negotiated.
*/
address[] public acoTokens;
/**
* @dev Mapping for ACO tokens data currently negotiated.
*/
mapping(address => ACOTokenData) public acoTokensData;
/**
* @dev Underlying asset precision. (18 decimals = 1000000000000000000)
*/
uint256 internal underlyingPrecision;
/**
* @dev Strike asset precision. (6 decimals = 1000000)
*/
uint256 internal strikeAssetPrecision;
/**
* @dev Modifier to check if the pool is open to trade.
*/
modifier open() {
require(isStarted() && notFinished(), "ACOPool:: Pool is not open");
_;
}
/**
* @dev Modifier to apply the Chi gas token and save gas.
*/
modifier discountCHI {
uint256 gasStart = gasleft();
_;
uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length;
chiToken.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41947);
}
/**
* @dev Function to initialize the contract.
* It should be called by the ACO pool factory when creating the pool.
* It must be called only once. The first `require` is to guarantee that behavior.
* @param initData The initialize data.
*/
function init(InitData calldata initData) external override {
require(underlying == address(0) && strikeAsset == address(0) && minExpiration == 0, "ACOPool::init: Already initialized");
require(initData.acoFactory.isContract(), "ACOPool:: Invalid ACO Factory");
require(initData.acoFlashExercise.isContract(), "ACOPool:: Invalid ACO flash exercise");
require(initData.chiToken.isContract(), "ACOPool:: Invalid Chi Token");
require(initData.fee <= 12500, "ACOPool:: The maximum fee allowed is 12.5%");
require(initData.poolStart > block.timestamp, "ACOPool:: Invalid pool start");
require(initData.minExpiration > block.timestamp, "ACOPool:: Invalid expiration");
require(initData.minStrikePrice <= initData.maxStrikePrice, "ACOPool:: Invalid strike price range");
require(initData.minStrikePrice > 0, "ACOPool:: Invalid strike price");
require(initData.minExpiration <= initData.maxExpiration, "ACOPool:: Invalid expiration range");
require(initData.underlying != initData.strikeAsset, "ACOPool:: Same assets");
require(ACOAssetHelper._isEther(initData.underlying) || initData.underlying.isContract(), "ACOPool:: Invalid underlying");
require(ACOAssetHelper._isEther(initData.strikeAsset) || initData.strikeAsset.isContract(), "ACOPool:: Invalid strike asset");
super.init();
poolStart = initData.poolStart;
acoFlashExercise = IACOFlashExercise(initData.acoFlashExercise);
acoFactory = IACOFactory(initData.acoFactory);
chiToken = IChiToken(initData.chiToken);
fee = initData.fee;
feeDestination = initData.feeDestination;
underlying = initData.underlying;
strikeAsset = initData.strikeAsset;
minStrikePrice = initData.minStrikePrice;
maxStrikePrice = initData.maxStrikePrice;
minExpiration = initData.minExpiration;
maxExpiration = initData.maxExpiration;
isCall = initData.isCall;
canBuy = initData.canBuy;
address _uniswapRouter = IACOFlashExercise(initData.acoFlashExercise).uniswapRouter();
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
_setStrategy(initData.strategy);
_setBaseVolatility(initData.baseVolatility);
_setAssetsPrecision(initData.underlying, initData.strikeAsset);
_approveAssetsOnRouter(initData.isCall, initData.canBuy, _uniswapRouter, initData.underlying, initData.strikeAsset);
}
receive() external payable {
}
/**
* @dev Function to get the token name.
*/
function name() public view override returns(string memory) {
return _name();
}
/**
* @dev Function to get the token symbol, that it is equal to the name.
*/
function symbol() public view override returns(string memory) {
return _name();
}
/**
* @dev Function to get the token decimals.
*/
function decimals() public view override returns(uint8) {
return 18;
}
/**
* @dev Function to get whether the pool already started trade ACO tokens.
*/
function isStarted() public view returns(bool) {
return block.timestamp >= poolStart;
}
/**
* @dev Function to get whether the pool is not finished.
*/
function notFinished() public view returns(bool) {
return block.timestamp < maxExpiration;
}
/**
* @dev Function to get the number of ACO tokens currently negotiated.
*/
function numberOfACOTokensCurrentlyNegotiated() public override view returns(uint256) {
return acoTokens.length;
}
/**
* @dev Function to get the pool collateral asset.
*/
function collateral() public override view returns(address) {
if (isCall) {
return underlying;
} else {
return strikeAsset;
}
}
/**
* @dev Function to quote an ACO token swap.
* @param isBuying True whether it is quoting to buy an ACO token, otherwise it is quoting to sell an ACO token.
* @param acoToken Address of the ACO token.
* @param tokenAmount Amount of ACO tokens to swap.
* @return The swap price, the protocol fee charged on the swap, and the underlying price in strike asset.
*/
function quote(bool isBuying, address acoToken, uint256 tokenAmount) open public override view returns(uint256, uint256, uint256) {
(uint256 swapPrice, uint256 protocolFee, uint256 underlyingPrice,) = _internalQuote(isBuying, acoToken, tokenAmount);
return (swapPrice, protocolFee, underlyingPrice);
}
/**
* @dev Function to set the pool strategy address.
* Only can be called by the ACO pool factory contract.
* @param newStrategy Address of the new strategy.
*/
function setStrategy(address newStrategy) onlyOwner external override {
_setStrategy(newStrategy);
}
/**
* @dev Function to set the pool base volatility percentage. (100000 = 100%)
* Only can be called by the ACO pool factory contract.
* @param newBaseVolatility Value of the new base volatility.
*/
function setBaseVolatility(uint256 newBaseVolatility) onlyOwner external override {
_setBaseVolatility(newBaseVolatility);
}
/**
* @dev Function to deposit on the pool.
* Only can be called when the pool is not started.
* @param collateralAmount Amount of collateral to be deposited.
* @param to Address of the destination of the pool token.
* @return The amount of pool tokens minted.
*/
function deposit(uint256 collateralAmount, address to) public override payable returns(uint256) {
require(!isStarted(), "ACOPool:: Pool already started");
require(collateralAmount > 0, "ACOPool:: Invalid collateral amount");
require(to != address(0) && to != address(this), "ACOPool:: Invalid to");
(uint256 normalizedAmount, uint256 amount) = _getNormalizedDepositAmount(collateralAmount);
ACOAssetHelper._receiveAsset(collateral(), amount);
collateralDeposited = collateralDeposited.add(amount);
_mintAction(to, normalizedAmount);
emit CollateralDeposited(msg.sender, amount);
return normalizedAmount;
}
/**
* @dev Function to swap an ACO token with the pool.
* Only can be called when the pool is opened.
* @param isBuying True whether it is quoting to buy an ACO token, otherwise it is quoting to sell an ACO token.
* @param acoToken Address of the ACO token.
* @param tokenAmount Amount of ACO tokens to swap.
* @param restriction Value of the swap restriction. The minimum premium to receive on a selling or the maximum value to pay on a purchase.
* @param to Address of the destination. ACO tokens when is buying or strike asset on a selling.
* @param deadline UNIX deadline for the swap to be executed.
* @return The amount ACO tokens received when is buying or the amount of strike asset received on a selling.
*/
function swap(
bool isBuying,
address acoToken,
uint256 tokenAmount,
uint256 restriction,
address to,
uint256 deadline
) open public override returns(uint256) {
return _swap(isBuying, acoToken, tokenAmount, restriction, to, deadline);
}
/**
* @dev Function to swap an ACO token with the pool and use Chi token to save gas.
* Only can be called when the pool is opened.
* @param isBuying True whether it is quoting to buy an ACO token, otherwise it is quoting to sell an ACO token.
* @param acoToken Address of the ACO token.
* @param tokenAmount Amount of ACO tokens to swap.
* @param restriction Value of the swap restriction. The minimum premium to receive on a selling or the maximum value to pay on a purchase.
* @param to Address of the destination. ACO tokens when is buying or strike asset on a selling.
* @param deadline UNIX deadline for the swap to be executed.
* @return The amount ACO tokens received when is buying or the amount of strike asset received on a selling.
*/
function swapWithGasToken(
bool isBuying,
address acoToken,
uint256 tokenAmount,
uint256 restriction,
address to,
uint256 deadline
) open discountCHI public override returns(uint256) {
return _swap(isBuying, acoToken, tokenAmount, restriction, to, deadline);
}
/**
* @dev Function to redeem the collateral and the premium from the pool.
* Only can be called when the pool is finished.
* @return The amount of underlying asset received and the amount of strike asset received.
*/
function redeem() public override returns(uint256, uint256) {
return _redeem(msg.sender);
}
/**
* @dev Function to redeem the collateral and the premium from the pool from an account.
* Only can be called when the pool is finished.
* The allowance must be respected.
* The transaction sender will receive the redeemed assets.
* @param account Address of the account.
* @return The amount of underlying asset received and the amount of strike asset received.
*/
function redeemFrom(address account) public override returns(uint256, uint256) {
return _redeem(account);
}
/**
* @dev Function to redeem the collateral from the ACO tokens negotiated on the pool.
* It redeems the collateral only if the respective ACO token is expired.
*/
function redeemACOTokens() public override {
for (uint256 i = acoTokens.length; i > 0; --i) {
address acoToken = acoTokens[i - 1];
uint256 expiryTime = IACOToken(acoToken).expiryTime();
_redeemACOToken(acoToken, expiryTime);
}
}
/**
* @dev Function to redeem the collateral from an ACO token.
* It redeems the collateral only if the ACO token is expired.
* @param acoToken Address of the ACO token.
*/
function redeemACOToken(address acoToken) public override {
(,uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken);
_redeemACOToken(acoToken, expiryTime);
}
/**
* @dev Function to exercise an ACO token negotiated on the pool.
* Only ITM ACO tokens are exercisable.
* @param acoToken Address of the ACO token.
*/
function exerciseACOToken(address acoToken) public override {
(uint256 strikePrice, uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken);
uint256 exercisableAmount = _getExercisableAmount(acoToken);
require(exercisableAmount > 0, "ACOPool:: Exercise is not available");
address _strikeAsset = strikeAsset;
address _underlying = underlying;
bool _isCall = isCall;
uint256 collateralAmount;
address _collateral;
if (_isCall) {
_collateral = _underlying;
collateralAmount = exercisableAmount;
} else {
_collateral = _strikeAsset;
collateralAmount = IACOToken(acoToken).getCollateralAmount(exercisableAmount);
}
uint256 collateralAvailable = _getPoolBalanceOf(_collateral);
ACOTokenData storage data = acoTokensData[acoToken];
(bool canExercise, uint256 minIntrinsicValue) = strategy.checkExercise(IACOStrategy.CheckExercise(
_underlying,
_strikeAsset,
_isCall,
strikePrice,
expiryTime,
collateralAmount,
collateralAvailable,
data.amountPurchased,
data.amountSold
));
require(canExercise, "ACOPool:: Exercise is not possible");
if (IACOToken(acoToken).allowance(address(this), address(acoFlashExercise)) < exercisableAmount) {
_setAuthorizedSpender(acoToken, address(acoFlashExercise));
}
acoFlashExercise.flashExercise(acoToken, exercisableAmount, minIntrinsicValue, block.timestamp);
uint256 collateralIn = _getPoolBalanceOf(_collateral).sub(collateralAvailable);
emit ACOExercise(acoToken, exercisableAmount, collateralIn);
}
/**
* @dev Function to restore the collateral on the pool by selling the other asset balance.
*/
function restoreCollateral() public override {
address _strikeAsset = strikeAsset;
address _underlying = underlying;
bool _isCall = isCall;
uint256 underlyingBalance = _getPoolBalanceOf(_underlying);
uint256 strikeAssetBalance = _getPoolBalanceOf(_strikeAsset);
uint256 balanceOut;
address assetIn;
address assetOut;
if (_isCall) {
balanceOut = strikeAssetBalance;
assetIn = _underlying;
assetOut = _strikeAsset;
} else {
balanceOut = underlyingBalance;
assetIn = _strikeAsset;
assetOut = _underlying;
}
require(balanceOut > 0, "ACOPool:: No balance");
uint256 acceptablePrice = strategy.getAcceptableUnderlyingPriceToSwapAssets(_underlying, _strikeAsset, false);
uint256 minToReceive;
if (_isCall) {
minToReceive = balanceOut.mul(underlyingPrecision).div(acceptablePrice);
} else {
minToReceive = balanceOut.mul(acceptablePrice).div(underlyingPrecision);
}
_swapAssetsExactAmountOut(assetOut, assetIn, minToReceive, balanceOut);
uint256 collateralIn;
if (_isCall) {
collateralIn = _getPoolBalanceOf(_underlying).sub(underlyingBalance);
} else {
collateralIn = _getPoolBalanceOf(_strikeAsset).sub(strikeAssetBalance);
}
emit RestoreCollateral(balanceOut, collateralIn);
}
/**
* @dev Internal function to swap an ACO token with the pool.
* @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying.
* @param acoToken Address of the ACO token.
* @param tokenAmount Amount of ACO tokens to swap.
* @param restriction Value of the swap restriction. The minimum premium to receive on a selling or the maximum value to pay on a purchase.
* @param to Address of the destination. ACO tokens when is buying or strike asset on a selling.
* @param deadline UNIX deadline for the swap to be executed.
* @return The amount ACO tokens received when is buying or the amount of strike asset received on a selling.
*/
function _swap(
bool isPoolSelling,
address acoToken,
uint256 tokenAmount,
uint256 restriction,
address to,
uint256 deadline
) internal returns(uint256) {
require(block.timestamp <= deadline, "ACOPool:: Swap deadline");
require(to != address(0) && to != acoToken && to != address(this), "ACOPool:: Invalid destination");
(uint256 swapPrice, uint256 protocolFee, uint256 underlyingPrice, uint256 collateralAmount) = _internalQuote(isPoolSelling, acoToken, tokenAmount);
uint256 amount;
if (isPoolSelling) {
amount = _internalSelling(to, acoToken, collateralAmount, tokenAmount, restriction, swapPrice, protocolFee);
} else {
amount = _internalBuying(to, acoToken, tokenAmount, restriction, swapPrice, protocolFee);
}
if (protocolFee > 0) {
ACOAssetHelper._transferAsset(strikeAsset, feeDestination, protocolFee);
}
emit Swap(isPoolSelling, msg.sender, acoToken, tokenAmount, swapPrice, protocolFee, underlyingPrice);
return amount;
}
/**
* @dev Internal function to quote an ACO token price.
* @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying.
* @param acoToken Address of the ACO token.
* @param tokenAmount Amount of ACO tokens to swap.
* @return The quote price, the protocol fee charged, the underlying price, and the collateral amount.
*/
function _internalQuote(bool isPoolSelling, address acoToken, uint256 tokenAmount) internal view returns(uint256, uint256, uint256, uint256) {
require(isPoolSelling || canBuy, "ACOPool:: The pool only sell");
require(tokenAmount > 0, "ACOPool:: Invalid token amount");
(uint256 strikePrice, uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken);
require(expiryTime > block.timestamp, "ACOPool:: ACO token expired");
(uint256 collateralAmount, uint256 collateralAvailable) = _getSizeData(isPoolSelling, acoToken, tokenAmount);
(uint256 price, uint256 underlyingPrice,) = _strategyQuote(acoToken, isPoolSelling, strikePrice, expiryTime, collateralAmount, collateralAvailable);
price = price.mul(tokenAmount).div(underlyingPrecision);
uint256 protocolFee = 0;
if (fee > 0) {
protocolFee = price.mul(fee).div(100000);
if (isPoolSelling) {
price = price.add(protocolFee);
} else {
price = price.sub(protocolFee);
}
}
require(price > 0, "ACOPool:: Invalid quote");
return (price, protocolFee, underlyingPrice, collateralAmount);
}
/**
* @dev Internal function to the size data for a quote.
* @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying.
* @param acoToken Address of the ACO token.
* @param tokenAmount Amount of ACO tokens to swap.
* @return The collateral amount and the collateral available on the pool.
*/
function _getSizeData(bool isPoolSelling, address acoToken, uint256 tokenAmount) internal view returns(uint256, uint256) {
uint256 collateralAmount;
uint256 collateralAvailable;
if (isCall) {
collateralAvailable = _getPoolBalanceOf(underlying);
collateralAmount = tokenAmount;
} else {
collateralAvailable = _getPoolBalanceOf(strikeAsset);
collateralAmount = IACOToken(acoToken).getCollateralAmount(tokenAmount);
require(collateralAmount > 0, "ACOPool:: Token amount is too small");
}
require(!isPoolSelling || collateralAmount <= collateralAvailable, "ACOPool:: Insufficient liquidity");
return (collateralAmount, collateralAvailable);
}
/**
* @dev Internal function to quote on the strategy contract.
* @param acoToken Address of the ACO token.
* @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying.
* @param strikePrice ACO token strike price.
* @param expiryTime ACO token expiry time on UNIX.
* @param collateralAmount Amount of collateral for the order size.
* @param collateralAvailable Amount of collateral available on the pool.
* @return The quote price, the underlying price and the volatility.
*/
function _strategyQuote(
address acoToken,
bool isPoolSelling,
uint256 strikePrice,
uint256 expiryTime,
uint256 collateralAmount,
uint256 collateralAvailable
) internal view returns(uint256, uint256, uint256) {
ACOTokenData storage data = acoTokensData[acoToken];
return strategy.quote(IACOStrategy.OptionQuote(
isPoolSelling,
underlying,
strikeAsset,
isCall,
strikePrice,
expiryTime,
baseVolatility,
collateralAmount,
collateralAvailable,
collateralDeposited,
strikeAssetEarnedSelling,
strikeAssetSpentBuying,
data.amountPurchased,
data.amountSold
));
}
/**
* @dev Internal function to sell ACO tokens.
* @param to Address of the destination of the ACO tokens.
* @param acoToken Address of the ACO token.
* @param collateralAmount Order collateral amount.
* @param tokenAmount Order token amount.
* @param maxPayment Maximum value to be paid for the ACO tokens.
* @param swapPrice The swap price quoted.
* @param protocolFee The protocol fee amount.
* @return The ACO token amount sold.
*/
function _internalSelling(
address to,
address acoToken,
uint256 collateralAmount,
uint256 tokenAmount,
uint256 maxPayment,
uint256 swapPrice,
uint256 protocolFee
) internal returns(uint256) {
require(swapPrice <= maxPayment, "ACOPool:: Swap restriction");
ACOAssetHelper._callTransferFromERC20(strikeAsset, msg.sender, address(this), swapPrice);
uint256 acoBalance = _getPoolBalanceOf(acoToken);
ACOTokenData storage acoTokenData = acoTokensData[acoToken];
uint256 _amountSold = acoTokenData.amountSold;
if (_amountSold == 0 && acoTokenData.amountPurchased == 0) {
acoTokenData.index = acoTokens.length;
acoTokens.push(acoToken);
}
if (tokenAmount > acoBalance) {
tokenAmount = acoBalance;
if (acoBalance > 0) {
collateralAmount = IACOToken(acoToken).getCollateralAmount(tokenAmount.sub(acoBalance));
}
if (collateralAmount > 0) {
address _collateral = collateral();
if (ACOAssetHelper._isEther(_collateral)) {
tokenAmount = tokenAmount.add(IACOToken(acoToken).mintPayable{value: collateralAmount}());
} else {
if (_amountSold == 0) {
_setAuthorizedSpender(_collateral, acoToken);
}
tokenAmount = tokenAmount.add(IACOToken(acoToken).mint(collateralAmount));
}
}
}
acoTokenData.amountSold = tokenAmount.add(_amountSold);
strikeAssetEarnedSelling = swapPrice.sub(protocolFee).add(strikeAssetEarnedSelling);
ACOAssetHelper._callTransferERC20(acoToken, to, tokenAmount);
return tokenAmount;
}
/**
* @dev Internal function to buy ACO tokens.
* @param to Address of the destination of the premium.
* @param acoToken Address of the ACO token.
* @param tokenAmount Order token amount.
* @param minToReceive Minimum value to be received for the ACO tokens.
* @param swapPrice The swap price quoted.
* @param protocolFee The protocol fee amount.
* @return The premium amount transferred.
*/
function _internalBuying(
address to,
address acoToken,
uint256 tokenAmount,
uint256 minToReceive,
uint256 swapPrice,
uint256 protocolFee
) internal returns(uint256) {
require(swapPrice >= minToReceive, "ACOPool:: Swap restriction");
uint256 requiredStrikeAsset = swapPrice.add(protocolFee);
if (isCall) {
_getStrikeAssetAmount(requiredStrikeAsset);
}
ACOAssetHelper._callTransferFromERC20(acoToken, msg.sender, address(this), tokenAmount);
ACOTokenData storage acoTokenData = acoTokensData[acoToken];
uint256 _amountPurchased = acoTokenData.amountPurchased;
if (_amountPurchased == 0 && acoTokenData.amountSold == 0) {
acoTokenData.index = acoTokens.length;
acoTokens.push(acoToken);
}
acoTokenData.amountPurchased = tokenAmount.add(_amountPurchased);
strikeAssetSpentBuying = requiredStrikeAsset.add(strikeAssetSpentBuying);
ACOAssetHelper._transferAsset(strikeAsset, to, swapPrice);
return swapPrice;
}
/**
* @dev Internal function to get the normalized deposit amount.
* The pool token has always with 18 decimals.
* @param collateralAmount Amount of collateral to be deposited.
* @return The normalized token amount and the collateral amount.
*/
function _getNormalizedDepositAmount(uint256 collateralAmount) internal view returns(uint256, uint256) {
uint256 basePrecision = isCall ? underlyingPrecision : strikeAssetPrecision;
uint256 normalizedAmount;
if (basePrecision > POOL_PRECISION) {
uint256 adjust = basePrecision.div(POOL_PRECISION);
normalizedAmount = collateralAmount.div(adjust);
collateralAmount = normalizedAmount.mul(adjust);
} else if (basePrecision < POOL_PRECISION) {
normalizedAmount = collateralAmount.mul(POOL_PRECISION.div(basePrecision));
} else {
normalizedAmount = collateralAmount;
}
require(normalizedAmount > 0, "ACOPool:: Invalid collateral amount");
return (normalizedAmount, collateralAmount);
}
/**
* @dev Internal function to get an amount of strike asset for the pool.
* The pool swaps the collateral for it if necessary.
* @param strikeAssetAmount Amount of strike asset required.
*/
function _getStrikeAssetAmount(uint256 strikeAssetAmount) internal {
address _strikeAsset = strikeAsset;
uint256 balance = _getPoolBalanceOf(_strikeAsset);
if (balance < strikeAssetAmount) {
uint256 amountToPurchase = strikeAssetAmount.sub(balance);
address _underlying = underlying;
uint256 acceptablePrice = strategy.getAcceptableUnderlyingPriceToSwapAssets(_underlying, _strikeAsset, true);
uint256 maxPayment = amountToPurchase.mul(underlyingPrecision).div(acceptablePrice);
_swapAssetsExactAmountIn(_underlying, _strikeAsset, amountToPurchase, maxPayment);
}
}
/**
* @dev Internal function to redeem the collateral from an ACO token.
* It redeems the collateral only if the ACO token is expired.
* @param acoToken Address of the ACO token.
* @param expiryTime ACO token expiry time in UNIX.
*/
function _redeemACOToken(address acoToken, uint256 expiryTime) internal {
if (expiryTime <= block.timestamp) {
uint256 collateralIn = 0;
if (IACOToken(acoToken).currentCollateralizedTokens(address(this)) > 0) {
collateralIn = IACOToken(acoToken).redeem();
}
ACOTokenData storage data = acoTokensData[acoToken];
uint256 lastIndex = acoTokens.length - 1;
if (lastIndex != data.index) {
address last = acoTokens[lastIndex];
acoTokensData[last].index = data.index;
acoTokens[data.index] = last;
}
emit ACORedeem(acoToken, collateralIn, data.amountSold, data.amountPurchased);
acoTokens.pop();
delete acoTokensData[acoToken];
}
}
/**
* @dev Internal function to redeem the collateral and the premium from the pool from an account.
* @param account Address of the account.
* @return The amount of underlying asset received and the amount of strike asset received.
*/
function _redeem(address account) internal returns(uint256, uint256) {
uint256 share = balanceOf(account);
require(share > 0, "ACOPool:: Account with no share");
require(!notFinished(), "ACOPool:: Pool is not finished");
redeemACOTokens();
uint256 _totalSupply = totalSupply();
uint256 underlyingBalance = share.mul(_getPoolBalanceOf(underlying)).div(_totalSupply);
uint256 strikeAssetBalance = share.mul(_getPoolBalanceOf(strikeAsset)).div(_totalSupply);
_callBurn(account, share);
if (underlyingBalance > 0) {
ACOAssetHelper._transferAsset(underlying, msg.sender, underlyingBalance);
}
if (strikeAssetBalance > 0) {
ACOAssetHelper._transferAsset(strikeAsset, msg.sender, strikeAssetBalance);
}
emit Redeem(msg.sender, underlyingBalance, strikeAssetBalance);
return (underlyingBalance, strikeAssetBalance);
}
/**
* @dev Internal function to burn pool tokens.
* @param account Address of the account.
* @param tokenAmount Amount of pool tokens to be burned.
*/
function _callBurn(address account, uint256 tokenAmount) internal {
if (account == msg.sender) {
super._burnAction(account, tokenAmount);
} else {
super._burnFrom(account, tokenAmount);
}
}
/**
* @dev Internal function to swap assets on the Uniswap V2 with an exact amount of an asset to be sold.
* @param assetOut Address of the asset to be sold.
* @param assetIn Address of the asset to be purchased.
* @param minAmountIn Minimum amount to be received.
* @param amountOut The exact amount to be sold.
*/
function _swapAssetsExactAmountOut(address assetOut, address assetIn, uint256 minAmountIn, uint256 amountOut) internal {
address[] memory path = new address[](2);
if (ACOAssetHelper._isEther(assetOut)) {
path[0] = acoFlashExercise.weth();
path[1] = assetIn;
uniswapRouter.swapExactETHForTokens{value: amountOut}(minAmountIn, path, address(this), block.timestamp);
} else if (ACOAssetHelper._isEther(assetIn)) {
path[0] = assetOut;
path[1] = acoFlashExercise.weth();
uniswapRouter.swapExactTokensForETH(amountOut, minAmountIn, path, address(this), block.timestamp);
} else {
path[0] = assetOut;
path[1] = assetIn;
uniswapRouter.swapExactTokensForTokens(amountOut, minAmountIn, path, address(this), block.timestamp);
}
}
/**
* @dev Internal function to swap assets on the Uniswap V2 with an exact amount of an asset to be purchased.
* @param assetOut Address of the asset to be sold.
* @param assetIn Address of the asset to be purchased.
* @param amountIn The exact amount to be purchased.
* @param maxAmountOut Maximum amount to be paid.
*/
function _swapAssetsExactAmountIn(address assetOut, address assetIn, uint256 amountIn, uint256 maxAmountOut) internal {
address[] memory path = new address[](2);
if (ACOAssetHelper._isEther(assetOut)) {
path[0] = acoFlashExercise.weth();
path[1] = assetIn;
uniswapRouter.swapETHForExactTokens{value: maxAmountOut}(amountIn, path, address(this), block.timestamp);
} else if (ACOAssetHelper._isEther(assetIn)) {
path[0] = assetOut;
path[1] = acoFlashExercise.weth();
uniswapRouter.swapTokensForExactETH(amountIn, maxAmountOut, path, address(this), block.timestamp);
} else {
path[0] = assetOut;
path[1] = assetIn;
uniswapRouter.swapTokensForExactTokens(amountIn, maxAmountOut, path, address(this), block.timestamp);
}
}
/**
* @dev Internal function to set the strategy address.
* @param newStrategy Address of the new strategy.
*/
function _setStrategy(address newStrategy) internal {
require(newStrategy.isContract(), "ACOPool:: Invalid strategy");
emit SetStrategy(address(strategy), newStrategy);
strategy = IACOStrategy(newStrategy);
}
/**
* @dev Internal function to set the base volatility percentage. (100000 = 100%)
* @param newBaseVolatility Value of the new base volatility.
*/
function _setBaseVolatility(uint256 newBaseVolatility) internal {
require(newBaseVolatility > 0, "ACOPool:: Invalid base volatility");
emit SetBaseVolatility(baseVolatility, newBaseVolatility);
baseVolatility = newBaseVolatility;
}
/**
* @dev Internal function to set the pool assets precisions.
* @param _underlying Address of the underlying asset.
* @param _strikeAsset Address of the strike asset.
*/
function _setAssetsPrecision(address _underlying, address _strikeAsset) internal {
underlyingPrecision = 10 ** uint256(ACOAssetHelper._getAssetDecimals(_underlying));
strikeAssetPrecision = 10 ** uint256(ACOAssetHelper._getAssetDecimals(_strikeAsset));
}
/**
* @dev Internal function to infinite authorize the pool assets on the Uniswap V2 router.
* @param _isCall True whether it is a CALL option, otherwise it is PUT.
* @param _canBuy True whether the pool can also buy ACO tokens, otherwise it only sells.
* @param _uniswapRouter Address of the Uniswap V2 router.
* @param _underlying Address of the underlying asset.
* @param _strikeAsset Address of the strike asset.
*/
function _approveAssetsOnRouter(
bool _isCall,
bool _canBuy,
address _uniswapRouter,
address _underlying,
address _strikeAsset
) internal {
if (_isCall) {
if (!ACOAssetHelper._isEther(_strikeAsset)) {
_setAuthorizedSpender(_strikeAsset, _uniswapRouter);
}
if (_canBuy && !ACOAssetHelper._isEther(_underlying)) {
_setAuthorizedSpender(_underlying, _uniswapRouter);
}
} else if (!ACOAssetHelper._isEther(_underlying)) {
_setAuthorizedSpender(_underlying, _uniswapRouter);
}
}
/**
* @dev Internal function to infinite authorize a spender on an asset.
* @param asset Address of the asset.
* @param spender Address of the spender to be authorized.
*/
function _setAuthorizedSpender(address asset, address spender) internal {
ACOAssetHelper._callApproveERC20(asset, spender, MAX_UINT);
}
/**
* @dev Internal function to get the pool balance of an asset.
* @param asset Address of the asset.
* @return The pool balance.
*/
function _getPoolBalanceOf(address asset) internal view returns(uint256) {
return ACOAssetHelper._getAssetBalanceOf(asset, address(this));
}
/**
* @dev Internal function to get the exercible amount of an ACO token.
* @param acoToken Address of the ACO token.
* @return The exercisable amount.
*/
function _getExercisableAmount(address acoToken) internal view returns(uint256) {
uint256 balance = _getPoolBalanceOf(acoToken);
if (balance > 0) {
uint256 collaterized = IACOToken(acoToken).currentCollateralizedTokens(address(this));
if (balance > collaterized) {
return balance.sub(collaterized);
}
}
return 0;
}
/**
* @dev Internal function to get an accepted ACO token by the pool.
* @param acoToken Address of the ACO token.
* @return The ACO token strike price, and the ACO token expiration.
*/
function _getValidACOTokenStrikePriceAndExpiration(address acoToken) internal view returns(uint256, uint256) {
(address _underlying, address _strikeAsset, bool _isCall, uint256 _strikePrice, uint256 _expiryTime) = acoFactory.acoTokenData(acoToken);
require(
_underlying == underlying &&
_strikeAsset == strikeAsset &&
_isCall == isCall &&
_strikePrice >= minStrikePrice &&
_strikePrice <= maxStrikePrice &&
_expiryTime >= minExpiration &&
_expiryTime <= maxExpiration,
"ACOPool:: Invalid ACO Token"
);
return (_strikePrice, _expiryTime);
}
/**
* @dev Internal function to get the token name.
* The token name is assembled with the token data:
* ACO POOL UNDERLYING_SYMBOL-STRIKE_ASSET_SYMBOL-TYPE-{ONLY_SELL}-MIN_STRIKE_PRICE-MAX_STRIKE_PRICE-MIN_EXPIRATION-MAX_EXPIRATION
* @return The token name.
*/
function _name() internal view returns(string memory) {
uint8 strikeDecimals = ACOAssetHelper._getAssetDecimals(strikeAsset);
string memory strikePriceFormatted;
if (minStrikePrice != maxStrikePrice) {
strikePriceFormatted = string(abi.encodePacked(ACONameFormatter.formatNumber(minStrikePrice, strikeDecimals), "-", ACONameFormatter.formatNumber(maxStrikePrice, strikeDecimals)));
} else {
strikePriceFormatted = ACONameFormatter.formatNumber(minStrikePrice, strikeDecimals);
}
string memory dateFormatted;
if (minExpiration != maxExpiration) {
dateFormatted = string(abi.encodePacked(ACONameFormatter.formatTime(minExpiration), "-", ACONameFormatter.formatTime(maxExpiration)));
} else {
dateFormatted = ACONameFormatter.formatTime(minExpiration);
}
return string(abi.encodePacked(
"ACO POOL ",
ACOAssetHelper._getAssetSymbol(underlying),
"-",
ACOAssetHelper._getAssetSymbol(strikeAsset),
"-",
ACONameFormatter.formatType(isCall),
(canBuy ? "" : "-SELL"),
"-",
strikePriceFormatted,
"-",
dateFormatted
));
}
} | * @dev Function to get the pool collateral asset./ | function collateral() public override view returns(address) {
if (isCall) {
return underlying;
return strikeAsset;
}
}
| 48,851 | [
1,
2083,
358,
336,
326,
2845,
4508,
2045,
287,
3310,
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,
4508,
2045,
287,
1435,
1071,
3849,
1476,
1135,
12,
2867,
13,
288,
203,
3639,
309,
261,
291,
1477,
13,
288,
203,
5411,
327,
6808,
31,
203,
5411,
327,
609,
2547,
6672,
31,
203,
3639,
289,
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
]
|
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.4;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IStandardERC20} from '../../../base/interfaces/IStandardERC20.sol';
import {
MintableBurnableIERC20
} from '../../../tokens/interfaces/MintableBurnableIERC20.sol';
import {
IdentifierWhitelistInterface
} from '@uma/core/contracts/oracle/interfaces/IdentifierWhitelistInterface.sol';
import {
AddressWhitelistInterface
} from '@uma/core/contracts/common/interfaces/AddressWhitelistInterface.sol';
import {
AdministrateeInterface
} from '@uma/core/contracts/oracle/interfaces/AdministrateeInterface.sol';
import {ISynthereumFinder} from '../../../core/interfaces/IFinder.sol';
import {
ISelfMintingDerivativeDeployment
} from '../common/interfaces/ISelfMintingDerivativeDeployment.sol';
import {
OracleInterface
} from '@uma/core/contracts/oracle/interfaces/OracleInterface.sol';
import {
OracleInterfaces
} from '@uma/core/contracts/oracle/implementation/Constants.sol';
import {SynthereumInterfaces} from '../../../core/Constants.sol';
import {
FixedPoint
} from '@uma/core/contracts/common/implementation/FixedPoint.sol';
import {
SafeERC20
} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import {
SelfMintingPerpetualPositionManagerMultiPartyLib
} from './SelfMintingPerpetualPositionManagerMultiPartyLib.sol';
import {FeePayerPartyLib} from '../../common/FeePayerPartyLib.sol';
import {FeePayerParty} from '../../common/FeePayerParty.sol';
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract SelfMintingPerpetualPositionManagerMultiParty is
ISelfMintingDerivativeDeployment,
FeePayerParty
{
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for MintableBurnableIERC20;
using SelfMintingPerpetualPositionManagerMultiPartyLib for PositionData;
using SelfMintingPerpetualPositionManagerMultiPartyLib for PositionManagerData;
using FeePayerPartyLib for FixedPoint.Unsigned;
/**
* @notice Construct the PerpetualPositionManager.
* @dev Deployer of this contract should consider carefully which parties have ability to mint and burn
* the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts
* can mint new tokens, which could be used to steal all of this contract's locked collateral.
* We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles)
* is assigned to this contract, whose sole Minter role is assigned to this contract, and whose
* total supply is 0 prior to construction of this contract.
* @param withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param collateralAddress ERC20 token used as collateral for all positions.
* @param tokenAddress ERC20 token used as synthetic token.
* @param finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param priceFeedIdentifier registered in the DVM for the synthetic.
* @param minSponsorTokens minimum amount of collateral that must exist at any time in a position.
* @param timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production.
* @param excessTokenBeneficiary Beneficiary to send all excess token balances that accrue in the contract.
* @param version Version of the self-minting derivative
* @param synthereumFinder The SynthereumFinder contract
*/
struct PositionManagerParams {
uint256 withdrawalLiveness;
address collateralAddress;
address tokenAddress;
address finderAddress;
bytes32 priceFeedIdentifier;
FixedPoint.Unsigned minSponsorTokens;
address timerAddress;
address excessTokenBeneficiary;
uint8 version;
ISynthereumFinder synthereumFinder;
}
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
struct GlobalPositionData {
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
//_getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned rawTotalPositionCollateral;
}
struct PositionManagerData {
// SynthereumFinder contract
ISynthereumFinder synthereumFinder;
// Synthetic token created by this contract.
MintableBurnableIERC20 tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 priceIdentifier;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned minSponsorTokens;
// Expiry price pulled from the DVM in the case of an emergency shutdown.
FixedPoint.Unsigned emergencyShutdownPrice;
// Timestamp used in case of emergency shutdown.
uint256 emergencyShutdownTimestamp;
// The excessTokenBeneficiary of any excess tokens added to the contract.
address excessTokenBeneficiary;
// Version of the self-minting derivative
uint8 version;
}
//----------------------------------------
// Storage
//----------------------------------------
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
GlobalPositionData public globalPositionData;
PositionManagerData public positionManagerData;
//----------------------------------------
// Events
//----------------------------------------
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(
address indexed sponsor,
uint256 indexed collateralAmount
);
event RequestWithdrawalExecuted(
address indexed sponsor,
uint256 indexed collateralAmount
);
event RequestWithdrawalCanceled(
address indexed sponsor,
uint256 indexed collateralAmount
);
event PositionCreated(
address indexed sponsor,
uint256 indexed collateralAmount,
uint256 indexed tokenAmount,
uint256 feeAmount
);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Redeem(
address indexed sponsor,
uint256 indexed collateralAmount,
uint256 indexed tokenAmount,
uint256 feeAmount
);
event Repay(
address indexed sponsor,
uint256 indexed numTokensRepaid,
uint256 indexed newTokenCount,
uint256 feeAmount
);
event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp);
event SettleEmergencyShutdown(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
//----------------------------------------
// Modifiers
//----------------------------------------
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
modifier notEmergencyShutdown() {
_notEmergencyShutdown();
_;
}
modifier isEmergencyShutdown() {
_isEmergencyShutdown();
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
//----------------------------------------
// Constructor
//----------------------------------------
/**
* @notice Construct the SelfMintingPerpetualPositionManagerMultiParty.
* @param _positionManagerData Input parameters of PositionManager (see PositionManagerData struct)
*/
constructor(PositionManagerParams memory _positionManagerData)
FeePayerParty(
_positionManagerData.collateralAddress,
_positionManagerData.finderAddress,
_positionManagerData.timerAddress
)
nonReentrant()
{
require(
_getIdentifierWhitelist().isIdentifierSupported(
_positionManagerData.priceFeedIdentifier
),
'Unsupported price identifier'
);
require(
_getCollateralWhitelist().isOnWhitelist(
_positionManagerData.collateralAddress
),
'Collateral not whitelisted'
);
positionManagerData.synthereumFinder = _positionManagerData
.synthereumFinder;
positionManagerData.withdrawalLiveness = _positionManagerData
.withdrawalLiveness;
positionManagerData.tokenCurrency = MintableBurnableIERC20(
_positionManagerData.tokenAddress
);
positionManagerData.minSponsorTokens = _positionManagerData
.minSponsorTokens;
positionManagerData.priceIdentifier = _positionManagerData
.priceFeedIdentifier;
positionManagerData.excessTokenBeneficiary = _positionManagerData
.excessTokenBeneficiary;
positionManagerData.version = _positionManagerData.version;
}
//----------------------------------------
// External functions
//----------------------------------------
/**
* @notice Transfers `collateralAmount` of `feePayerData.collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `feePayerData.collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(uint256 collateralAmount) external {
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `feePayerData.collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(uint256 collateralAmount)
external
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (uint256 amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
amountWithdrawn = positionData
.withdraw(
globalPositionData,
FixedPoint.Unsigned(collateralAmount),
feePayerData
)
.rawValue;
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(uint256 collateralAmount)
external
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
uint256 actualTime = getCurrentTime();
PositionData storage positionData = _getPositionData(msg.sender);
positionData.requestWithdrawal(
positionManagerData,
FixedPoint.Unsigned(collateralAmount),
actualTime,
feePayerData
);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (uint256 amountWithdrawn)
{
uint256 actualTime = getCurrentTime();
PositionData storage positionData = _getPositionData(msg.sender);
amountWithdrawn = positionData
.withdrawPassedRequest(globalPositionData, actualTime, feePayerData)
.rawValue;
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
positionData.cancelWithdrawal();
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount
* ` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev Can only be called by a token sponsor. Might not mint the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
* @param feePercentage The percentage of fee that is paid in collateralCurrency
*/
function create(
uint256 collateralAmount,
uint256 numTokens,
uint256 feePercentage
)
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (uint256 daoFeeAmount)
{
PositionData storage positionData = positions[msg.sender];
daoFeeAmount = positionData
.create(
globalPositionData,
positionManagerData,
FixedPoint.Unsigned(collateralAmount),
FixedPoint.Unsigned(numTokens),
FixedPoint.Unsigned(feePercentage),
feePayerData
)
.rawValue;
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `feePayerData.collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(uint256 numTokens, uint256 feePercentage)
external
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (uint256 amountWithdrawn, uint256 daoFeeAmount)
{
PositionData storage positionData = _getPositionData(msg.sender);
(
FixedPoint.Unsigned memory collateralAmount,
FixedPoint.Unsigned memory feeAmount
) =
positionData.redeeem(
globalPositionData,
positionManagerData,
FixedPoint.Unsigned(numTokens),
FixedPoint.Unsigned(feePercentage),
feePayerData,
msg.sender
);
amountWithdrawn = collateralAmount.rawValue;
daoFeeAmount = feeAmount.rawValue;
}
/**
* @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `feePayerData.collateralCurrency`.
* This is done by a sponsor to increase position CR.
* @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @param feePercentage the fee percentage paid by the token sponsor in collateralCurrency
*/
function repay(uint256 numTokens, uint256 feePercentage)
external
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (uint256 daoFeeAmount)
{
PositionData storage positionData = _getPositionData(msg.sender);
daoFeeAmount = (
positionData.repay(
globalPositionData,
positionManagerData,
FixedPoint.Unsigned(numTokens),
FixedPoint.Unsigned(feePercentage),
feePayerData
)
)
.rawValue;
}
/**
* @notice If the contract is emergency shutdown then all token holders and sponsor can redeem their tokens or
* remaining collateral for underlying at the prevailing price defined by a DVM vote.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of
* `feePayerData.collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleEmergencyShutdown()
external
isEmergencyShutdown()
fees()
nonReentrant()
returns (uint256 amountWithdrawn)
{
PositionData storage positionData = positions[msg.sender];
amountWithdrawn = positionData
.settleEmergencyShutdown(
globalPositionData,
positionManagerData,
feePayerData
)
.rawValue;
}
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the `settleEmergencyShutdown` function.
*/
function emergencyShutdown()
external
override
notEmergencyShutdown()
nonReentrant()
{
require(
msg.sender ==
positionManagerData.synthereumFinder.getImplementationAddress(
SynthereumInterfaces.Manager
) ||
msg.sender == _getFinancialContractsAdminAddress(),
'Caller must be a Synthereum manager or the UMA governor'
);
positionManagerData.emergencyShutdownTimestamp = getCurrentTime();
positionManagerData.requestOraclePrice(
positionManagerData.emergencyShutdownTimestamp,
feePayerData
);
emit EmergencyShutdown(
msg.sender,
positionManagerData.emergencyShutdownTimestamp
);
}
/** @notice Remargin function
*/
function remargin() external override {
return;
}
/**
* @notice Drains any excess balance of the provided ERC20 token to a pre-selected beneficiary.
* @dev This will drain down to the amount of tracked collateral and drain the full balance of any other token.
* @param token address of the ERC20 token whose excess balance should be drained.
*/
function trimExcess(IERC20 token)
external
nonReentrant()
returns (uint256 amount)
{
FixedPoint.Unsigned memory pfcAmount = _pfc();
amount = positionManagerData
.trimExcess(token, pfcAmount, feePayerData)
.rawValue;
}
/**
* @notice Delete a TokenSponsor position (This function can only be called by the contract itself)
* @param sponsor address of the TokenSponsor.
*/
function deleteSponsorPosition(address sponsor) external onlyThisContract {
delete positions[sponsor];
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory collateralAmount)
{
return
positions[sponsor].rawCollateral.getFeeAdjustedCollateral(
feePayerData.cumulativeFeeMultiplier
);
}
/**
* @notice Get SynthereumFinder contract address
* @return finder SynthereumFinder contract
*/
function synthereumFinder()
external
view
override
returns (ISynthereumFinder finder)
{
finder = positionManagerData.synthereumFinder;
}
/**
* @notice Get synthetic token currency
* @return synthToken Synthetic token
*/
function tokenCurrency() external view override returns (IERC20 synthToken) {
synthToken = positionManagerData.tokenCurrency;
}
/**
* @notice Get synthetic token symbol
* @return symbol Synthetic token symbol
*/
function syntheticTokenSymbol()
external
view
override
returns (string memory symbol)
{
symbol = IStandardERC20(address(positionManagerData.tokenCurrency))
.symbol();
}
/** @notice Get the version of a self minting derivative
* @return contractVersion Contract version
*/
function version() external view override returns (uint8 contractVersion) {
contractVersion = positionManagerData.version;
}
/**
* @notice Get synthetic token price identifier registered with UMA DVM
* @return identifier Synthetic token price identifier
*/
function priceIdentifier() external view returns (bytes32 identifier) {
identifier = positionManagerData.priceIdentifier;
}
/**
* @notice Accessor method for the total collateral stored within the SelfMintingPerpetualPositionManagerMultiParty.
* @return totalCollateral amount of all collateral within the position manager.
*/
function totalPositionCollateral()
external
view
nonReentrantView()
returns (uint256)
{
return
globalPositionData
.rawTotalPositionCollateral
.getFeeAdjustedCollateral(feePayerData.cumulativeFeeMultiplier)
.rawValue;
}
/**
* @notice Get the currently minted synthetic tokens from all self-minting derivatives
* @return totalTokens Total amount of synthetic tokens minted
*/
function totalTokensOutstanding() external view returns (uint256) {
return globalPositionData.totalTokensOutstanding.rawValue;
}
/**
* @notice Get the price of synthetic token set by DVM after emergencyShutdown call
* @return Price of synthetic token
*/
function emergencyShutdownPrice()
external
view
isEmergencyShutdown()
returns (uint256)
{
return positionManagerData.emergencyShutdownPrice.rawValue;
}
/** @notice Calculates the DAO fee based on the numTokens parameter
* @param numTokens Number of synthetic tokens used in the transaction
* @return rawValue The DAO fee to be paid in collateralCurrency
*/
function calculateDaoFee(uint256 numTokens) external view returns (uint256) {
return
positionManagerData
.calculateDaoFee(
globalPositionData,
FixedPoint.Unsigned(numTokens),
feePayerData
)
.rawValue;
}
/** @notice Checks the currently set fee recipient and fee percentage for the DAO fee
* @return feePercentage The percentage set by the DAO to be taken as a fee on each transaction
* @return feeRecipient The DAO address that receives the fee
*/
function daoFee()
external
view
returns (uint256 feePercentage, address feeRecipient)
{
(FixedPoint.Unsigned memory percentage, address recipient) =
positionManagerData.daoFee();
feePercentage = percentage.rawValue;
feeRecipient = recipient;
}
/** @notice Check the current cap on self-minting synthetic tokens.
* A cap mint amount is set in order to avoid depletion of liquidity pools,
* by self-minting synthetic assets and redeeming collateral from the pools.
* The cap mint amount is updateable and is based on a percentage of the currently
* minted synthetic assets from the liquidity pools.
* @return capMint The currently set cap amount for self-minting a synthetic token
*/
function capMintAmount() external view returns (uint256 capMint) {
capMint = positionManagerData.capMintAmount().rawValue;
}
/** @notice Check the current cap on deposit of collateral into a self-minting derivative.
* A cap deposit ratio is set in order to avoid a troll attack in which an attacker
* can increase infinitely the GCR thus making it extremelly expensive or impossible
* for other users to self-mint synthetic assets with a given collateral.
* @return capDeposit The current cap deposit ratio
*/
function capDepositRatio() external view returns (uint256 capDeposit) {
capDeposit = positionManagerData.capDepositRatio().rawValue;
}
/**
* @notice Transfers `collateralAmount` of `feePayerData.collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `feePayerData.collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, uint256 collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(sponsor);
positionData.depositTo(
globalPositionData,
positionManagerData,
FixedPoint.Unsigned(collateralAmount),
feePayerData,
sponsor
);
}
/** @notice Check the collateralCurrency in which fees are paid for a given self-minting derivative
* @return collateral The collateral currency
*/
function collateralCurrency()
public
view
override(ISelfMintingDerivativeDeployment, FeePayerParty)
returns (IERC20 collateral)
{
collateral = FeePayerParty.collateralCurrency();
}
//----------------------------------------
// Internal functions
//----------------------------------------
/** @notice Gets the adjusted collateral after substracting fee
* @return adjusted net collateral
*/
function _pfc()
internal
view
virtual
override
returns (FixedPoint.Unsigned memory)
{
return
globalPositionData.rawTotalPositionCollateral.getFeeAdjustedCollateral(
feePayerData.cumulativeFeeMultiplier
);
}
/** @notice Gets all data on a given sponsors position for a self-minting derivative
* @param sponsor Address of the sponsor to check
* @return A struct of information on a tokens sponsor position
*/
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
/** @notice Get a whitelisted price feed implementation from the Finder contract for a self-minting derivative
* @return IdentifierWhitelistInterface Address of the whitelisted identifier
*/
function _getIdentifierWhitelist()
internal
view
returns (IdentifierWhitelistInterface)
{
return
IdentifierWhitelistInterface(
feePayerData.finder.getImplementationAddress(
OracleInterfaces.IdentifierWhitelist
)
);
}
/** @notice Get a whitelisted collateralCurrency address from the Finder contract for a self-minting derivative
* @return AddressWhitelistInterface Address of the whitelisted collateralCurrency
*/
function _getCollateralWhitelist()
internal
view
returns (AddressWhitelistInterface)
{
return
AddressWhitelistInterface(
feePayerData.finder.getImplementationAddress(
OracleInterfaces.CollateralWhitelist
)
);
}
/** @notice Get the collateral for a position of a token sponsor on a self-minting derivative if any
* or return that this token sponsor does not have such a position
* @param sponsor Address of the token sponsor to check
*/
function _onlyCollateralizedPosition(address sponsor) internal view {
require(
positions[sponsor]
.rawCollateral
.getFeeAdjustedCollateral(feePayerData.cumulativeFeeMultiplier)
.isGreaterThan(0),
'Position has no collateral'
);
}
/** @notice Make sure an emergency shutdown is not called on a self-minting derivative
*/
function _notEmergencyShutdown() internal view {
require(
positionManagerData.emergencyShutdownTimestamp == 0,
'Contract emergency shutdown'
);
}
/** @notice Make sure an emergency shutdown is called on a self-minting derivative
*/
function _isEmergencyShutdown() internal view {
require(
positionManagerData.emergencyShutdownTimestamp != 0,
'Contract not emergency shutdown'
);
}
/** @notice Make sure that there are no pending withdraws on a position of a token sponsor
* @param sponsor Token sponsor address for which to check
*/
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(
_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0,
'Pending withdrawal'
);
}
/** @notice Gets the financial contract admin address
*/
function _getFinancialContractsAdminAddress()
internal
view
returns (address)
{
return
feePayerData.finder.getImplementationAddress(
OracleInterfaces.FinancialContractsAdmin
);
}
}
| * @notice Gets the financial contract admin address/ | function _getFinancialContractsAdminAddress()
internal
view
returns (address)
{
return
feePayerData.finder.getImplementationAddress(
OracleInterfaces.FinancialContractsAdmin
);
}
| 1,791,564 | [
1,
3002,
326,
574,
19292,
649,
6835,
3981,
1758,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
389,
588,
6187,
19292,
649,
20723,
4446,
1887,
1435,
203,
565,
2713,
203,
565,
1476,
203,
565,
1135,
261,
2867,
13,
203,
225,
288,
203,
565,
327,
203,
1377,
14036,
52,
1773,
751,
18,
15356,
18,
588,
13621,
1887,
12,
203,
3639,
28544,
10273,
18,
6187,
19292,
649,
20723,
4446,
203,
1377,
11272,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
/*
* @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;
}
}
interface ICAMAEvents {
event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed fromAddress, address indexed toAddress);
}
/**
* @title CustomOwnable
* @dev This contract has the owner address providing basic authorization control
*/
contract CustomOwnable {
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event OwnershipTransferred(address previousOwner, address newOwner);
// Owner of the contract
address private _owner;
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner(), "CustomOwnable: FORBIDDEN");
_;
}
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Sets a new owner address
*/
function _setOwner(address newOwner) internal {
_owner = newOwner;
}
/**
* @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), "CustomOwnable: FORBIDDEN");
emit OwnershipTransferred(owner(), newOwner);
_setOwner(newOwner);
}
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
/**
* @title 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);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev 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;
}
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping (uint256 => address) private _owners;
// Mapping owner address to token count
mapping (address => uint256) private _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC721).interfaceId
|| interfaceId == type(IERC721Metadata).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || 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 _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 || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* 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;
}
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract AppolloAddress is Context, CustomOwnable, ICAMAEvents, ERC165, IERC721, IERC721Metadata {
using SafeMath for uint256;
using Address for address;
using Strings for uint256;
struct Batch {
address owner;
uint96 size;
}
// Mapping from batch start Batch
mapping (uint256 => Batch) private batches;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Mapping owner address to token count
mapping(address => uint) internal _balances;
// Mapping from token ID to owner address
mapping (uint256 => address) private _owners;
uint256 public constant MAX_SUPPLY = 648000000000000;
uint128 public batchSize;
uint128 public nextBatch;
// Token name
string private _name;
// Token symbol
string private _symbol;
address _rootNode;
bool internal _initialized;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function initialize(address owner, uint128 _batchSize, string memory name_, string memory symbol_) public {
require(!_initialized, "CAMA: Already Initialized");
_initialized = true;
_setOwner(owner);
_rootNode = owner;
_name = name_;
batchSize = _batchSize;
_symbol = symbol_;
_balances[owner] = MAX_SUPPLY;
emit ConsecutiveTransfer(0, MAX_SUPPLY, address(0), owner);
}
/**
* @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), "CAMA: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "CAMA: Invalid TokenId");
if (_owners[tokenId] != address(0)) {
return _owners[tokenId];
}
uint256 start = getBatchStart(tokenId);
Batch storage batch = batches[start];
if (batch.size + start > tokenId) {
return batch.owner;
}
return _rootNode;
}
function getBatchStart(uint256 tokenId) public view returns (uint256) {
return tokenId.div(batchSize).mul(batchSize);
}
/**
* @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), "CAMA: 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}. CAMA 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;
}
function exists(uint256 tokenId) public view virtual returns (bool) {
return _exists(tokenId);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return MAX_SUPPLY;
}
function setBaseURI(string memory uri) public virtual onlyOwner {
if (bytes(uri).length > 0) {
_setBaseURI(uri);
}
}
function setTokenURI(uint tokenId, string memory uri) public virtual returns(bool) {
require(_msgSender() == ownerOf(tokenId), "CAMA: Invalid Token Owner");
require(bytes(uri).length > 0, "CAMA: Invalid URI");
_setTokenURI(tokenId, uri);
return true;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = this.ownerOf(tokenId);
require(to != owner, "CAMA: approval to current owner");
require(_msgSender() == owner || this.isApprovedForAll(owner, _msgSender()),
"CAMA: 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), "CAMA: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "CAMA: 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), "CAMA: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
function batchTransfer(address to, uint96 size) public virtual {
require(_msgSender() == owner() || this.isApprovedForAll(_rootNode, _msgSender()), "CAMA: transfer caller is not owner nor approved");
require(to != _rootNode, "CAMA: Can't transfer batch to own address");
_batchTransfer(_rootNode, to, size);
}
function batchTransferFrom(address from, address to, uint[] memory ids) public virtual {
require(from == _msgSender() || this.isApprovedForAll(from, _msgSender()), "CAMA: transfer caller is not owner nor approved");
_batchTransferFrom(from, to, ids);
}
/**
* @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), "CAMA: 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`.
*
* CAMA 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), "CAMA: 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 tokenId < MAX_SUPPLY;
}
/**
* @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), "CAMA: operator query for nonexistent token");
address owner = this.ownerOf(tokenId);
return (owner == spender || getApproved(tokenId) == spender || this.isApprovedForAll(owner, spender));
}
/**
* @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 = this.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];
}
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, CAMA 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(this.ownerOf(tokenId) == from, "CAMA: transfer of token that is not own");
require(to != address(0), "CAMA: 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);
}
function _batchTransfer(address from, address to, uint96 size) internal returns (uint) {
require(to != address(0), "CAMA: must not be null");
require(size > 0 && size <= batchSize, "CAMA: size must be within limits");
uint256 start = nextBatch;
require(_exists(start.add(size)), "CAMA: Max token limit reached");
Batch storage batch = batches[start];
batch.owner = to;
batch.size = size;
uint256 end = start.add(size);
emit ConsecutiveTransfer(start, end, from, to);
nextBatch = uint128(uint256(nextBatch).add(uint256(batchSize)));
_balances[from] = _balances[from].sub(size);
_balances[to] = _balances[to].add(size);
return start;
}
function _batchTransferFrom(address from, address to, uint[] memory ids) internal virtual {
uint len = ids.length;
require(to != address(0), "CAMA: must not be null");
require(ids.length > 1, "CAMA: Min 2 ids");
for (uint i; i < ids.length; i++) {
require(_exists(ids[i]), "CAMA: Invalid TokenId");
require(this.ownerOf(ids[i]) == from, "CAMA: Invalid Owner");
_beforeTokenTransfer(from, to, ids[i]);
// Clear approvals from the previous owner
_approve(address(0), ids[i]);
_owners[ids[i]] = to;
emit Transfer(from, to, ids[i]);
}
_balances[from] -= len;
_balances[to] += len;
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "CAMA: 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()) {
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("CAMA: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(this.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. CAMA 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 { }
}
| * @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), "CAMA: operator query for nonexistent token");
address owner = this.ownerOf(tokenId);
return (owner == spender || getApproved(tokenId) == spender || this.isApprovedForAll(owner, spender));
}
| 12,149,480 | [
1,
1356,
2856,
1375,
87,
1302,
264,
68,
353,
2935,
358,
10680,
1375,
2316,
548,
8338,
29076,
30,
300,
1375,
2316,
548,
68,
1297,
1005,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
291,
31639,
1162,
5541,
12,
2867,
17571,
264,
16,
2254,
5034,
1147,
548,
13,
2713,
1476,
5024,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
24899,
1808,
12,
2316,
548,
3631,
315,
39,
2192,
37,
30,
3726,
843,
364,
1661,
19041,
1147,
8863,
203,
3639,
1758,
3410,
273,
333,
18,
8443,
951,
12,
2316,
548,
1769,
203,
3639,
327,
261,
8443,
422,
17571,
264,
747,
336,
31639,
12,
2316,
548,
13,
422,
17571,
264,
747,
333,
18,
291,
31639,
1290,
1595,
12,
8443,
16,
17571,
264,
10019,
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
]
|
./partial_match/1/0x396fdd293a5C3A692a5E8F2fdE6C62667518D052/sources/WorldOfDypians.sol | * @title WorldOfDypians contract @dev Extends ERC721 Non-Fungible Token Standard basic implementation/ Mapping to keep track of CAWS token IDs that have been used to mint a new NFT | contract WorldOfDypians is ERC721A, Ownable {
using SafeMath for uint256;
string public WOD_PROVENANCE = "";
string public baseURI;
uint256 public startingIndexBlock;
uint256 public startingIndex;
uint public constant maxLandPurchase = 10;
uint256 public MAX_WOD;
uint256 public MAX_MINT = 999;
bool public saleIsActive = false;
uint256 public REVEAL_TIMESTAMP;
CawsContract public cawsContract;
StakeContract public stakeContract;
mapping (uint256 => bool) public cawsUsed;
constructor(string memory name, string memory symbol, uint256 maxNftSupply, uint256 saleStart) ERC721A(name, symbol, maxLandPurchase, maxNftSupply) {
MAX_WOD = maxNftSupply;
REVEAL_TIMESTAMP = saleStart + (86400 * 13);
cawsContract = CawsContract(0xd06cF9e1189FEAb09c844C597abc3767BC12608c);
stakeContract = StakeContract(0xEe425BbbEC5e9Bf4a59a1c19eFff522AD8b7A47A);
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function reserveWod(uint numberOfTokens) public onlyOwner {
require(numberOfTokens > 0, "Mint at least 1 NFT");
require(totalSupply() >= 999, "Genesis Mint is not Finished");
require(totalSupply().add(numberOfTokens) <= MAX_WOD, "Mint would exceed max WOD Lands");
_safeMint(msg.sender, numberOfTokens);
}
function setRevealTimestamp(uint256 revealTimeStamp) public onlyOwner {
REVEAL_TIMESTAMP = revealTimeStamp;
}
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
WOD_PROVENANCE = provenanceHash;
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function setBaseURI(string calldata tokenURI) external onlyOwner {
baseURI = tokenURI;
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function mintWodGenesis(uint numberOfTokens, uint[] calldata tokenIds) public payable {
require(saleIsActive, "Sale must be active to mint WOD");
require(numberOfTokens <= maxLandPurchase, "Can only mint 10 tokens at a time");
require(numberOfTokens > 0, "Mint at least 1 NFT");
require(totalSupply().add(numberOfTokens) <= MAX_MINT, "Purchase would exceed max Genesis Lands");
require(tokenIds.length <= numberOfTokens, "Cannot provide more than 10 CAWS");
uint countDiscount = 0;
if (tokenIds.length != 0) {
for (uint i = 0; i < tokenIds.length; i++) {
if (cawsUsed[tokenIds[i]] != true) {
if (cawsContract.ownerOf(tokenIds[i]) == msg.sender) {
cawsUsed[tokenIds[i]] = true;
countDiscount++;
continue;
}
if (stakeContract.calculateReward(msg.sender, tokenIds[i]) > 0) {
cawsUsed[tokenIds[i]] = true;
countDiscount++;
}
}
}
}
if (countDiscount != 0) {
require(LandPriceDiscount.mul(countDiscount).add(landPrice.mul(numberOfTokens.sub(countDiscount))) <= msg.value, "Ether value sent is not correct");
require(landPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
}
_safeMint(msg.sender, numberOfTokens);
if (startingIndexBlock == 0 && (totalSupply() == MAX_WOD || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
function mintWodGenesis(uint numberOfTokens, uint[] calldata tokenIds) public payable {
require(saleIsActive, "Sale must be active to mint WOD");
require(numberOfTokens <= maxLandPurchase, "Can only mint 10 tokens at a time");
require(numberOfTokens > 0, "Mint at least 1 NFT");
require(totalSupply().add(numberOfTokens) <= MAX_MINT, "Purchase would exceed max Genesis Lands");
require(tokenIds.length <= numberOfTokens, "Cannot provide more than 10 CAWS");
uint countDiscount = 0;
if (tokenIds.length != 0) {
for (uint i = 0; i < tokenIds.length; i++) {
if (cawsUsed[tokenIds[i]] != true) {
if (cawsContract.ownerOf(tokenIds[i]) == msg.sender) {
cawsUsed[tokenIds[i]] = true;
countDiscount++;
continue;
}
if (stakeContract.calculateReward(msg.sender, tokenIds[i]) > 0) {
cawsUsed[tokenIds[i]] = true;
countDiscount++;
}
}
}
}
if (countDiscount != 0) {
require(LandPriceDiscount.mul(countDiscount).add(landPrice.mul(numberOfTokens.sub(countDiscount))) <= msg.value, "Ether value sent is not correct");
require(landPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
}
_safeMint(msg.sender, numberOfTokens);
if (startingIndexBlock == 0 && (totalSupply() == MAX_WOD || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
function mintWodGenesis(uint numberOfTokens, uint[] calldata tokenIds) public payable {
require(saleIsActive, "Sale must be active to mint WOD");
require(numberOfTokens <= maxLandPurchase, "Can only mint 10 tokens at a time");
require(numberOfTokens > 0, "Mint at least 1 NFT");
require(totalSupply().add(numberOfTokens) <= MAX_MINT, "Purchase would exceed max Genesis Lands");
require(tokenIds.length <= numberOfTokens, "Cannot provide more than 10 CAWS");
uint countDiscount = 0;
if (tokenIds.length != 0) {
for (uint i = 0; i < tokenIds.length; i++) {
if (cawsUsed[tokenIds[i]] != true) {
if (cawsContract.ownerOf(tokenIds[i]) == msg.sender) {
cawsUsed[tokenIds[i]] = true;
countDiscount++;
continue;
}
if (stakeContract.calculateReward(msg.sender, tokenIds[i]) > 0) {
cawsUsed[tokenIds[i]] = true;
countDiscount++;
}
}
}
}
if (countDiscount != 0) {
require(LandPriceDiscount.mul(countDiscount).add(landPrice.mul(numberOfTokens.sub(countDiscount))) <= msg.value, "Ether value sent is not correct");
require(landPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
}
_safeMint(msg.sender, numberOfTokens);
if (startingIndexBlock == 0 && (totalSupply() == MAX_WOD || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
function mintWodGenesis(uint numberOfTokens, uint[] calldata tokenIds) public payable {
require(saleIsActive, "Sale must be active to mint WOD");
require(numberOfTokens <= maxLandPurchase, "Can only mint 10 tokens at a time");
require(numberOfTokens > 0, "Mint at least 1 NFT");
require(totalSupply().add(numberOfTokens) <= MAX_MINT, "Purchase would exceed max Genesis Lands");
require(tokenIds.length <= numberOfTokens, "Cannot provide more than 10 CAWS");
uint countDiscount = 0;
if (tokenIds.length != 0) {
for (uint i = 0; i < tokenIds.length; i++) {
if (cawsUsed[tokenIds[i]] != true) {
if (cawsContract.ownerOf(tokenIds[i]) == msg.sender) {
cawsUsed[tokenIds[i]] = true;
countDiscount++;
continue;
}
if (stakeContract.calculateReward(msg.sender, tokenIds[i]) > 0) {
cawsUsed[tokenIds[i]] = true;
countDiscount++;
}
}
}
}
if (countDiscount != 0) {
require(LandPriceDiscount.mul(countDiscount).add(landPrice.mul(numberOfTokens.sub(countDiscount))) <= msg.value, "Ether value sent is not correct");
require(landPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
}
_safeMint(msg.sender, numberOfTokens);
if (startingIndexBlock == 0 && (totalSupply() == MAX_WOD || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
function mintWodGenesis(uint numberOfTokens, uint[] calldata tokenIds) public payable {
require(saleIsActive, "Sale must be active to mint WOD");
require(numberOfTokens <= maxLandPurchase, "Can only mint 10 tokens at a time");
require(numberOfTokens > 0, "Mint at least 1 NFT");
require(totalSupply().add(numberOfTokens) <= MAX_MINT, "Purchase would exceed max Genesis Lands");
require(tokenIds.length <= numberOfTokens, "Cannot provide more than 10 CAWS");
uint countDiscount = 0;
if (tokenIds.length != 0) {
for (uint i = 0; i < tokenIds.length; i++) {
if (cawsUsed[tokenIds[i]] != true) {
if (cawsContract.ownerOf(tokenIds[i]) == msg.sender) {
cawsUsed[tokenIds[i]] = true;
countDiscount++;
continue;
}
if (stakeContract.calculateReward(msg.sender, tokenIds[i]) > 0) {
cawsUsed[tokenIds[i]] = true;
countDiscount++;
}
}
}
}
if (countDiscount != 0) {
require(LandPriceDiscount.mul(countDiscount).add(landPrice.mul(numberOfTokens.sub(countDiscount))) <= msg.value, "Ether value sent is not correct");
require(landPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
}
_safeMint(msg.sender, numberOfTokens);
if (startingIndexBlock == 0 && (totalSupply() == MAX_WOD || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
function mintWodGenesis(uint numberOfTokens, uint[] calldata tokenIds) public payable {
require(saleIsActive, "Sale must be active to mint WOD");
require(numberOfTokens <= maxLandPurchase, "Can only mint 10 tokens at a time");
require(numberOfTokens > 0, "Mint at least 1 NFT");
require(totalSupply().add(numberOfTokens) <= MAX_MINT, "Purchase would exceed max Genesis Lands");
require(tokenIds.length <= numberOfTokens, "Cannot provide more than 10 CAWS");
uint countDiscount = 0;
if (tokenIds.length != 0) {
for (uint i = 0; i < tokenIds.length; i++) {
if (cawsUsed[tokenIds[i]] != true) {
if (cawsContract.ownerOf(tokenIds[i]) == msg.sender) {
cawsUsed[tokenIds[i]] = true;
countDiscount++;
continue;
}
if (stakeContract.calculateReward(msg.sender, tokenIds[i]) > 0) {
cawsUsed[tokenIds[i]] = true;
countDiscount++;
}
}
}
}
if (countDiscount != 0) {
require(LandPriceDiscount.mul(countDiscount).add(landPrice.mul(numberOfTokens.sub(countDiscount))) <= msg.value, "Ether value sent is not correct");
require(landPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
}
_safeMint(msg.sender, numberOfTokens);
if (startingIndexBlock == 0 && (totalSupply() == MAX_WOD || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
function mintWodGenesis(uint numberOfTokens, uint[] calldata tokenIds) public payable {
require(saleIsActive, "Sale must be active to mint WOD");
require(numberOfTokens <= maxLandPurchase, "Can only mint 10 tokens at a time");
require(numberOfTokens > 0, "Mint at least 1 NFT");
require(totalSupply().add(numberOfTokens) <= MAX_MINT, "Purchase would exceed max Genesis Lands");
require(tokenIds.length <= numberOfTokens, "Cannot provide more than 10 CAWS");
uint countDiscount = 0;
if (tokenIds.length != 0) {
for (uint i = 0; i < tokenIds.length; i++) {
if (cawsUsed[tokenIds[i]] != true) {
if (cawsContract.ownerOf(tokenIds[i]) == msg.sender) {
cawsUsed[tokenIds[i]] = true;
countDiscount++;
continue;
}
if (stakeContract.calculateReward(msg.sender, tokenIds[i]) > 0) {
cawsUsed[tokenIds[i]] = true;
countDiscount++;
}
}
}
}
if (countDiscount != 0) {
require(LandPriceDiscount.mul(countDiscount).add(landPrice.mul(numberOfTokens.sub(countDiscount))) <= msg.value, "Ether value sent is not correct");
require(landPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
}
_safeMint(msg.sender, numberOfTokens);
if (startingIndexBlock == 0 && (totalSupply() == MAX_WOD || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
} else {
function mintWodGenesis(uint numberOfTokens, uint[] calldata tokenIds) public payable {
require(saleIsActive, "Sale must be active to mint WOD");
require(numberOfTokens <= maxLandPurchase, "Can only mint 10 tokens at a time");
require(numberOfTokens > 0, "Mint at least 1 NFT");
require(totalSupply().add(numberOfTokens) <= MAX_MINT, "Purchase would exceed max Genesis Lands");
require(tokenIds.length <= numberOfTokens, "Cannot provide more than 10 CAWS");
uint countDiscount = 0;
if (tokenIds.length != 0) {
for (uint i = 0; i < tokenIds.length; i++) {
if (cawsUsed[tokenIds[i]] != true) {
if (cawsContract.ownerOf(tokenIds[i]) == msg.sender) {
cawsUsed[tokenIds[i]] = true;
countDiscount++;
continue;
}
if (stakeContract.calculateReward(msg.sender, tokenIds[i]) > 0) {
cawsUsed[tokenIds[i]] = true;
countDiscount++;
}
}
}
}
if (countDiscount != 0) {
require(LandPriceDiscount.mul(countDiscount).add(landPrice.mul(numberOfTokens.sub(countDiscount))) <= msg.value, "Ether value sent is not correct");
require(landPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
}
_safeMint(msg.sender, numberOfTokens);
if (startingIndexBlock == 0 && (totalSupply() == MAX_WOD || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
function setStartingIndex() public {
require(startingIndex == 0, "Starting index is already set");
require(startingIndexBlock != 0, "Starting index block must be set");
startingIndex = uint(blockhash(startingIndexBlock)) % MAX_WOD;
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number - 1)) % MAX_WOD;
}
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
function setStartingIndex() public {
require(startingIndex == 0, "Starting index is already set");
require(startingIndexBlock != 0, "Starting index block must be set");
startingIndex = uint(blockhash(startingIndexBlock)) % MAX_WOD;
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number - 1)) % MAX_WOD;
}
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
function setStartingIndex() public {
require(startingIndex == 0, "Starting index is already set");
require(startingIndexBlock != 0, "Starting index block must be set");
startingIndex = uint(blockhash(startingIndexBlock)) % MAX_WOD;
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number - 1)) % MAX_WOD;
}
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, "Starting index is already set");
startingIndexBlock = block.number;
}
} | 15,624,813 | [
1,
18071,
951,
40,
879,
19657,
6835,
225,
6419,
5839,
4232,
39,
27,
5340,
3858,
17,
42,
20651,
1523,
3155,
8263,
5337,
4471,
19,
9408,
358,
3455,
3298,
434,
6425,
2651,
1147,
7115,
716,
1240,
2118,
1399,
358,
312,
474,
279,
394,
423,
4464,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
21820,
951,
40,
879,
19657,
353,
4232,
39,
27,
5340,
37,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
533,
1071,
678,
1212,
67,
3373,
58,
1157,
4722,
273,
1408,
31,
203,
203,
565,
533,
1071,
1026,
3098,
31,
203,
203,
565,
2254,
5034,
1071,
5023,
1016,
1768,
31,
203,
203,
565,
2254,
5034,
1071,
5023,
1016,
31,
203,
203,
203,
377,
203,
565,
2254,
1071,
5381,
943,
29398,
23164,
273,
1728,
31,
203,
203,
565,
2254,
5034,
1071,
4552,
67,
59,
1212,
31,
203,
203,
565,
2254,
5034,
1071,
4552,
67,
49,
3217,
273,
22249,
31,
203,
203,
565,
1426,
1071,
272,
5349,
2520,
3896,
273,
629,
31,
203,
203,
565,
2254,
5034,
1071,
2438,
3412,
1013,
67,
17201,
31,
203,
203,
565,
385,
6850,
8924,
1071,
276,
6850,
8924,
31,
203,
565,
934,
911,
8924,
1071,
384,
911,
8924,
31,
203,
203,
565,
2874,
261,
11890,
5034,
516,
1426,
13,
1071,
276,
6850,
6668,
31,
203,
203,
565,
3885,
12,
1080,
3778,
508,
16,
533,
3778,
3273,
16,
2254,
5034,
943,
50,
1222,
3088,
1283,
16,
2254,
5034,
272,
5349,
1685,
13,
4232,
39,
27,
5340,
37,
12,
529,
16,
3273,
16,
943,
29398,
23164,
16,
943,
50,
1222,
3088,
1283,
13,
288,
203,
3639,
4552,
67,
59,
1212,
273,
943,
50,
1222,
3088,
1283,
31,
203,
3639,
2438,
3412,
1013,
67,
17201,
273,
272,
5349,
1685,
397,
261,
28,
1105,
713,
380,
5958,
1769,
203,
203,
3639,
276,
6850,
8924,
273,
385,
2
]
|
./partial_match/1/0xDDE5B33a56f3F1C22e5a6bd8429E6ad508BFF24E/sources/WHCToken.sol | 2022-04-01T00:00:00Z
| foundationMap[5]=1648771200; | 2,884,448 | [
1,
18212,
22,
17,
3028,
17,
1611,
56,
713,
30,
713,
30,
713,
62,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
202,
202,
30493,
863,
63,
25,
65,
33,
23147,
28,
4700,
2138,
713,
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
]
|
/*
Copyright 2022 libertyland
SPDX-License-Identifier: Apache-2.0
Website: https://www.libertyland.finance/
TLT: https://www.thelostthrone.net/
CertikReport: https://www.certik.com/projects/the-lost-throne
*/
pragma solidity ^0.8.0;
interface ITheLostThroneCard {
function mint(
address to,
uint256 tokenId,
uint256 amount,
bytes memory data
) external;
function bacthMint(
address to,
uint256[] memory tokenIds,
uint256[] memory amounts
) external;
}
interface IRandomGenerator {
function random(uint256 seed) external view returns (uint256);
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
abstract contract Pausable is Context {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor() {
_paused = false;
}
function paused() public view virtual returns (bool) {
return _paused;
}
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
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 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 {
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;
}
}
}
pragma solidity ^0.8.1;
library Address {
function isContract(address account) internal view returns (bool) {
return account.code.length > 0;
}
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");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
abstract contract Initializable {
bool private _initialized;
bool private _initializing;
modifier initializer() {
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !Address.isContract(address(this));
}
}
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface IERC721Receiver {
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
contract ERC721Holder is IERC721Receiver {
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
contract MysteryBoxTron is Ownable, Initializable, Pausable, ERC721Holder {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
// ============ Storage ============
bytes32 public constant CONTROL_TYPE = keccak256("GAME_BOX");
address public _FEECOLLECTOR_;
uint256 public _MINTED_;
uint256 public _TRX_MINTED_;
uint256 public _TOKEN_MINTED_;
uint256 public _TRX_PRCIE_ = 1300 trx;
uint256 public constant _TRX_MINTED_LIMIT_ = 2510;
uint256 public _TOKEN_MINTED_LIMIT_ = 0;
uint256 public _TOKEN_PRCIE_;
IRandomGenerator private _RANDOM_;
ITheLostThroneCard public _CARD_;
IERC20 public _PAID_TOKEN_;
bool public _SELL_START_ = false;
mapping(IERC721 => bool) public white_tickets;
// user rarity query for alloc
mapping(uint256 => uint256[]) public rarity_alloc;
// use rarity query for total alloc by rarity group
mapping(uint256 => uint256) public rarity_alloc_total;
// use rarity query for alloc, then get cid
mapping(uint256 => mapping(uint256 => uint256[])) public rarity_alloc_cid;
// ============ Event =============
event UpdateWhiteTicekt(address ticket, bool state);
event UpdateRandom(address randomGenerator);
event UpdateCollector(address newCollector);
event UpdatePaidToken(address paidToken, uint256 tokenPrice);
event UpdateBucketNum(uint256 originNum, uint256 num);
modifier whenSellStart() {
require(_SELL_START_, "Not yet start");
_;
}
fallback() external payable {}
receive() external payable {}
function init(
IRandomGenerator randomGen,
ITheLostThroneCard card,
address owner,
address fee
) external initializer {
require(owner != address(0));
transferOwnership(owner);
_FEECOLLECTOR_ = fee;
_RANDOM_ = randomGen;
_CARD_ = card;
}
// =========== External =============
// unlimited mysterybox pay by trx
function mintByTRX(uint256 amount)
external
payable
whenNotPaused
whenSellStart
{
require(_TRX_PRCIE_ > 0,"Invalid trx price");
require(
_TRX_MINTED_ + amount <= _TRX_MINTED_LIMIT_,
"TRX mint finished."
);
require(amount > 0 && amount <= 10, "Invalid mint amount");
require(amount * _TRX_PRCIE_ <= msg.value, "Invalid payment amount");
(bool success, ) = payable(_FEECOLLECTOR_).call{
value: address(this).balance
}(new bytes(0));
require(success, "Transfer eth failed");
_TRX_MINTED_ += amount;
_mintCharacter(amount);
}
// unlimited mysterybox pay by token
function mintByERC20(uint256 amount) external whenNotPaused {
require(address(_PAID_TOKEN_) != address(0), "Paidtoken not yet");
require(amount > 0 && amount <= 10, "Invalid mint amount");
if (_TOKEN_MINTED_LIMIT_ > 0) {
require(
_TOKEN_MINTED_ + amount <= _TOKEN_MINTED_LIMIT_,
"Token mint finished"
);
}
uint256 cost = _TOKEN_PRCIE_ * amount;
_PAID_TOKEN_.safeTransferFrom(msg.sender, _FEECOLLECTOR_, cost);
_TOKEN_MINTED_ += amount;
_mintCharacter(amount);
}
// unlimited mysterybox pay by white ticket
function mintByTicket(uint256[] calldata tokenIds, IERC721 ticket)
external
whenNotPaused
{
require(address(ticket) != address(0), "not allowed");
require(white_tickets[ticket], "only white ticket");
for (uint256 i = 0; i < tokenIds.length; i++) {
ticket.safeTransferFrom(
msg.sender,
address(this),
tokenIds[i],
"0x"
);
}
_mintCharacter(tokenIds.length);
}
// ================= View ===================
function _getOneRarity(uint256 num)
internal
view
returns (uint256 rarity, uint256 seed)
{
seed = _RANDOM_.random(num + (gasleft()));
rarity = _caculateRarity(seed % 100);
}
// =============== Internal ================
function _mintCharacter(uint256 num) internal {
uint256[] memory cids = new uint256[](num);
uint256[] memory amounts = new uint256[](num);
for (uint256 i = 0; i < num; i++) {
_MINTED_++;
(uint256 rarity, uint256 seed) = _getOneRarity(_MINTED_);
cids[i] = _pickUpCid(rarity, seed);
amounts[i] = 1;
}
_CARD_.bacthMint(msg.sender, cids, amounts);
}
function _pickUpCid(uint256 rarity, uint256 seed)
internal
view
returns (uint256)
{
uint256[] memory allocs = rarity_alloc[rarity];
uint256 totalalloc = rarity_alloc_total[rarity];
// caculate total rarity_alloc
uint256 bucket = (seed & 0xFFFFFFFF) % totalalloc;
uint256 cumulative = totalalloc;
seed >>= 32;
uint256[] memory cids;
// get alloc order by decs
for (uint256 i = (allocs.length - 1); i > 0; i--) {
cumulative -= allocs[i];
if (bucket > cumulative) {
cids = rarity_alloc_cid[rarity][allocs[i]];
return cids[seed % cids.length];
}
}
cids = rarity_alloc_cid[rarity][allocs[0]];
return cids[seed % cids.length];
}
// rarity: 1 Diamond %, 2 Gold 13%, 3 Silver 89%
function _caculateRarity(uint256 random)
internal
pure
returns (uint256 rarity)
{
if (random < 10) {
return 2;
} else if (random < 99) {
return 3;
} else {
return 1;
}
}
// ================= OnlyOwner ===================
function updateRandomGenerator(address newRandomGenerator)
external
onlyOwner
{
require(newRandomGenerator != address(0));
_RANDOM_ = IRandomGenerator(newRandomGenerator);
emit UpdateRandom(newRandomGenerator);
}
function setPaidToken(IERC20 _token, uint256 _tokenPrice)
external
onlyOwner
{
_PAID_TOKEN_ = _token;
_TOKEN_PRCIE_ = _tokenPrice;
emit UpdatePaidToken(address(_token), _tokenPrice);
}
function setTokenMintLimit(uint256 limit) external onlyOwner {
_TOKEN_MINTED_LIMIT_ = limit;
}
function setWhiteTicket(IERC721 ticket, bool state) external onlyOwner {
white_tickets[ticket] = state;
emit UpdateWhiteTicekt(address(ticket), state);
}
function sellStart(bool _state) external onlyOwner {
_SELL_START_ = _state;
}
function setPaused(bool _paused) external onlyOwner {
if (_paused) _pause();
else _unpause();
}
function updateFeeCollector(address _collector) external onlyOwner {
_FEECOLLECTOR_ = _collector;
emit UpdateCollector(_collector);
}
function withdraw(address _token) external {
require(msg.sender == _FEECOLLECTOR_, "not collector");
if (_token == address(0)) {
payable(_FEECOLLECTOR_).transfer(address(this).balance);
return;
}
IERC20 token = IERC20(_token);
token.transfer(_FEECOLLECTOR_, token.balanceOf(address(this)));
}
// set or add cid, only Owner execute after init
function setCid(
uint256[] calldata cids,
uint256[] calldata allocs,
uint256[] calldata raritys
) external onlyOwner {
require(cids.length == allocs.length, "Array length must equals!");
require(cids.length == raritys.length, "Array length must equals!");
for (uint256 i = 0; i < cids.length; i++) {
bool flag = false;
rarity_alloc_cid[raritys[i]][allocs[i]].push(cids[i]);
if (rarity_alloc[raritys[i]].length == 0) {
rarity_alloc[raritys[i]].push(allocs[i]);
rarity_alloc_total[raritys[i]] += allocs[i];
}
for (uint256 m = 0; m < rarity_alloc[raritys[i]].length; m++) {
if (rarity_alloc[raritys[i]][m] == allocs[i]) flag = true;
}
if (!flag) {
rarity_alloc[raritys[i]].push(allocs[i]);
rarity_alloc_total[raritys[i]] += allocs[i];
}
}
}
}
| ============ Storage ============ user rarity query for alloc use rarity query for total alloc by rarity group use rarity query for alloc, then get cid ============ Event ============= | contract MysteryBoxTron is Ownable, Initializable, Pausable, ERC721Holder {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
bytes32 public constant CONTROL_TYPE = keccak256("GAME_BOX");
address public _FEECOLLECTOR_;
uint256 public _MINTED_;
uint256 public _TRX_MINTED_;
uint256 public _TOKEN_MINTED_;
uint256 public _TRX_PRCIE_ = 1300 trx;
uint256 public constant _TRX_MINTED_LIMIT_ = 2510;
uint256 public _TOKEN_MINTED_LIMIT_ = 0;
uint256 public _TOKEN_PRCIE_;
IRandomGenerator private _RANDOM_;
ITheLostThroneCard public _CARD_;
IERC20 public _PAID_TOKEN_;
bool public _SELL_START_ = false;
mapping(IERC721 => bool) public white_tickets;
mapping(uint256 => uint256[]) public rarity_alloc;
mapping(uint256 => uint256) public rarity_alloc_total;
mapping(uint256 => mapping(uint256 => uint256[])) public rarity_alloc_cid;
event UpdateWhiteTicekt(address ticket, bool state);
event UpdateRandom(address randomGenerator);
event UpdateCollector(address newCollector);
event UpdatePaidToken(address paidToken, uint256 tokenPrice);
event UpdateBucketNum(uint256 originNum, uint256 num);
modifier whenSellStart() {
require(_SELL_START_, "Not yet start");
_;
}
fallback() external payable {}
receive() external payable {}
function init(
IRandomGenerator randomGen,
ITheLostThroneCard card,
address owner,
address fee
) external initializer {
require(owner != address(0));
transferOwnership(owner);
_FEECOLLECTOR_ = fee;
_RANDOM_ = randomGen;
_CARD_ = card;
}
function mintByTRX(uint256 amount)
external
payable
whenNotPaused
whenSellStart
{
require(_TRX_PRCIE_ > 0,"Invalid trx price");
require(
_TRX_MINTED_ + amount <= _TRX_MINTED_LIMIT_,
"TRX mint finished."
);
require(amount > 0 && amount <= 10, "Invalid mint amount");
require(amount * _TRX_PRCIE_ <= msg.value, "Invalid payment amount");
(bool success, ) = payable(_FEECOLLECTOR_).call{
value: address(this).balance
}(new bytes(0));
require(success, "Transfer eth failed");
_TRX_MINTED_ += amount;
_mintCharacter(amount);
}
function mintByTRX(uint256 amount)
external
payable
whenNotPaused
whenSellStart
{
require(_TRX_PRCIE_ > 0,"Invalid trx price");
require(
_TRX_MINTED_ + amount <= _TRX_MINTED_LIMIT_,
"TRX mint finished."
);
require(amount > 0 && amount <= 10, "Invalid mint amount");
require(amount * _TRX_PRCIE_ <= msg.value, "Invalid payment amount");
(bool success, ) = payable(_FEECOLLECTOR_).call{
value: address(this).balance
}(new bytes(0));
require(success, "Transfer eth failed");
_TRX_MINTED_ += amount;
_mintCharacter(amount);
}
function mintByERC20(uint256 amount) external whenNotPaused {
require(address(_PAID_TOKEN_) != address(0), "Paidtoken not yet");
require(amount > 0 && amount <= 10, "Invalid mint amount");
if (_TOKEN_MINTED_LIMIT_ > 0) {
require(
_TOKEN_MINTED_ + amount <= _TOKEN_MINTED_LIMIT_,
"Token mint finished"
);
}
uint256 cost = _TOKEN_PRCIE_ * amount;
_PAID_TOKEN_.safeTransferFrom(msg.sender, _FEECOLLECTOR_, cost);
_TOKEN_MINTED_ += amount;
_mintCharacter(amount);
}
function mintByERC20(uint256 amount) external whenNotPaused {
require(address(_PAID_TOKEN_) != address(0), "Paidtoken not yet");
require(amount > 0 && amount <= 10, "Invalid mint amount");
if (_TOKEN_MINTED_LIMIT_ > 0) {
require(
_TOKEN_MINTED_ + amount <= _TOKEN_MINTED_LIMIT_,
"Token mint finished"
);
}
uint256 cost = _TOKEN_PRCIE_ * amount;
_PAID_TOKEN_.safeTransferFrom(msg.sender, _FEECOLLECTOR_, cost);
_TOKEN_MINTED_ += amount;
_mintCharacter(amount);
}
function mintByTicket(uint256[] calldata tokenIds, IERC721 ticket)
external
whenNotPaused
{
require(address(ticket) != address(0), "not allowed");
require(white_tickets[ticket], "only white ticket");
for (uint256 i = 0; i < tokenIds.length; i++) {
ticket.safeTransferFrom(
msg.sender,
address(this),
tokenIds[i],
"0x"
);
}
_mintCharacter(tokenIds.length);
}
function mintByTicket(uint256[] calldata tokenIds, IERC721 ticket)
external
whenNotPaused
{
require(address(ticket) != address(0), "not allowed");
require(white_tickets[ticket], "only white ticket");
for (uint256 i = 0; i < tokenIds.length; i++) {
ticket.safeTransferFrom(
msg.sender,
address(this),
tokenIds[i],
"0x"
);
}
_mintCharacter(tokenIds.length);
}
function _getOneRarity(uint256 num)
internal
view
returns (uint256 rarity, uint256 seed)
{
seed = _RANDOM_.random(num + (gasleft()));
rarity = _caculateRarity(seed % 100);
}
function _mintCharacter(uint256 num) internal {
uint256[] memory cids = new uint256[](num);
uint256[] memory amounts = new uint256[](num);
for (uint256 i = 0; i < num; i++) {
_MINTED_++;
(uint256 rarity, uint256 seed) = _getOneRarity(_MINTED_);
cids[i] = _pickUpCid(rarity, seed);
amounts[i] = 1;
}
_CARD_.bacthMint(msg.sender, cids, amounts);
}
function _mintCharacter(uint256 num) internal {
uint256[] memory cids = new uint256[](num);
uint256[] memory amounts = new uint256[](num);
for (uint256 i = 0; i < num; i++) {
_MINTED_++;
(uint256 rarity, uint256 seed) = _getOneRarity(_MINTED_);
cids[i] = _pickUpCid(rarity, seed);
amounts[i] = 1;
}
_CARD_.bacthMint(msg.sender, cids, amounts);
}
function _pickUpCid(uint256 rarity, uint256 seed)
internal
view
returns (uint256)
{
uint256[] memory allocs = rarity_alloc[rarity];
uint256 totalalloc = rarity_alloc_total[rarity];
uint256 bucket = (seed & 0xFFFFFFFF) % totalalloc;
uint256 cumulative = totalalloc;
seed >>= 32;
uint256[] memory cids;
for (uint256 i = (allocs.length - 1); i > 0; i--) {
cumulative -= allocs[i];
if (bucket > cumulative) {
cids = rarity_alloc_cid[rarity][allocs[i]];
return cids[seed % cids.length];
}
}
cids = rarity_alloc_cid[rarity][allocs[0]];
return cids[seed % cids.length];
}
function _pickUpCid(uint256 rarity, uint256 seed)
internal
view
returns (uint256)
{
uint256[] memory allocs = rarity_alloc[rarity];
uint256 totalalloc = rarity_alloc_total[rarity];
uint256 bucket = (seed & 0xFFFFFFFF) % totalalloc;
uint256 cumulative = totalalloc;
seed >>= 32;
uint256[] memory cids;
for (uint256 i = (allocs.length - 1); i > 0; i--) {
cumulative -= allocs[i];
if (bucket > cumulative) {
cids = rarity_alloc_cid[rarity][allocs[i]];
return cids[seed % cids.length];
}
}
cids = rarity_alloc_cid[rarity][allocs[0]];
return cids[seed % cids.length];
}
function _pickUpCid(uint256 rarity, uint256 seed)
internal
view
returns (uint256)
{
uint256[] memory allocs = rarity_alloc[rarity];
uint256 totalalloc = rarity_alloc_total[rarity];
uint256 bucket = (seed & 0xFFFFFFFF) % totalalloc;
uint256 cumulative = totalalloc;
seed >>= 32;
uint256[] memory cids;
for (uint256 i = (allocs.length - 1); i > 0; i--) {
cumulative -= allocs[i];
if (bucket > cumulative) {
cids = rarity_alloc_cid[rarity][allocs[i]];
return cids[seed % cids.length];
}
}
cids = rarity_alloc_cid[rarity][allocs[0]];
return cids[seed % cids.length];
}
function _caculateRarity(uint256 random)
internal
pure
returns (uint256 rarity)
{
if (random < 10) {
return 2;
return 3;
return 1;
}
}
function _caculateRarity(uint256 random)
internal
pure
returns (uint256 rarity)
{
if (random < 10) {
return 2;
return 3;
return 1;
}
}
} else if (random < 99) {
} else {
function updateRandomGenerator(address newRandomGenerator)
external
onlyOwner
{
require(newRandomGenerator != address(0));
_RANDOM_ = IRandomGenerator(newRandomGenerator);
emit UpdateRandom(newRandomGenerator);
}
function setPaidToken(IERC20 _token, uint256 _tokenPrice)
external
onlyOwner
{
_PAID_TOKEN_ = _token;
_TOKEN_PRCIE_ = _tokenPrice;
emit UpdatePaidToken(address(_token), _tokenPrice);
}
function setTokenMintLimit(uint256 limit) external onlyOwner {
_TOKEN_MINTED_LIMIT_ = limit;
}
function setWhiteTicket(IERC721 ticket, bool state) external onlyOwner {
white_tickets[ticket] = state;
emit UpdateWhiteTicekt(address(ticket), state);
}
function sellStart(bool _state) external onlyOwner {
_SELL_START_ = _state;
}
function setPaused(bool _paused) external onlyOwner {
if (_paused) _pause();
else _unpause();
}
function updateFeeCollector(address _collector) external onlyOwner {
_FEECOLLECTOR_ = _collector;
emit UpdateCollector(_collector);
}
function withdraw(address _token) external {
require(msg.sender == _FEECOLLECTOR_, "not collector");
if (_token == address(0)) {
payable(_FEECOLLECTOR_).transfer(address(this).balance);
return;
}
IERC20 token = IERC20(_token);
token.transfer(_FEECOLLECTOR_, token.balanceOf(address(this)));
}
function withdraw(address _token) external {
require(msg.sender == _FEECOLLECTOR_, "not collector");
if (_token == address(0)) {
payable(_FEECOLLECTOR_).transfer(address(this).balance);
return;
}
IERC20 token = IERC20(_token);
token.transfer(_FEECOLLECTOR_, token.balanceOf(address(this)));
}
function setCid(
uint256[] calldata cids,
uint256[] calldata allocs,
uint256[] calldata raritys
) external onlyOwner {
require(cids.length == allocs.length, "Array length must equals!");
require(cids.length == raritys.length, "Array length must equals!");
for (uint256 i = 0; i < cids.length; i++) {
bool flag = false;
rarity_alloc_cid[raritys[i]][allocs[i]].push(cids[i]);
if (rarity_alloc[raritys[i]].length == 0) {
rarity_alloc[raritys[i]].push(allocs[i]);
rarity_alloc_total[raritys[i]] += allocs[i];
}
for (uint256 m = 0; m < rarity_alloc[raritys[i]].length; m++) {
if (rarity_alloc[raritys[i]][m] == allocs[i]) flag = true;
}
if (!flag) {
rarity_alloc[raritys[i]].push(allocs[i]);
rarity_alloc_total[raritys[i]] += allocs[i];
}
}
}
function setCid(
uint256[] calldata cids,
uint256[] calldata allocs,
uint256[] calldata raritys
) external onlyOwner {
require(cids.length == allocs.length, "Array length must equals!");
require(cids.length == raritys.length, "Array length must equals!");
for (uint256 i = 0; i < cids.length; i++) {
bool flag = false;
rarity_alloc_cid[raritys[i]][allocs[i]].push(cids[i]);
if (rarity_alloc[raritys[i]].length == 0) {
rarity_alloc[raritys[i]].push(allocs[i]);
rarity_alloc_total[raritys[i]] += allocs[i];
}
for (uint256 m = 0; m < rarity_alloc[raritys[i]].length; m++) {
if (rarity_alloc[raritys[i]][m] == allocs[i]) flag = true;
}
if (!flag) {
rarity_alloc[raritys[i]].push(allocs[i]);
rarity_alloc_total[raritys[i]] += allocs[i];
}
}
}
function setCid(
uint256[] calldata cids,
uint256[] calldata allocs,
uint256[] calldata raritys
) external onlyOwner {
require(cids.length == allocs.length, "Array length must equals!");
require(cids.length == raritys.length, "Array length must equals!");
for (uint256 i = 0; i < cids.length; i++) {
bool flag = false;
rarity_alloc_cid[raritys[i]][allocs[i]].push(cids[i]);
if (rarity_alloc[raritys[i]].length == 0) {
rarity_alloc[raritys[i]].push(allocs[i]);
rarity_alloc_total[raritys[i]] += allocs[i];
}
for (uint256 m = 0; m < rarity_alloc[raritys[i]].length; m++) {
if (rarity_alloc[raritys[i]][m] == allocs[i]) flag = true;
}
if (!flag) {
rarity_alloc[raritys[i]].push(allocs[i]);
rarity_alloc_total[raritys[i]] += allocs[i];
}
}
}
function setCid(
uint256[] calldata cids,
uint256[] calldata allocs,
uint256[] calldata raritys
) external onlyOwner {
require(cids.length == allocs.length, "Array length must equals!");
require(cids.length == raritys.length, "Array length must equals!");
for (uint256 i = 0; i < cids.length; i++) {
bool flag = false;
rarity_alloc_cid[raritys[i]][allocs[i]].push(cids[i]);
if (rarity_alloc[raritys[i]].length == 0) {
rarity_alloc[raritys[i]].push(allocs[i]);
rarity_alloc_total[raritys[i]] += allocs[i];
}
for (uint256 m = 0; m < rarity_alloc[raritys[i]].length; m++) {
if (rarity_alloc[raritys[i]][m] == allocs[i]) flag = true;
}
if (!flag) {
rarity_alloc[raritys[i]].push(allocs[i]);
rarity_alloc_total[raritys[i]] += allocs[i];
}
}
}
function setCid(
uint256[] calldata cids,
uint256[] calldata allocs,
uint256[] calldata raritys
) external onlyOwner {
require(cids.length == allocs.length, "Array length must equals!");
require(cids.length == raritys.length, "Array length must equals!");
for (uint256 i = 0; i < cids.length; i++) {
bool flag = false;
rarity_alloc_cid[raritys[i]][allocs[i]].push(cids[i]);
if (rarity_alloc[raritys[i]].length == 0) {
rarity_alloc[raritys[i]].push(allocs[i]);
rarity_alloc_total[raritys[i]] += allocs[i];
}
for (uint256 m = 0; m < rarity_alloc[raritys[i]].length; m++) {
if (rarity_alloc[raritys[i]][m] == allocs[i]) flag = true;
}
if (!flag) {
rarity_alloc[raritys[i]].push(allocs[i]);
rarity_alloc_total[raritys[i]] += allocs[i];
}
}
}
}
| 14,067,313 | [
1,
14468,
5235,
422,
1432,
631,
729,
436,
20498,
843,
364,
4767,
999,
436,
20498,
843,
364,
2078,
4767,
635,
436,
20498,
1041,
999,
436,
20498,
843,
364,
4767,
16,
1508,
336,
7504,
422,
1432,
631,
2587,
422,
1432,
12275,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
490,
1094,
627,
3514,
1070,
265,
353,
14223,
6914,
16,
10188,
6934,
16,
21800,
16665,
16,
4232,
39,
27,
5340,
6064,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
565,
1731,
1578,
1071,
5381,
8020,
13429,
67,
2399,
273,
417,
24410,
581,
5034,
2932,
43,
1642,
67,
16876,
8863,
203,
565,
1758,
1071,
389,
8090,
41,
4935,
3918,
916,
67,
31,
203,
565,
2254,
5034,
1071,
389,
6236,
6404,
67,
31,
203,
565,
2254,
5034,
1071,
389,
4349,
60,
67,
6236,
6404,
67,
31,
203,
565,
2254,
5034,
1071,
389,
8412,
67,
6236,
6404,
67,
31,
203,
565,
2254,
5034,
1071,
389,
4349,
60,
67,
8025,
7266,
41,
67,
273,
5958,
713,
433,
92,
31,
203,
565,
2254,
5034,
1071,
5381,
389,
4349,
60,
67,
6236,
6404,
67,
8283,
67,
273,
6969,
2163,
31,
203,
565,
2254,
5034,
1071,
389,
8412,
67,
6236,
6404,
67,
8283,
67,
273,
374,
31,
203,
565,
2254,
5034,
1071,
389,
8412,
67,
8025,
7266,
41,
67,
31,
203,
565,
467,
8529,
3908,
3238,
389,
54,
28159,
67,
31,
203,
565,
467,
1986,
19024,
1315,
86,
476,
6415,
1071,
389,
28760,
67,
31,
203,
565,
467,
654,
39,
3462,
1071,
389,
4066,
734,
67,
8412,
67,
31,
203,
565,
1426,
1071,
389,
1090,
4503,
67,
7570,
67,
273,
629,
31,
203,
565,
2874,
12,
45,
654,
39,
27,
5340,
516,
1426,
13,
1071,
9578,
67,
2
]
|
./full_match/44787/0xa0B190d02C4340B61399cc1D2B7d04B0cB257bF3/sources/contracts/Campaign.sol | * Campaign initialization, called once at deploy (using the campaign factory). CHALLENGE_PERIOD > ACTIVE_DURATION is recommended to limite one proposeal per active window/ | function initCampaign(
bytes32 _rewardRulesetUri,
address _admin,
address _oracle,
uint256 _activationTime,
uint256 _CHALLENGE_PERIOD,
uint256 _ACTIVATION_PERIOD,
uint256 _ACTIVE_DURATION
) external initializer {
rewardRulesetUri = _rewardRulesetUri;
admin = _admin;
oracle = _oracle;
activationTime = _activationTime > 0 ? _activationTime : block.timestamp;
deployTime = block.timestamp;
CHALLENGE_PERIOD = _CHALLENGE_PERIOD;
ACTIVATION_PERIOD = _ACTIVATION_PERIOD;
ACTIVE_DURATION = _ACTIVE_DURATION;
}
| 13,263,286 | [
1,
13432,
10313,
16,
2566,
3647,
622,
7286,
261,
9940,
326,
8965,
3272,
2934,
6469,
1013,
7011,
41,
67,
28437,
405,
21135,
67,
24951,
353,
14553,
358,
1800,
73,
1245,
450,
4150,
287,
1534,
2695,
2742,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1208,
13432,
12,
203,
3639,
1731,
1578,
389,
266,
2913,
4478,
278,
3006,
16,
203,
3639,
1758,
389,
3666,
16,
203,
3639,
1758,
389,
280,
16066,
16,
203,
3639,
2254,
5034,
389,
16908,
950,
16,
203,
3639,
2254,
5034,
389,
1792,
1013,
7011,
41,
67,
28437,
16,
203,
3639,
2254,
5034,
389,
22271,
2689,
67,
28437,
16,
203,
3639,
2254,
5034,
389,
13301,
67,
24951,
203,
565,
262,
3903,
12562,
288,
203,
3639,
19890,
4478,
278,
3006,
273,
389,
266,
2913,
4478,
278,
3006,
31,
203,
3639,
3981,
273,
389,
3666,
31,
203,
3639,
20865,
273,
389,
280,
16066,
31,
203,
3639,
10027,
950,
273,
389,
16908,
950,
405,
374,
692,
389,
16908,
950,
294,
1203,
18,
5508,
31,
203,
3639,
7286,
950,
273,
1203,
18,
5508,
31,
203,
203,
3639,
6469,
1013,
7011,
41,
67,
28437,
273,
389,
1792,
1013,
7011,
41,
67,
28437,
31,
203,
3639,
14684,
8188,
2689,
67,
28437,
273,
389,
22271,
2689,
67,
28437,
31,
203,
3639,
21135,
67,
24951,
273,
389,
13301,
67,
24951,
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
]
|
./full_match/137/0x32201d0f8C57fCeb5A2e26155bc0412bE9ca83BD/sources/CRPFactory.sol | Fee is initialized on creation, and can be changed if permission is set Only needed for temporary storage between construction and createPool Thereafter, the swap fee should always be read from the underlying pool | uint private _initialSwapFee;
| 3,765,579 | [
1,
14667,
353,
6454,
603,
6710,
16,
471,
848,
506,
3550,
309,
4132,
353,
444,
5098,
3577,
364,
6269,
2502,
3086,
16171,
471,
752,
2864,
6149,
5205,
16,
326,
7720,
14036,
1410,
3712,
506,
855,
628,
326,
6808,
2845,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2254,
3238,
389,
6769,
12521,
14667,
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
]
|
./full_match/1/0x365aBa0acea260fAe1c7E08577Ed645697Be648d/sources/contracts/messaging/connectors/optimism/lib/Types.sol | * @title Types @notice Contains various types used throughout the Optimism contract system./ | library Types {
pragma solidity 0.8.17;
struct OutputProposal {
bytes32 outputRoot;
uint128 timestamp;
uint128 l2BlockNumber;
}
struct OutputRootProof {
bytes32 version;
bytes32 stateRoot;
bytes32 messagePasserStorageRoot;
bytes32 latestBlockhash;
}
struct UserDepositTransaction {
address from;
address to;
bool isCreation;
uint256 value;
uint256 mint;
uint64 gasLimit;
bytes data;
bytes32 l1BlockHash;
uint256 logIndex;
}
struct WithdrawalTransaction {
uint256 nonce;
address sender;
address target;
uint256 value;
uint256 gasLimit;
bytes data;
}
}
| 8,481,752 | [
1,
2016,
225,
8398,
11191,
1953,
1399,
3059,
659,
326,
19615,
6228,
6835,
2619,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
12083,
7658,
288,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
4033,
31,
203,
225,
1958,
3633,
14592,
288,
203,
565,
1731,
1578,
876,
2375,
31,
203,
565,
2254,
10392,
2858,
31,
203,
565,
2254,
10392,
328,
22,
1768,
1854,
31,
203,
225,
289,
203,
203,
225,
1958,
3633,
2375,
20439,
288,
203,
565,
1731,
1578,
1177,
31,
203,
565,
1731,
1578,
919,
2375,
31,
203,
565,
1731,
1578,
883,
6433,
264,
3245,
2375,
31,
203,
565,
1731,
1578,
4891,
1768,
2816,
31,
203,
225,
289,
203,
203,
225,
1958,
2177,
758,
1724,
3342,
288,
203,
565,
1758,
628,
31,
203,
565,
1758,
358,
31,
203,
565,
1426,
353,
9906,
31,
203,
565,
2254,
5034,
460,
31,
203,
565,
2254,
5034,
312,
474,
31,
203,
565,
2254,
1105,
16189,
3039,
31,
203,
565,
1731,
501,
31,
203,
565,
1731,
1578,
328,
21,
1768,
2310,
31,
203,
565,
2254,
5034,
613,
1016,
31,
203,
225,
289,
203,
203,
225,
1958,
3423,
9446,
287,
3342,
288,
203,
565,
2254,
5034,
7448,
31,
203,
565,
1758,
5793,
31,
203,
565,
1758,
1018,
31,
203,
565,
2254,
5034,
460,
31,
203,
565,
2254,
5034,
16189,
3039,
31,
203,
565,
1731,
501,
31,
203,
225,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: Unlicense
pragma solidity >=0.8.12;
/// @notice Gas optimized reentrancy protection for smart contracts.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/ReentrancyGuard.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
uint256 private locked = 1;
modifier nonReentrant() {
require(locked == 1, "REENTRANCY");
locked = 2;
_;
locked = 1;
}
} /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(
address indexed owner,
address indexed spender,
uint256 amount
);
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
uint8 public immutable decimals;
/*///////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
/*///////////////////////////////////////////////////////////////
EIP-2612 STORAGE
//////////////////////////////////////////////////////////////*/
bytes32 public constant PERMIT_TYPEHASH =
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
);
uint256 internal immutable INITIAL_CHAIN_ID;
bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/*///////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 amount)
public
virtual
returns (bool)
{
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount)
public
virtual
returns (bool)
{
balanceOf[msg.sender] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max)
allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
return true;
}
/*///////////////////////////////////////////////////////////////
EIP-2612 LOGIC
//////////////////////////////////////////////////////////////*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing
// the owner's nonce which cannot realistically overflow.
unchecked {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(
recoveredAddress != address(0) && recoveredAddress == owner,
"INVALID_SIGNER"
);
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
return
block.chainid == INITIAL_CHAIN_ID
? INITIAL_DOMAIN_SEPARATOR
: computeDomainSeparator();
}
function computeDomainSeparator() internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*///////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal virtual {
balanceOf[from] -= amount;
// Cannot underflow because a user's balance
// will never be larger than the total supply.
unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
} // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
/**
* @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);
}
} /// @title Interface for verifying contract-based account signatures
/// @notice Interface that verifies provided signature for the data
/// @dev Interface defined by EIP-1271
interface IERC1271 {
/// @notice Returns whether the provided signature is valid for the provided data
/// @dev MUST return the bytes4 magic value 0x1626ba7e when function passes.
/// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5).
/// MUST allow external calls.
/// @param hash Hash of the data to be signed
/// @param signature Signature byte array associated with _data
/// @return magicValue The bytes4 magic value 0x1626ba7e
function isValidSignature(bytes32 hash, bytes memory signature)
external
view
returns (bytes4 magicValue);
}
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
library Signature {
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (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.
require(
uint256(s) <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"ODYSSEY: INVALID_SIGNATURE_S_VALUE"
);
require(v == 27 || v == 28, "ODYSSEY: INVALID_SIGNATURE_V_VALUE");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ODYSSEY: INVALID_SIGNATURE");
return signer;
}
function verify(
bytes32 hash,
address signer,
uint8 v,
bytes32 r,
bytes32 s,
bytes32 domainSeparator
) internal view {
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", domainSeparator, hash)
);
if (Address.isContract(signer)) {
require(
IERC1271(signer).isValidSignature(
digest,
abi.encodePacked(r, s, v)
) == 0x1626ba7e,
"ODYSSEY: UNAUTHORIZED"
);
} else {
require(
recover(digest, v, r, s) == signer,
"ODYSSEY: UNAUTHORIZED"
);
}
}
} // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the merkle tree could be reinterpreted as a leaf value.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf)
internal
pure
returns (bytes32)
{
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b)
private
pure
returns (bytes32 value)
{
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
library MerkleWhiteList {
function verify(
address sender,
bytes32[] calldata merkleProof,
bytes32 merkleRoot
) internal pure {
// Verify whitelist
require(address(0) != sender);
bytes32 leaf = keccak256(abi.encodePacked(sender));
require(
MerkleProof.verify(merkleProof, merkleRoot, leaf),
"Not whitelisted"
);
}
} /// @notice Modern, minimalist, and gas efficient ERC-721 implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol)
/// @dev Note that balanceOf does not revert if passed the zero address, in defiance of the ERC.
abstract contract ERC721 {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed id
);
event Approval(
address indexed owner,
address indexed spender,
uint256 indexed id
);
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/*///////////////////////////////////////////////////////////////
METADATA STORAGE/LOGIC
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
function tokenURI(uint256 id) public view virtual returns (string memory);
/*///////////////////////////////////////////////////////////////
ERC721 STORAGE
//////////////////////////////////////////////////////////////*/
mapping(address => uint256) public balanceOf;
mapping(uint256 => address) public ownerOf;
mapping(uint256 => address) public getApproved;
mapping(address => mapping(address => bool)) public isApprovedForAll;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(string memory _name, string memory _symbol) {
name = _name;
symbol = _symbol;
}
/*///////////////////////////////////////////////////////////////
ERC721 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 id) public virtual {
address owner = ownerOf[id];
require(
msg.sender == owner || isApprovedForAll[owner][msg.sender],
"NOT_AUTHORIZED"
);
getApproved[id] = spender;
emit Approval(owner, spender, id);
}
function setApprovalForAll(address operator, bool approved) public virtual {
isApprovedForAll[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function transferFrom(
address from,
address to,
uint256 id
) public virtual {
require(from == ownerOf[id], "WRONG_FROM");
require(to != address(0), "INVALID_RECIPIENT");
require(
msg.sender == from ||
msg.sender == getApproved[id] ||
isApprovedForAll[from][msg.sender],
"NOT_AUTHORIZED"
);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
unchecked {
balanceOf[from]--;
balanceOf[to]++;
}
ownerOf[id] = to;
delete getApproved[id];
emit Transfer(from, to, id);
}
function safeTransferFrom(
address from,
address to,
uint256 id
) public virtual {
transferFrom(from, to, id);
require(
to.code.length == 0 ||
ERC721TokenReceiver(to).onERC721Received(
msg.sender,
from,
id,
""
) ==
ERC721TokenReceiver.onERC721Received.selector,
"UNSAFE_RECIPIENT"
);
}
function safeTransferFrom(
address from,
address to,
uint256 id,
bytes memory data
) public virtual {
transferFrom(from, to, id);
require(
to.code.length == 0 ||
ERC721TokenReceiver(to).onERC721Received(
msg.sender,
from,
id,
data
) ==
ERC721TokenReceiver.onERC721Received.selector,
"UNSAFE_RECIPIENT"
);
}
/*///////////////////////////////////////////////////////////////
ERC165 LOGIC
//////////////////////////////////////////////////////////////*/
function supportsInterface(bytes4 interfaceId)
public
pure
virtual
returns (bool)
{
return
interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165
interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721
interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata
}
/*///////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 id) internal virtual {
require(to != address(0), "INVALID_RECIPIENT");
require(ownerOf[id] == address(0), "ALREADY_MINTED");
// Counter overflow is incredibly unrealistic.
unchecked {
balanceOf[to]++;
}
ownerOf[id] = to;
emit Transfer(address(0), to, id);
}
function _burn(uint256 id) internal virtual {
address owner = ownerOf[id];
require(ownerOf[id] != address(0), "NOT_MINTED");
// Ownership check above ensures no underflow.
unchecked {
balanceOf[owner]--;
}
delete ownerOf[id];
delete getApproved[id];
emit Transfer(owner, address(0), id);
}
/*///////////////////////////////////////////////////////////////
INTERNAL SAFE MINT LOGIC
//////////////////////////////////////////////////////////////*/
function _safeMint(address to, uint256 id) internal virtual {
_mint(to, id);
require(
to.code.length == 0 ||
ERC721TokenReceiver(to).onERC721Received(
msg.sender,
address(0),
id,
""
) ==
ERC721TokenReceiver.onERC721Received.selector,
"UNSAFE_RECIPIENT"
);
}
function _safeMint(
address to,
uint256 id,
bytes memory data
) internal virtual {
_mint(to, id);
require(
to.code.length == 0 ||
ERC721TokenReceiver(to).onERC721Received(
msg.sender,
address(0),
id,
data
) ==
ERC721TokenReceiver.onERC721Received.selector,
"UNSAFE_RECIPIENT"
);
}
}
/// @notice A generic interface for a contract which properly accepts ERC721 tokens.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol)
interface ERC721TokenReceiver {
function onERC721Received(
address operator,
address from,
uint256 id,
bytes calldata data
) external returns (bytes4);
}
library UInt2Str {
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;
while (_i != 0) {
k = k - 1;
uint8 temp = (48 + uint8(_i - (_i / 10) * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
}
contract OdysseyERC721 is ERC721("", "") {
using UInt2Str for uint256;
/*///////////////////////////////////////////////////////////////
CUSTOM ERRORS
//////////////////////////////////////////////////////////////*/
error OdysseyERC721_AlreadyInit();
error OdysseyERC721_Unauthorized();
error OdysseyERC721_BadAddress();
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
address launcher;
address public owner;
bool initialized;
string public baseURI;
uint256 public royaltyFeeInBips; // 1% = 100
address public royaltyReceiver;
string public contractURI;
/*///////////////////////////////////////////////////////////////
METADATA LOGIC
//////////////////////////////////////////////////////////////*/
function tokenURI(uint256 id)
public
view
virtual
override
returns (string memory)
{
return string(abi.encodePacked(baseURI, id.uint2str()));
}
/*///////////////////////////////////////////////////////////////
FACTORY LOGIC
//////////////////////////////////////////////////////////////*/
function initialize(
address _launcher,
address _owner,
string calldata _name,
string calldata _symbol,
string calldata _baseURI
) external {
if (initialized) {
revert OdysseyERC721_AlreadyInit();
}
initialized = true;
launcher = _launcher;
owner = _owner;
name = _name;
symbol = _symbol;
baseURI = _baseURI;
}
/*///////////////////////////////////////////////////////////////
ERC721 LOGIC
//////////////////////////////////////////////////////////////*/
function transferOwnership(address newOwner) public virtual {
if (newOwner == address(0)) {
revert OdysseyERC721_BadAddress();
}
if (msg.sender != owner) {
revert OdysseyERC721_Unauthorized();
}
owner = newOwner;
}
function mint(address user, uint256 id) external {
if (msg.sender != launcher) {
revert OdysseyERC721_Unauthorized();
}
_mint(user, id);
}
/*///////////////////////////////////////////////////////////////
EIP2981 LOGIC
//////////////////////////////////////////////////////////////*/
function royaltyInfo(uint256, uint256 _salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
return (royaltyReceiver, (_salePrice / 10000) * royaltyFeeInBips);
}
function setRoyaltyInfo(address _royaltyReceiver, uint256 _royaltyFeeInBips)
external
{
if (_royaltyReceiver == address(0)) {
revert OdysseyERC721_BadAddress();
}
if (msg.sender != owner) {
revert OdysseyERC721_Unauthorized();
}
royaltyReceiver = _royaltyReceiver;
royaltyFeeInBips = _royaltyFeeInBips;
}
function setContractURI(string memory _uri) public {
if (msg.sender != owner) {
revert OdysseyERC721_Unauthorized();
}
contractURI = _uri;
}
/*///////////////////////////////////////////////////////////////
ERC165 LOGIC
//////////////////////////////////////////////////////////////*/
function supportsInterface(bytes4 interfaceID)
public
pure
override(ERC721)
returns (bool)
{
return
bytes4(keccak256("royaltyInfo(uint256,uint256)")) == interfaceID ||
super.supportsInterface(interfaceID);
}
} /// @notice Minimalist and gas efficient standard ERC1155 implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC1155.sol)
abstract contract ERC1155 {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 amount
);
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] amounts
);
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
event URI(string value, uint256 indexed id);
/*///////////////////////////////////////////////////////////////
ERC1155 STORAGE
//////////////////////////////////////////////////////////////*/
mapping(address => mapping(uint256 => uint256)) public balanceOf;
mapping(address => mapping(address => bool)) public isApprovedForAll;
/*///////////////////////////////////////////////////////////////
METADATA LOGIC
//////////////////////////////////////////////////////////////*/
function uri(uint256 id) public view virtual returns (string memory);
/*///////////////////////////////////////////////////////////////
ERC1155 LOGIC
//////////////////////////////////////////////////////////////*/
function setApprovalForAll(address operator, bool approved) public virtual {
isApprovedForAll[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual {
require(
msg.sender == from || isApprovedForAll[from][msg.sender],
"NOT_AUTHORIZED"
);
balanceOf[from][id] -= amount;
balanceOf[to][id] += amount;
emit TransferSingle(msg.sender, from, to, id, amount);
require(
to.code.length == 0
? to != address(0)
: ERC1155TokenReceiver(to).onERC1155Received(
msg.sender,
from,
id,
amount,
data
) == ERC1155TokenReceiver.onERC1155Received.selector,
"UNSAFE_RECIPIENT"
);
}
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual {
uint256 idsLength = ids.length; // Saves MLOADs.
require(idsLength == amounts.length, "LENGTH_MISMATCH");
require(
msg.sender == from || isApprovedForAll[from][msg.sender],
"NOT_AUTHORIZED"
);
for (uint256 i = 0; i < idsLength; ) {
uint256 id = ids[i];
uint256 amount = amounts[i];
balanceOf[from][id] -= amount;
balanceOf[to][id] += amount;
// An array can't have a total length
// larger than the max uint256 value.
unchecked {
i++;
}
}
emit TransferBatch(msg.sender, from, to, ids, amounts);
require(
to.code.length == 0
? to != address(0)
: ERC1155TokenReceiver(to).onERC1155BatchReceived(
msg.sender,
from,
ids,
amounts,
data
) == ERC1155TokenReceiver.onERC1155BatchReceived.selector,
"UNSAFE_RECIPIENT"
);
}
function balanceOfBatch(address[] memory owners, uint256[] memory ids)
public
view
virtual
returns (uint256[] memory balances)
{
uint256 ownersLength = owners.length; // Saves MLOADs.
require(ownersLength == ids.length, "LENGTH_MISMATCH");
balances = new uint256[](owners.length);
// Unchecked because the only math done is incrementing
// the array index counter which cannot possibly overflow.
unchecked {
for (uint256 i = 0; i < ownersLength; i++) {
balances[i] = balanceOf[owners[i]][ids[i]];
}
}
}
/*///////////////////////////////////////////////////////////////
ERC165 LOGIC
//////////////////////////////////////////////////////////////*/
function supportsInterface(bytes4 interfaceId)
public
pure
virtual
returns (bool)
{
return
interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165
interfaceId == 0xd9b67a26 || // ERC165 Interface ID for ERC1155
interfaceId == 0x0e89341c; // ERC165 Interface ID for ERC1155MetadataURI
}
/*///////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal {
balanceOf[to][id] += amount;
emit TransferSingle(msg.sender, address(0), to, id, amount);
require(
to.code.length == 0
? to != address(0)
: ERC1155TokenReceiver(to).onERC1155Received(
msg.sender,
address(0),
id,
amount,
data
) == ERC1155TokenReceiver.onERC1155Received.selector,
"UNSAFE_RECIPIENT"
);
}
function _batchMint(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal {
uint256 idsLength = ids.length; // Saves MLOADs.
require(idsLength == amounts.length, "LENGTH_MISMATCH");
for (uint256 i = 0; i < idsLength; ) {
balanceOf[to][ids[i]] += amounts[i];
// An array can't have a total length
// larger than the max uint256 value.
unchecked {
i++;
}
}
emit TransferBatch(msg.sender, address(0), to, ids, amounts);
require(
to.code.length == 0
? to != address(0)
: ERC1155TokenReceiver(to).onERC1155BatchReceived(
msg.sender,
address(0),
ids,
amounts,
data
) == ERC1155TokenReceiver.onERC1155BatchReceived.selector,
"UNSAFE_RECIPIENT"
);
}
function _batchBurn(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal {
uint256 idsLength = ids.length; // Saves MLOADs.
require(idsLength == amounts.length, "LENGTH_MISMATCH");
for (uint256 i = 0; i < idsLength; ) {
balanceOf[from][ids[i]] -= amounts[i];
// An array can't have a total length
// larger than the max uint256 value.
unchecked {
i++;
}
}
emit TransferBatch(msg.sender, from, address(0), ids, amounts);
}
function _burn(
address from,
uint256 id,
uint256 amount
) internal {
balanceOf[from][id] -= amount;
emit TransferSingle(msg.sender, from, address(0), id, amount);
}
}
/// @notice A generic interface for a contract which properly accepts ERC1155 tokens.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC1155.sol)
interface ERC1155TokenReceiver {
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 amount,
bytes calldata data
) external returns (bytes4);
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external returns (bytes4);
}
contract OdysseyERC1155 is ERC1155 {
using UInt2Str for uint256;
/*///////////////////////////////////////////////////////////////
CUSTOM ERRORS
//////////////////////////////////////////////////////////////*/
error OdysseyERC1155_AlreadyInit();
error OdysseyERC1155_Unauthorized();
error OdysseyERC1155_BadAddress();
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
address launcher;
address public owner;
string public name;
string public symbol;
string public baseURI;
bool initialized;
uint256 public royaltyFeeInBips; // 1% = 100
address public royaltyReceiver;
string public contractURI;
/*///////////////////////////////////////////////////////////////
METADATA LOGIC
//////////////////////////////////////////////////////////////*/
function uri(uint256 id)
public
view
virtual
override
returns (string memory)
{
return string(abi.encodePacked(baseURI, id.uint2str()));
}
/*///////////////////////////////////////////////////////////////
FACTORY LOGIC
//////////////////////////////////////////////////////////////*/
function initialize(
address _launcher,
address _owner,
string calldata _name,
string calldata _symbol,
string calldata _baseURI
) external {
if (isInit()) {
revert OdysseyERC1155_AlreadyInit();
}
initialized = true;
launcher = _launcher;
owner = _owner;
name = _name;
symbol = _symbol;
baseURI = _baseURI;
}
function isInit() internal view returns (bool) {
return initialized;
}
/*///////////////////////////////////////////////////////////////
ERC1155 LOGIC
//////////////////////////////////////////////////////////////*/
function transferOwnership(address newOwner) public virtual {
if (newOwner == address(0)) {
revert OdysseyERC1155_BadAddress();
}
if (msg.sender != owner) {
revert OdysseyERC1155_Unauthorized();
}
owner = newOwner;
}
function mint(address user, uint256 id) external {
if (msg.sender != launcher) {
revert OdysseyERC1155_Unauthorized();
}
_mint(user, id, 1, "");
}
function mintBatch(
address user,
uint256 id,
uint256 amount
) external {
if (msg.sender != launcher) {
revert OdysseyERC1155_Unauthorized();
}
_mint(user, id, amount, "");
}
/*///////////////////////////////////////////////////////////////
EIP2981 LOGIC
//////////////////////////////////////////////////////////////*/
function royaltyInfo(uint256, uint256 _salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
return (royaltyReceiver, (_salePrice / 10000) * royaltyFeeInBips);
}
function setRoyaltyInfo(address _royaltyReceiver, uint256 _royaltyFeeInBips)
external
{
if (_royaltyReceiver == address(0)) {
revert OdysseyERC1155_BadAddress();
}
if (msg.sender != owner) {
revert OdysseyERC1155_Unauthorized();
}
royaltyReceiver = _royaltyReceiver;
royaltyFeeInBips = _royaltyFeeInBips;
}
function setContractURI(string memory _uri) public {
if (msg.sender != owner) {
revert OdysseyERC1155_Unauthorized();
}
contractURI = _uri;
}
/*///////////////////////////////////////////////////////////////
ERC165 LOGIC
//////////////////////////////////////////////////////////////*/
function supportsInterface(bytes4 interfaceID)
public
pure
override(ERC1155)
returns (bool)
{
return
bytes4(keccak256("royaltyInfo(uint256,uint256)")) == interfaceID ||
super.supportsInterface(interfaceID);
}
}
contract OdysseyTokenFactory {
/*///////////////////////////////////////////////////////////////
CUSTOM ERRORS
//////////////////////////////////////////////////////////////*/
error OdysseyTokenFactory_TokenAlreadyExists();
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event TokenCreated(
string indexed name,
string indexed symbol,
address addr,
bool isERC721,
uint256 length
);
/*///////////////////////////////////////////////////////////////
FACTORY STORAGE
//////////////////////////////////////////////////////////////*/
mapping(string => mapping(string => address)) public getToken;
mapping(address => uint256) public tokenExists;
address[] public allTokens;
/*///////////////////////////////////////////////////////////////
FACTORY LOGIC
//////////////////////////////////////////////////////////////*/
function allTokensLength() external view returns (uint256) {
return allTokens.length;
}
function create1155(
address owner,
string calldata name,
string calldata symbol,
string calldata baseURI
) external returns (address token) {
if (getToken[name][symbol] != address(0)) {
revert OdysseyTokenFactory_TokenAlreadyExists();
}
bytes memory bytecode = type(OdysseyERC1155).creationCode;
bytes32 salt = keccak256(abi.encodePacked(name, symbol));
assembly {
token := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
getToken[name][symbol] = token;
tokenExists[token] = 1;
// Run the proper initialize function
OdysseyERC1155(token).initialize(
msg.sender,
owner,
name,
symbol,
string(
abi.encodePacked(
baseURI,
Strings.toString(block.chainid),
"/",
Strings.toHexString(uint160(token)),
"/"
)
)
);
emit TokenCreated(name, symbol, token, false, allTokens.length);
return token;
}
function create721(
address owner,
string calldata name,
string calldata symbol,
string calldata baseURI
) external returns (address token) {
if (getToken[name][symbol] != address(0)) {
revert OdysseyTokenFactory_TokenAlreadyExists();
}
bytes memory bytecode = type(OdysseyERC721).creationCode;
bytes32 salt = keccak256(abi.encodePacked(name, symbol));
assembly {
token := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
getToken[name][symbol] = token;
tokenExists[token] = 1;
// Run the proper initialize function
OdysseyERC721(token).initialize(
msg.sender,
owner,
name,
symbol,
string(
abi.encodePacked(
baseURI,
Strings.toString(block.chainid),
"/",
Strings.toHexString(uint160(token)),
"/"
)
)
);
emit TokenCreated(name, symbol, token, true, allTokens.length);
}
}
library OdysseyLib {
struct Odyssey1155Info {
uint256[] maxSupply;
uint256[] tokenIds;
uint256[] reserveAmounts;
}
struct BatchMint {
bytes32[][] merkleProof;
bytes32[] merkleRoot;
uint256[] minPrice;
uint256[] mintsPerUser;
uint256[] tokenId;
address[] tokenAddress;
address[] currency;
uint8[] v;
bytes32[] r;
bytes32[] s;
}
struct Percentage {
uint256 numerator;
uint256 denominator;
}
function compareDefaultPercentage(OdysseyLib.Percentage calldata percent)
internal
pure
returns (bool result)
{
if (percent.numerator > percent.denominator) {
// Can't have a percent greater than 100
return false;
}
if (percent.numerator == 0 || percent.denominator == 0) {
// Can't use 0 in percentage
return false;
}
//Check cross multiplication of 3/100
uint256 crossMultiple1 = percent.numerator * 100;
uint256 crossMultiple2 = percent.denominator * 3;
if (crossMultiple1 < crossMultiple2) {
return false;
}
return true;
}
}
abstract contract OdysseyDatabase {
// Custom Errors
error OdysseyLaunchPlatform_TokenDoesNotExist();
error OdysseyLaunchPlatform_AlreadyClaimed();
error OdysseyLaunchPlatform_MaxSupplyCap();
error OdysseyLaunchPlatform_InsufficientFunds();
error OdysseyLaunchPlatform_TreasuryPayFailure();
error OdysseyLaunchPlatform_FailedToPayEther();
error OdysseyLaunchPlatform_FailedToPayERC20();
error OdysseyLaunchPlatform_ReservedOrClaimedMax();
// Constants
// keccak256("whitelistMint721(bytes32 merkleRoot,uint256 minPrice,uint256 mintsPerUser,address tokenAddress,address currency)").toString('hex')
bytes32 public constant MERKLE_TREE_ROOT_ERC721_TYPEHASH =
0xf0f6f256599682b9387f45fc268ed696625f835d98d64b8967134239e103fc6c;
// keccak256("whitelistMint1155(bytes32 merkleRoot,uint256 minPrice,uint256 mintsPerUser,uint256 tokenId,address tokenAddress,address currency)").toString('hex')
bytes32 public constant MERKLE_TREE_ROOT_ERC1155_TYPEHASH =
0x0a52f6e0133eadd055cc5703844e676242c3b461d85fb7ce7f74becd7e40edd1;
// Def understand this before writing code:
// https://docs.soliditylang.org/en/v0.8.12/internals/layout_in_storage.html
//--------------------------------------------------------------------------------//
// Slot | Type | Description //
//--------------------------------------------------------------------------------//
// 0x00 | address | OdysseyLaunchPlatform.sol //
// 0x01 | address | OdysseyFactory.sol //
// 0x02 | address | Treasury Multisig //
// 0x03 | address | Admin Address //
// 0x04 | address | OdysseyXp.sol //
//--------------------------------------------------------------------------------//
// Slot storage
address launchPlatform; // slot 0
address factory; // slot 1
address treasury; // slot 2
address admin; //slot 3
address xp; //slot 4
// Common Storage
mapping(address => bytes32) public domainSeparator;
mapping(address => uint256) public whitelistActive;
mapping(address => address) public ownerOf;
mapping(address => address) public royaltyRecipient;
mapping(address => OdysseyLib.Percentage) public treasuryCommission;
mapping(address => uint256) public ohmFamilyCurrencies;
// ERC721 Storage
mapping(address => mapping(address => uint256)) public whitelistClaimed721;
mapping(address => mapping(address => uint256)) public isReserved721;
mapping(address => uint256) public cumulativeSupply721;
mapping(address => uint256) public mintedSupply721;
mapping(address => uint256) public maxSupply721;
// ERC1155 Storage
mapping(address => mapping(address => mapping(uint256 => uint256)))
public whitelistClaimed1155;
mapping(address => mapping(address => mapping(uint256 => uint256)))
public isReserved1155;
mapping(address => mapping(uint256 => uint256)) public cumulativeSupply1155;
mapping(address => mapping(uint256 => uint256)) public maxSupply1155;
function readSlotAsAddress(uint256 slot)
public
view
returns (address data)
{
assembly {
data := sload(slot)
}
}
} /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
library SafeTransferLib {
/*///////////////////////////////////////////////////////////////
ETH OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferETH(address to, uint256 amount) internal {
bool callStatus;
assembly {
// Transfer the ETH and store if it succeeded or not.
callStatus := call(gas(), to, amount, 0, 0, 0, 0)
}
require(callStatus, "ETH_TRANSFER_FAILED");
}
/*///////////////////////////////////////////////////////////////
ERC20 OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 amount
) internal {
bool callStatus;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata to memory piece by piece:
mstore(
freeMemoryPointer,
0x23b872dd00000000000000000000000000000000000000000000000000000000
) // Begin with the function selector.
mstore(
add(freeMemoryPointer, 4),
and(from, 0xffffffffffffffffffffffffffffffffffffffff)
) // Mask and append the "from" argument.
mstore(
add(freeMemoryPointer, 36),
and(to, 0xffffffffffffffffffffffffffffffffffffffff)
) // Mask and append the "to" argument.
mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
// Call the token and store if it succeeded or not.
// We use 100 because the calldata length is 4 + 32 * 3.
callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)
}
require(
didLastOptionalReturnCallSucceed(callStatus),
"TRANSFER_FROM_FAILED"
);
}
function safeTransfer(
ERC20 token,
address to,
uint256 amount
) internal {
bool callStatus;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata to memory piece by piece:
mstore(
freeMemoryPointer,
0xa9059cbb00000000000000000000000000000000000000000000000000000000
) // Begin with the function selector.
mstore(
add(freeMemoryPointer, 4),
and(to, 0xffffffffffffffffffffffffffffffffffffffff)
) // Mask and append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
// Call the token and store if it succeeded or not.
// We use 68 because the calldata length is 4 + 32 * 2.
callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
}
require(
didLastOptionalReturnCallSucceed(callStatus),
"TRANSFER_FAILED"
);
}
function safeApprove(
ERC20 token,
address to,
uint256 amount
) internal {
bool callStatus;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata to memory piece by piece:
mstore(
freeMemoryPointer,
0x095ea7b300000000000000000000000000000000000000000000000000000000
) // Begin with the function selector.
mstore(
add(freeMemoryPointer, 4),
and(to, 0xffffffffffffffffffffffffffffffffffffffff)
) // Mask and append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
// Call the token and store if it succeeded or not.
// We use 68 because the calldata length is 4 + 32 * 2.
callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
}
require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED");
}
/*///////////////////////////////////////////////////////////////
INTERNAL HELPER LOGIC
//////////////////////////////////////////////////////////////*/
function didLastOptionalReturnCallSucceed(bool callStatus)
private
pure
returns (bool success)
{
assembly {
// Get how many bytes the call returned.
let returnDataSize := returndatasize()
// If the call reverted:
if iszero(callStatus) {
// Copy the revert message into memory.
returndatacopy(0, 0, returnDataSize)
// Revert with the same message.
revert(0, returnDataSize)
}
switch returnDataSize
case 32 {
// Copy the return data into memory.
returndatacopy(0, 0, returnDataSize)
// Set success to whether it returned true.
success := iszero(iszero(mload(0)))
}
case 0 {
// There was no return data.
success := 1
}
default {
// It returned some malformed input.
success := 0
}
}
}
} /// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
library FixedPointMathLib {
/*//////////////////////////////////////////////////////////////
SIMPLIFIED FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.
function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
}
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
}
function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
}
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
}
/*//////////////////////////////////////////////////////////////
LOW LEVEL FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
function mulDivDown(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
if iszero(
and(
iszero(iszero(denominator)),
or(iszero(x), eq(div(z, x), y))
)
) {
revert(0, 0)
}
// Divide z by the denominator.
z := div(z, denominator)
}
}
function mulDivUp(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
if iszero(
and(
iszero(iszero(denominator)),
or(iszero(x), eq(div(z, x), y))
)
) {
revert(0, 0)
}
// First, divide z - 1 by the denominator and add 1.
// We allow z - 1 to underflow if z is 0, because we multiply the
// end result by 0 if z is zero, ensuring we return 0 if z is zero.
z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1))
}
}
function rpow(
uint256 x,
uint256 n,
uint256 scalar
) internal pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 {
// 0 ** 0 = 1
z := scalar
}
default {
// 0 ** n = 0
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
// If n is even, store scalar in z for now.
z := scalar
}
default {
// If n is odd, store x in z for now.
z := x
}
// Shifting right by 1 is like dividing by 2.
let half := shr(1, scalar)
for {
// Shift n right by 1 before looping to halve it.
n := shr(1, n)
} n {
// Shift n right by 1 each iteration to halve it.
n := shr(1, n)
} {
// Revert immediately if x ** 2 would overflow.
// Equivalent to iszero(eq(div(xx, x), x)) here.
if shr(128, x) {
revert(0, 0)
}
// Store x squared.
let xx := mul(x, x)
// Round to the nearest number.
let xxRound := add(xx, half)
// Revert if xx + half overflowed.
if lt(xxRound, xx) {
revert(0, 0)
}
// Set x to scaled xxRound.
x := div(xxRound, scalar)
// If n is even:
if mod(n, 2) {
// Compute z * x.
let zx := mul(z, x)
// If z * x overflowed:
if iszero(eq(div(zx, x), z)) {
// Revert if x is non-zero.
if iszero(iszero(x)) {
revert(0, 0)
}
}
// Round to the nearest number.
let zxRound := add(zx, half)
// Revert if zx + half overflowed.
if lt(zxRound, zx) {
revert(0, 0)
}
// Return properly scaled zxRound.
z := div(zxRound, scalar)
}
}
}
}
}
/*//////////////////////////////////////////////////////////////
GENERAL NUMBER UTILITIES
//////////////////////////////////////////////////////////////*/
function sqrt(uint256 x) internal pure returns (uint256 z) {
assembly {
// Start off with z at 1.
z := 1
// Used below to help find a nearby power of 2.
let y := x
// Find the lowest power of 2 that is at least sqrt(x).
if iszero(lt(y, 0x100000000000000000000000000000000)) {
y := shr(128, y) // Like dividing by 2 ** 128.
z := shl(64, z) // Like multiplying by 2 ** 64.
}
if iszero(lt(y, 0x10000000000000000)) {
y := shr(64, y) // Like dividing by 2 ** 64.
z := shl(32, z) // Like multiplying by 2 ** 32.
}
if iszero(lt(y, 0x100000000)) {
y := shr(32, y) // Like dividing by 2 ** 32.
z := shl(16, z) // Like multiplying by 2 ** 16.
}
if iszero(lt(y, 0x10000)) {
y := shr(16, y) // Like dividing by 2 ** 16.
z := shl(8, z) // Like multiplying by 2 ** 8.
}
if iszero(lt(y, 0x100)) {
y := shr(8, y) // Like dividing by 2 ** 8.
z := shl(4, z) // Like multiplying by 2 ** 4.
}
if iszero(lt(y, 0x10)) {
y := shr(4, y) // Like dividing by 2 ** 4.
z := shl(2, z) // Like multiplying by 2 ** 2.
}
if iszero(lt(y, 0x8)) {
// Equivalent to 2 ** z.
z := shl(1, z)
}
// Shifting right by 1 is like dividing by 2.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// Compute a rounded down version of z.
let zRoundDown := div(x, z)
// If zRoundDown is smaller, use it.
if lt(zRoundDown, z) {
z := zRoundDown
}
}
}
} // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165Checker.sol)
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
/**
* @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 Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return
_supportsERC165Interface(account, type(IERC165).interfaceId) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId)
internal
view
returns (bool)
{
// query support of both ERC165 as per the spec and support of _interfaceId
return
supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(
address account,
bytes4[] memory interfaceIds
) internal view returns (bool[] memory) {
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(
account,
interfaceIds[i]
);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(
address account,
bytes4[] memory interfaceIds
) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId)
private
view
returns (bool)
{
bytes memory encodedParams = abi.encodeWithSelector(
IERC165.supportsInterface.selector,
interfaceId
);
(bool success, bytes memory result) = account.staticcall{gas: 30000}(
encodedParams
);
if (result.length < 32) return false;
return success && abi.decode(result, (bool));
}
}
struct Rewards {
uint256 sale;
uint256 purchase;
uint256 mint;
uint256 ohmPurchase;
uint256 ohmMint;
uint256 multiplier;
}
struct NFT {
address contractAddress;
uint256 id;
}
enum NftType {
ERC721,
ERC1155
}
error OdysseyXpDirectory_Unauthorized();
contract OdysseyXpDirectory {
using ERC165Checker for address;
Rewards public defaultRewards;
mapping(address => Rewards) public erc721rewards;
mapping(address => mapping(uint256 => Rewards)) public erc1155rewards;
NFT[] public customRewardTokens;
address public owner;
constructor() {
owner = msg.sender;
}
// modifier substitute
function notOwner() internal view returns (bool) {
return msg.sender != owner;
}
function transferOwnership(address newOwner) external {
if (notOwner()) revert OdysseyXpDirectory_Unauthorized();
owner = newOwner;
}
/*///////////////////////////////////////////////////////////////
Reward Setters
//////////////////////////////////////////////////////////////*/
/// @notice Set default rewards for contracts without a custom reward set
/// @param sale XP reward for selling an NFT
/// @param purchase XP reward for purchasing an NFT
/// @param mint XP reward for minting an NFT
/// @param ohmPurchase XP reward for purchasing an NFT with OHM
/// @param ohmMint XP reward for minting an NFT with OHM
/// @param multiplier XP reward multiplier for wallets holding an NFT
function setDefaultRewards(
uint256 sale,
uint256 purchase,
uint256 mint,
uint256 ohmPurchase,
uint256 ohmMint,
uint256 multiplier
) public {
if (notOwner()) revert OdysseyXpDirectory_Unauthorized();
defaultRewards = Rewards(
sale,
purchase,
mint,
ohmPurchase,
ohmMint,
multiplier
);
}
/// @notice Set custom rewards for an ERC721 contract
/// @param sale XP reward for selling this NFT
/// @param purchase XP reward for purchasing this NFT
/// @param mint XP reward for minting this NFT
/// @param ohmPurchase XP reward for purchasing this NFT with OHM
/// @param ohmMint XP reward for minting this NFT with OHM
/// @param multiplier XP reward multiplier for wallets holding this NFT
function setErc721CustomRewards(
address tokenAddress,
uint256 sale,
uint256 purchase,
uint256 mint,
uint256 ohmPurchase,
uint256 ohmMint,
uint256 multiplier
) public {
if (notOwner()) revert OdysseyXpDirectory_Unauthorized();
customRewardTokens.push(NFT(tokenAddress, 0));
erc721rewards[tokenAddress] = Rewards(
sale,
purchase,
mint,
ohmPurchase,
ohmMint,
multiplier
);
}
/// @notice Set custom rewards for an ERC1155 contract and token ID
/// @param sale XP reward for selling this NFT
/// @param purchase XP reward for purchasing this NFT
/// @param mint XP reward for minting this NFT
/// @param ohmPurchase XP reward for purchasing this NFT with OHM
/// @param ohmMint XP reward for minting this NFT with OHM
/// @param multiplier XP reward multiplier for wallets holding this NFT
function setErc1155CustomRewards(
address tokenAddress,
uint256 tokenId,
uint256 sale,
uint256 purchase,
uint256 mint,
uint256 ohmPurchase,
uint256 ohmMint,
uint256 multiplier
) public {
if (notOwner()) revert OdysseyXpDirectory_Unauthorized();
customRewardTokens.push(NFT(tokenAddress, tokenId));
erc1155rewards[tokenAddress][tokenId] = Rewards(
sale,
purchase,
mint,
ohmPurchase,
ohmMint,
multiplier
);
}
/*///////////////////////////////////////////////////////////////
Reward Getters
//////////////////////////////////////////////////////////////*/
/// @notice Get the XP reward for selling an NFT
/// @param seller Seller of the NFT
/// @param contractAddress Address of the NFT being sold
/// @param tokenId ID of the NFT being sold
function getSaleReward(
address seller,
address contractAddress,
uint256 tokenId
) public view returns (uint256) {
(
bool isCustomErc721,
bool isCustomErc1155,
uint256 multiplier
) = _getRewardDetails(seller, contractAddress, tokenId);
if (isCustomErc721) {
return erc721rewards[contractAddress].sale * multiplier;
} else if (isCustomErc1155) {
return erc1155rewards[contractAddress][tokenId].sale * multiplier;
} else {
return defaultRewards.sale * multiplier;
}
}
/// @notice Get the XP reward for buying an NFT
/// @param buyer Buyer of the NFT
/// @param contractAddress Address of the NFT being sold
/// @param tokenId ID of the NFT being sold
function getPurchaseReward(
address buyer,
address contractAddress,
uint256 tokenId
) public view returns (uint256) {
(
bool isCustomErc721,
bool isCustomErc1155,
uint256 multiplier
) = _getRewardDetails(buyer, contractAddress, tokenId);
if (isCustomErc721) {
return erc721rewards[contractAddress].purchase * multiplier;
} else if (isCustomErc1155) {
return
erc1155rewards[contractAddress][tokenId].purchase * multiplier;
} else {
return defaultRewards.purchase * multiplier;
}
}
/// @notice Get the XP reward for minting an NFT
/// @param buyer Buyer of the NFT
/// @param contractAddress Address of the NFT being sold
/// @param tokenId ID of the NFT being sold
function getMintReward(
address buyer,
address contractAddress,
uint256 tokenId
) public view returns (uint256) {
(
bool isCustomErc721,
bool isCustomErc1155,
uint256 multiplier
) = _getRewardDetails(buyer, contractAddress, tokenId);
if (isCustomErc721) {
return erc721rewards[contractAddress].mint * multiplier;
} else if (isCustomErc1155) {
return erc1155rewards[contractAddress][tokenId].mint * multiplier;
} else {
return defaultRewards.mint * multiplier;
}
}
/// @notice Get the XP reward for buying an NFT with OHM
/// @param buyer Buyer of the NFT
/// @param contractAddress Address of the NFT being sold
/// @param tokenId ID of the NFT being sold
function getOhmPurchaseReward(
address buyer,
address contractAddress,
uint256 tokenId
) public view returns (uint256) {
(
bool isCustomErc721,
bool isCustomErc1155,
uint256 multiplier
) = _getRewardDetails(buyer, contractAddress, tokenId);
if (isCustomErc721) {
return erc721rewards[contractAddress].ohmPurchase * multiplier;
} else if (isCustomErc1155) {
return
erc1155rewards[contractAddress][tokenId].ohmPurchase *
multiplier;
} else {
return defaultRewards.ohmPurchase * multiplier;
}
}
/// @notice Get the XP reward for minting an NFT with OHM
/// @param buyer Buyer of the NFT
/// @param contractAddress Address of the NFT being sold
/// @param tokenId ID of the NFT being sold
function getOhmMintReward(
address buyer,
address contractAddress,
uint256 tokenId
) public view returns (uint256) {
(
bool isCustomErc721,
bool isCustomErc1155,
uint256 multiplier
) = _getRewardDetails(buyer, contractAddress, tokenId);
if (isCustomErc721) {
return erc721rewards[contractAddress].ohmMint * multiplier;
} else if (isCustomErc1155) {
return
erc1155rewards[contractAddress][tokenId].ohmMint * multiplier;
} else {
return defaultRewards.ohmMint * multiplier;
}
}
/// @notice Determine if an NFT has custom rewards and any multiplier based on the user's held NFTs
/// @dev The multiplier and custom rewards are determined simultaneously to save on gas costs of iteration
/// @param user Wallet address with potential multiplier NFTs
/// @param contractAddress Address of the NFT being sold
/// @param tokenId ID of the NFT being sold
function _getRewardDetails(
address user,
address contractAddress,
uint256 tokenId
)
internal
view
returns (
bool isCustomErc721,
bool isCustomErc1155,
uint256 multiplier
)
{
NFT[] memory _customRewardTokens = customRewardTokens; // save an SLOAD from length reading
for (uint256 i = 0; i < _customRewardTokens.length; i++) {
NFT memory token = _customRewardTokens[i];
if (token.contractAddress.supportsInterface(0x80ac58cd)) {
// is ERC721
if (OdysseyERC721(token.contractAddress).balanceOf(user) > 0) {
uint256 reward = erc721rewards[token.contractAddress]
.multiplier;
multiplier = reward > 1 ? multiplier + reward : multiplier; // only increment if multiplier is non-one
}
if (contractAddress == token.contractAddress) {
isCustomErc721 = true;
}
} else if (token.contractAddress.supportsInterface(0xd9b67a26)) {
// is isERC1155
if (
OdysseyERC1155(token.contractAddress).balanceOf(
user,
token.id
) > 0
) {
uint256 reward = erc1155rewards[token.contractAddress][
token.id
].multiplier;
multiplier = reward > 1 ? multiplier + reward : multiplier; // only increment if multiplier is non-one
if (
contractAddress == token.contractAddress &&
tokenId == token.id
) {
isCustomErc1155 = true;
}
}
}
}
multiplier = multiplier == 0 ? defaultRewards.multiplier : multiplier; // if no custom multiplier, use default
multiplier = multiplier > 4 ? 4 : multiplier; // multiplier caps at 4
}
}
error OdysseyXp_Unauthorized();
error OdysseyXp_NonTransferable();
error OdysseyXp_ZeroAssets();
contract OdysseyXp is ERC20 {
using SafeTransferLib for ERC20;
using FixedPointMathLib for uint256;
struct UserHistory {
uint256 balanceAtLastRedeem;
uint256 globallyWithdrawnAtLastRedeem;
}
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Mint(address indexed owner, uint256 assets, uint256 xp);
event Redeem(address indexed owner, uint256 assets, uint256 xp);
/*///////////////////////////////////////////////////////////////
STATE VARIABLES
//////////////////////////////////////////////////////////////*/
address public router;
address public exchange;
address public owner;
uint256 public globallyWithdrawn;
ERC20 public immutable asset;
OdysseyXpDirectory public directory;
mapping(address => UserHistory) public userHistories;
constructor(
ERC20 _asset,
OdysseyXpDirectory _directory,
address _router,
address _exchange,
address _owner
) ERC20("Odyssey XP", "XP", 0) {
asset = _asset;
directory = _directory;
router = _router;
exchange = _exchange;
owner = _owner;
}
/*///////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////*/
function notOwner() internal view returns (bool) {
return msg.sender != owner;
}
function notRouter() internal view returns (bool) {
return msg.sender != router;
}
function notExchange() internal view returns (bool) {
return msg.sender != exchange;
}
/*///////////////////////////////////////////////////////////////
RESTRICTED SETTERS
//////////////////////////////////////////////////////////////*/
function setExchange(address _exchange) external {
if (notOwner()) revert OdysseyXp_Unauthorized();
exchange = _exchange;
}
function setRouter(address _router) external {
if (notOwner()) revert OdysseyXp_Unauthorized();
router = _router;
}
function setDirectory(address _directory) external {
if (notOwner()) revert OdysseyXp_Unauthorized();
directory = OdysseyXpDirectory(_directory);
}
function transferOwnership(address _newOwner) external {
if (notOwner()) revert OdysseyXp_Unauthorized();
owner = _newOwner;
}
/*///////////////////////////////////////////////////////////////
XP Granting Methods
//////////////////////////////////////////////////////////////*/
function saleReward(
address seller,
address contractAddress,
uint256 tokenId
) external {
if (notExchange()) revert OdysseyXp_Unauthorized();
_grantXP(
seller,
directory.getSaleReward(seller, contractAddress, tokenId)
);
}
function purchaseReward(
address buyer,
address contractAddress,
uint256 tokenId
) external {
if (notExchange()) revert OdysseyXp_Unauthorized();
_grantXP(
buyer,
directory.getPurchaseReward(buyer, contractAddress, tokenId)
);
}
function mintReward(
address buyer,
address contractAddress,
uint256 tokenId
) external {
if (notRouter()) revert OdysseyXp_Unauthorized();
_grantXP(
buyer,
directory.getMintReward(buyer, contractAddress, tokenId)
);
}
function ohmPurchaseReward(
address buyer,
address contractAddress,
uint256 tokenId
) external {
if (notExchange()) revert OdysseyXp_Unauthorized();
_grantXP(
buyer,
directory.getOhmPurchaseReward(buyer, contractAddress, tokenId)
);
}
function ohmMintReward(
address buyer,
address contractAddress,
uint256 tokenId
) external {
if (notRouter()) revert OdysseyXp_Unauthorized();
_grantXP(
buyer,
directory.getOhmMintReward(buyer, contractAddress, tokenId)
);
}
/*///////////////////////////////////////////////////////////////
MINT LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Grants the receiver the given amount of XP
/// @dev Forces the receiver to redeem if they have rewards available
/// @param receiver The address to grant XP to
/// @param xp The amount of XP to grant
function _grantXP(address receiver, uint256 xp)
internal
returns (uint256 assets)
{
uint256 currentXp = balanceOf[receiver];
if ((assets = previewRedeem(receiver, currentXp)) > 0)
_redeem(receiver, assets, currentXp); // force redeeming to keep portions in line
else if (currentXp == 0)
userHistories[receiver]
.globallyWithdrawnAtLastRedeem = globallyWithdrawn; // if a new user, adjust their history to calculate withdrawn at their first redeem
_mint(receiver, xp);
emit Mint(msg.sender, assets, xp);
afterMint(assets, xp);
}
/*///////////////////////////////////////////////////////////////
REDEEM LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice external redeem method
/// @dev will revert if there is nothing to redeem
function redeem() public returns (uint256 assets) {
uint256 xp = balanceOf[msg.sender];
if ((assets = previewRedeem(msg.sender, xp)) == 0)
revert OdysseyXp_ZeroAssets();
_redeem(msg.sender, assets, xp);
}
/// @notice Internal logic for redeeming rewards
/// @param receiver The receiver of rewards
/// @param assets The amount of assets to grant
/// @param xp The amount of XP the user is redeeming with
function _redeem(
address receiver,
uint256 assets,
uint256 xp
) internal virtual {
beforeRedeem(assets, xp);
userHistories[receiver].balanceAtLastRedeem =
asset.balanceOf(address(this)) -
assets;
userHistories[receiver].globallyWithdrawnAtLastRedeem =
globallyWithdrawn +
assets;
globallyWithdrawn += assets;
asset.safeTransfer(receiver, assets);
emit Redeem(receiver, assets, xp);
}
/*///////////////////////////////////////////////////////////////
ACCOUNTING LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Preview the result of a redeem for the given user with the given XP amount
/// @param recipient The user to check potential rewards for
/// @param xp The amount of XP the user is previewing a redeem for
function previewRedeem(address recipient, uint256 xp)
public
view
virtual
returns (uint256)
{
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return
supply == 0 || xp == 0
? 0
: xp.mulDivDown(totalAssets(recipient), supply);
}
/// @notice The total amount of available assets for the user, adjusted based on their history
/// @param user The user to check assets for
function totalAssets(address user) internal view returns (uint256) {
uint256 balance = asset.balanceOf(address(this)); // Saves an extra SLOAD if balance is non-zero.
return
balance +
(globallyWithdrawn -
userHistories[user].globallyWithdrawnAtLastRedeem) -
userHistories[user].balanceAtLastRedeem;
}
/*///////////////////////////////////////////////////////////////
OVERRIDE TRANSFERABILITY
//////////////////////////////////////////////////////////////*/
function transfer(address to, uint256 amount)
public
override
returns (bool)
{
revert OdysseyXp_NonTransferable();
}
function transferFrom(
address from,
address to,
uint256 amount
) public override returns (bool) {
revert OdysseyXp_NonTransferable();
}
/*///////////////////////////////////////////////////////////////
INTERNAL HOOKS LOGIC
//////////////////////////////////////////////////////////////*/
function beforeRedeem(uint256 assets, uint256 xp) internal virtual {}
function afterMint(uint256 assets, uint256 xp) internal virtual {}
}
contract OdysseyLaunchPlatform is OdysseyDatabase, ReentrancyGuard {
/*///////////////////////////////////////////////////////////////
ACTIONS
//////////////////////////////////////////////////////////////*/
function mintERC721(
bytes32[] calldata merkleProof,
bytes32 merkleRoot,
uint256 minPrice,
uint256 mintsPerUser,
address tokenAddress,
address currency,
uint8 v,
bytes32 r,
bytes32 s
) external payable nonReentrant {
if (OdysseyTokenFactory(factory).tokenExists(tokenAddress) == 0) {
revert OdysseyLaunchPlatform_TokenDoesNotExist();
}
if (whitelistClaimed721[tokenAddress][msg.sender] >= mintsPerUser) {
revert OdysseyLaunchPlatform_AlreadyClaimed();
}
// Check if user is already reserved + paid
if (isReserved721[tokenAddress][msg.sender] == 0) {
if (
cumulativeSupply721[tokenAddress] >= maxSupply721[tokenAddress]
) {
revert OdysseyLaunchPlatform_MaxSupplyCap();
}
{
// Verify merkle root and minPrice signed by owner (all id's have same min price)
bytes32 hash = keccak256(
abi.encode(
MERKLE_TREE_ROOT_ERC721_TYPEHASH,
merkleRoot,
minPrice,
mintsPerUser,
tokenAddress,
currency
)
);
Signature.verify(
hash,
ownerOf[tokenAddress],
v,
r,
s,
domainSeparator[tokenAddress]
);
}
if (whitelistActive[tokenAddress] == 1) {
// Verify user whitelisted
MerkleWhiteList.verify(msg.sender, merkleProof, merkleRoot);
}
cumulativeSupply721[tokenAddress]++;
OdysseyLib.Percentage storage percent = treasuryCommission[
tokenAddress
];
uint256 commission = (minPrice * percent.numerator) /
percent.denominator;
if (currency == address(0)) {
if (msg.value < minPrice) {
revert OdysseyLaunchPlatform_InsufficientFunds();
}
(bool treasurySuccess, ) = treasury.call{value: commission}("");
if (!treasurySuccess) {
revert OdysseyLaunchPlatform_TreasuryPayFailure();
}
(bool success, ) = royaltyRecipient[tokenAddress].call{
value: minPrice - commission
}("");
if (!success) {
revert OdysseyLaunchPlatform_FailedToPayEther();
}
} else {
if (
ERC20(currency).allowance(msg.sender, address(this)) <
minPrice
) {
revert OdysseyLaunchPlatform_InsufficientFunds();
}
bool result = ERC20(currency).transferFrom(
msg.sender,
treasury,
commission
);
if (!result) {
revert OdysseyLaunchPlatform_TreasuryPayFailure();
}
result = ERC20(currency).transferFrom(
msg.sender,
royaltyRecipient[tokenAddress],
minPrice - commission
);
if (!result) {
revert OdysseyLaunchPlatform_FailedToPayERC20();
}
if (ohmFamilyCurrencies[currency] == 1) {
OdysseyXp(xp).ohmMintReward(msg.sender, tokenAddress, 0);
}
}
} else {
isReserved721[tokenAddress][msg.sender]--;
}
// Update State
whitelistClaimed721[tokenAddress][msg.sender]++;
OdysseyERC721(tokenAddress).mint(
msg.sender,
mintedSupply721[tokenAddress]++
);
}
function reserveERC721(
bytes32[] calldata merkleProof,
bytes32 merkleRoot,
uint256 minPrice,
uint256 mintsPerUser,
address tokenAddress,
address currency,
uint8 v,
bytes32 r,
bytes32 s
) external payable nonReentrant {
if (OdysseyTokenFactory(factory).tokenExists(tokenAddress) == 0) {
revert OdysseyLaunchPlatform_TokenDoesNotExist();
}
if (cumulativeSupply721[tokenAddress] >= maxSupply721[tokenAddress]) {
revert OdysseyLaunchPlatform_MaxSupplyCap();
}
if (
isReserved721[tokenAddress][msg.sender] +
whitelistClaimed721[tokenAddress][msg.sender] >=
mintsPerUser
) {
revert OdysseyLaunchPlatform_ReservedOrClaimedMax();
}
{
// Verify merkle root and minPrice signed by owner (all id's have same min price)
bytes32 hash = keccak256(
abi.encode(
MERKLE_TREE_ROOT_ERC721_TYPEHASH,
merkleRoot,
minPrice,
mintsPerUser,
tokenAddress,
currency
)
);
Signature.verify(
hash,
ownerOf[tokenAddress],
v,
r,
s,
domainSeparator[tokenAddress]
);
}
if (whitelistActive[tokenAddress] == 1) {
// Verify user whitelisted
MerkleWhiteList.verify(msg.sender, merkleProof, merkleRoot);
}
// Set user is reserved
isReserved721[tokenAddress][msg.sender]++;
// Increate Reserved + minted supply
cumulativeSupply721[tokenAddress]++;
OdysseyLib.Percentage storage percent = treasuryCommission[
tokenAddress
];
uint256 commission = (minPrice * percent.numerator) /
percent.denominator;
if (currency == address(0)) {
if (msg.value < minPrice) {
revert OdysseyLaunchPlatform_InsufficientFunds();
}
(bool treasurySuccess, ) = treasury.call{value: commission}("");
if (!treasurySuccess) {
revert OdysseyLaunchPlatform_TreasuryPayFailure();
}
(bool success, ) = royaltyRecipient[tokenAddress].call{
value: minPrice - commission
}("");
if (!success) {
revert OdysseyLaunchPlatform_FailedToPayEther();
}
} else {
if (
ERC20(currency).allowance(msg.sender, address(this)) < minPrice
) {
revert OdysseyLaunchPlatform_InsufficientFunds();
}
bool result = ERC20(currency).transferFrom(
msg.sender,
treasury,
commission
);
if (!result) {
revert OdysseyLaunchPlatform_TreasuryPayFailure();
}
result = ERC20(currency).transferFrom(
msg.sender,
royaltyRecipient[tokenAddress],
minPrice - commission
);
if (!result) {
revert OdysseyLaunchPlatform_FailedToPayERC20();
}
if (ohmFamilyCurrencies[currency] == 1) {
OdysseyXp(xp).ohmMintReward(msg.sender, tokenAddress, 0);
}
}
}
function mintERC1155(
bytes32[] calldata merkleProof,
bytes32 merkleRoot,
uint256 minPrice,
uint256 mintsPerUser,
uint256 tokenId,
address tokenAddress,
address currency,
uint8 v,
bytes32 r,
bytes32 s
) external payable nonReentrant {
if (OdysseyTokenFactory(factory).tokenExists(tokenAddress) == 0) {
revert OdysseyLaunchPlatform_TokenDoesNotExist();
}
if (
whitelistClaimed1155[tokenAddress][msg.sender][tokenId] >=
mintsPerUser
) {
revert OdysseyLaunchPlatform_AlreadyClaimed();
}
// Check if user is already reserved + paid
if (isReserved1155[tokenAddress][msg.sender][tokenId] == 0) {
if (
cumulativeSupply1155[tokenAddress][tokenId] >=
maxSupply1155[tokenAddress][tokenId]
) {
revert OdysseyLaunchPlatform_MaxSupplyCap();
}
{
// Verify merkle root and minPrice signed by owner (all id's have same min price)
bytes32 hash = keccak256(
abi.encode(
MERKLE_TREE_ROOT_ERC1155_TYPEHASH,
merkleRoot,
minPrice,
mintsPerUser,
tokenId,
tokenAddress,
currency
)
);
Signature.verify(
hash,
ownerOf[tokenAddress],
v,
r,
s,
domainSeparator[tokenAddress]
);
}
if (whitelistActive[tokenAddress] == 1) {
// Verify user whitelisted
MerkleWhiteList.verify(msg.sender, merkleProof, merkleRoot);
}
cumulativeSupply1155[tokenAddress][tokenId]++;
OdysseyLib.Percentage storage percent = treasuryCommission[
tokenAddress
];
uint256 commission = (minPrice * percent.numerator) /
percent.denominator;
if (currency == address(0)) {
if (msg.value < minPrice) {
revert OdysseyLaunchPlatform_InsufficientFunds();
}
(bool treasurySuccess, ) = treasury.call{value: commission}("");
if (!treasurySuccess) {
revert OdysseyLaunchPlatform_TreasuryPayFailure();
}
(bool success, ) = royaltyRecipient[tokenAddress].call{
value: minPrice - commission
}("");
if (!success) {
revert OdysseyLaunchPlatform_FailedToPayEther();
}
} else {
if (
ERC20(currency).allowance(msg.sender, address(this)) <
minPrice
) {
revert OdysseyLaunchPlatform_InsufficientFunds();
}
bool result = ERC20(currency).transferFrom(
msg.sender,
treasury,
commission
);
if (!result) {
revert OdysseyLaunchPlatform_TreasuryPayFailure();
}
result = ERC20(currency).transferFrom(
msg.sender,
royaltyRecipient[tokenAddress],
minPrice - commission
);
if (!result) {
revert OdysseyLaunchPlatform_FailedToPayERC20();
}
if (ohmFamilyCurrencies[currency] == 1) {
OdysseyXp(xp).ohmMintReward(
msg.sender,
tokenAddress,
tokenId
);
}
}
} else {
isReserved1155[tokenAddress][msg.sender][tokenId]--;
}
// Update State
whitelistClaimed1155[tokenAddress][msg.sender][tokenId]++;
OdysseyERC1155(tokenAddress).mint(msg.sender, tokenId);
}
function reserveERC1155(
bytes32[] calldata merkleProof,
bytes32 merkleRoot,
uint256 minPrice,
uint256 mintsPerUser,
uint256 tokenId,
address tokenAddress,
address currency,
uint8 v,
bytes32 r,
bytes32 s
) external payable nonReentrant {
if (OdysseyTokenFactory(factory).tokenExists(tokenAddress) == 0) {
revert OdysseyLaunchPlatform_TokenDoesNotExist();
}
if (
cumulativeSupply1155[tokenAddress][tokenId] >=
maxSupply1155[tokenAddress][tokenId]
) {
revert OdysseyLaunchPlatform_MaxSupplyCap();
}
if (
isReserved1155[tokenAddress][msg.sender][tokenId] +
whitelistClaimed1155[tokenAddress][msg.sender][tokenId] >=
mintsPerUser
) {
revert OdysseyLaunchPlatform_ReservedOrClaimedMax();
}
{
// Verify merkle root and minPrice signed by owner (all id's have same min price)
bytes32 hash = keccak256(
abi.encode(
MERKLE_TREE_ROOT_ERC1155_TYPEHASH,
merkleRoot,
minPrice,
mintsPerUser,
tokenId,
tokenAddress,
currency
)
);
Signature.verify(
hash,
ownerOf[tokenAddress],
v,
r,
s,
domainSeparator[tokenAddress]
);
}
if (whitelistActive[tokenAddress] == 1) {
// Verify user whitelisted
MerkleWhiteList.verify(msg.sender, merkleProof, merkleRoot);
}
// Set user is reserved
isReserved1155[tokenAddress][msg.sender][tokenId]++;
// Increase Reserved + minted supply
cumulativeSupply1155[tokenAddress][tokenId]++;
OdysseyLib.Percentage storage percent = treasuryCommission[
tokenAddress
];
uint256 commission = (minPrice * percent.numerator) /
percent.denominator;
if (currency == address(0)) {
if (msg.value < minPrice) {
revert OdysseyLaunchPlatform_InsufficientFunds();
}
(bool treasurySuccess, ) = treasury.call{value: commission}("");
if (!treasurySuccess) {
revert OdysseyLaunchPlatform_TreasuryPayFailure();
}
(bool success, ) = royaltyRecipient[tokenAddress].call{
value: minPrice - commission
}("");
if (!success) {
revert OdysseyLaunchPlatform_FailedToPayEther();
}
} else {
if (
ERC20(currency).allowance(msg.sender, address(this)) < minPrice
) {
revert OdysseyLaunchPlatform_InsufficientFunds();
}
bool result = ERC20(currency).transferFrom(
msg.sender,
treasury,
commission
);
if (!result) {
revert OdysseyLaunchPlatform_TreasuryPayFailure();
}
result = ERC20(currency).transferFrom(
msg.sender,
royaltyRecipient[tokenAddress],
minPrice - commission
);
if (!result) {
revert OdysseyLaunchPlatform_FailedToPayERC20();
}
if (ohmFamilyCurrencies[currency] == 1) {
OdysseyXp(xp).ohmMintReward(msg.sender, tokenAddress, tokenId);
}
}
}
function setWhitelistStatus(address addr, bool active)
external
nonReentrant
{
if (OdysseyTokenFactory(factory).tokenExists(addr) == 0) {
revert OdysseyLaunchPlatform_TokenDoesNotExist();
}
whitelistActive[addr] = active ? 1 : 0;
}
function mint721OnCreate(uint256 amount, address token)
external
nonReentrant
{
cumulativeSupply721[token] = amount;
mintedSupply721[token] = amount;
uint256 i;
for (; i < amount; ++i) {
OdysseyERC721(token).mint(msg.sender, i);
}
}
function mint1155OnCreate(
uint256[] calldata tokenIds,
uint256[] calldata amounts,
address token
) external nonReentrant {
uint256 i;
for (; i < tokenIds.length; ++i) {
cumulativeSupply1155[token][tokenIds[i]] = amounts[i];
OdysseyERC1155(token).mintBatch(
msg.sender,
tokenIds[i],
amounts[i]
);
}
}
function ownerMint721(address token, address to) external nonReentrant {
if (cumulativeSupply721[token] >= maxSupply721[token]) {
revert OdysseyLaunchPlatform_MaxSupplyCap();
}
cumulativeSupply721[token]++;
OdysseyERC721(token).mint(to, mintedSupply721[token]++);
}
function ownerMint1155(
uint256 id,
uint256 amount,
address token,
address to
) external nonReentrant {
if (
cumulativeSupply1155[token][id] + amount > maxSupply1155[token][id]
) {
revert OdysseyLaunchPlatform_MaxSupplyCap();
}
cumulativeSupply1155[token][id] += amount;
OdysseyERC1155(token).mintBatch(to, id, amount);
}
}
contract OdysseyRouter is OdysseyDatabase, ReentrancyGuard {
error OdysseyRouter_TokenIDSupplyMismatch();
error OdysseyRouter_WhitelistUpdateFail();
error OdysseyRouter_Unauthorized();
error OdysseyRouter_OwnerMintFailure();
error OdysseyRouter_BadTokenAddress();
error OdysseyRouter_BadOwnerAddress();
error OdysseyRouter_BadSenderAddress();
error OdysseyRouter_BadRecipientAddress();
error OdysseyRouter_BadTreasuryAddress();
error OdysseyRouter_BadAdminAddress();
constructor(
address treasury_,
address xpDirectory_,
address xp_,
address[] memory ohmCurrencies_
) {
launchPlatform = address(new OdysseyLaunchPlatform());
factory = address(new OdysseyTokenFactory());
treasury = treasury_;
admin = msg.sender;
uint256 i;
for (; i < ohmCurrencies_.length; i++) {
ohmFamilyCurrencies[ohmCurrencies_[i]] = 1;
}
if (xp_ == address(0)) {
if (xpDirectory_ == address(0)) {
xpDirectory_ = address(new OdysseyXpDirectory());
OdysseyXpDirectory(xpDirectory_).setDefaultRewards(
1,
1,
1,
3,
3,
1
);
OdysseyXpDirectory(xpDirectory_).transferOwnership(admin);
}
xp_ = address(
new OdysseyXp(
ERC20(ohmCurrencies_[0]),
OdysseyXpDirectory(xpDirectory_),
address(this),
address(this),
admin
)
);
}
xp = xp_;
}
function Factory() public view returns (OdysseyTokenFactory) {
return OdysseyTokenFactory(readSlotAsAddress(1));
}
function create1155(
string calldata name,
string calldata symbol,
string calldata baseURI,
OdysseyLib.Odyssey1155Info calldata info,
OdysseyLib.Percentage calldata treasuryPercentage,
address royaltyReceiver,
bool whitelist
) external returns (address token) {
if (info.maxSupply.length != info.tokenIds.length) {
revert OdysseyRouter_TokenIDSupplyMismatch();
}
token = Factory().create1155(msg.sender, name, symbol, baseURI);
ownerOf[token] = msg.sender;
whitelistActive[token] = whitelist ? 1 : 0;
royaltyRecipient[token] = royaltyReceiver;
uint256 i;
for (; i < info.tokenIds.length; ++i) {
maxSupply1155[token][info.tokenIds[i]] = (info.maxSupply[i] == 0)
? type(uint256).max
: info.maxSupply[i];
}
domainSeparator[token] = keccak256(
abi.encode(
// keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
keccak256(bytes(Strings.toHexString(uint160(token)))),
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1"))
block.chainid,
token
)
);
if (OdysseyLib.compareDefaultPercentage(treasuryPercentage)) {
// Treasury % was greater than 3/100
treasuryCommission[token] = treasuryPercentage;
} else {
// Treasury % was less than 3/100, using 3/100 as default
treasuryCommission[token] = OdysseyLib.Percentage(3, 100);
}
if (info.reserveAmounts.length > 0) {
(bool success, bytes memory data) = launchPlatform.delegatecall(
abi.encodeWithSignature(
"mint1155OnCreate(uint256[],uint256[],address)",
info.tokenIds,
info.reserveAmounts,
token
)
);
if (!success) {
if (data.length == 0) revert();
assembly {
revert(add(32, data), mload(data))
}
}
}
return token;
}
function create721(
string calldata name,
string calldata symbol,
string calldata baseURI,
uint256 maxSupply,
uint256 reserveAmount,
OdysseyLib.Percentage calldata treasuryPercentage,
address royaltyReceiver,
bool whitelist
) external returns (address token) {
token = Factory().create721(msg.sender, name, symbol, baseURI);
ownerOf[token] = msg.sender;
maxSupply721[token] = (maxSupply == 0) ? type(uint256).max : maxSupply;
whitelistActive[token] = whitelist ? 1 : 0;
royaltyRecipient[token] = royaltyReceiver;
domainSeparator[token] = keccak256(
abi.encode(
// keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
keccak256(bytes(Strings.toHexString(uint160(token)))),
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1"))
block.chainid,
token
)
);
if (OdysseyLib.compareDefaultPercentage(treasuryPercentage)) {
// Treasury % was greater than 3/100
treasuryCommission[token] = treasuryPercentage;
} else {
// Treasury % was less than 3/100, using 3/100 as default
treasuryCommission[token] = OdysseyLib.Percentage(3, 100);
}
if (reserveAmount > 0) {
(bool success, bytes memory data) = launchPlatform.delegatecall(
abi.encodeWithSignature(
"mint721OnCreate(uint256,address)",
reserveAmount,
token
)
);
if (!success) {
if (data.length == 0) revert();
assembly {
revert(add(32, data), mload(data))
}
}
}
return token;
}
function mintERC721(
bytes32[] calldata merkleProof,
bytes32 merkleRoot,
uint256 minPrice,
uint256 mintsPerUser,
address tokenAddress,
address currency,
uint8 v,
bytes32 r,
bytes32 s
) public payable {
(bool success, bytes memory data) = launchPlatform.delegatecall(
abi.encodeWithSignature(
"mintERC721(bytes32[],bytes32,uint256,uint256,address,address,uint8,bytes32,bytes32)",
merkleProof,
merkleRoot,
minPrice,
mintsPerUser,
tokenAddress,
currency,
v,
r,
s
)
);
if (!success) {
if (data.length == 0) revert();
assembly {
revert(add(32, data), mload(data))
}
}
}
function batchMintERC721(OdysseyLib.BatchMint calldata batch)
public
payable
{
for (uint256 i = 0; i < batch.tokenAddress.length; i++) {
(bool success, bytes memory data) = launchPlatform.delegatecall(
abi.encodeWithSignature(
"mintERC721(bytes32[],bytes32,uint256,uint256,address,address,uint8,bytes32,bytes32)",
batch.merkleProof[i],
batch.merkleRoot[i],
batch.minPrice[i],
batch.mintsPerUser[i],
batch.tokenAddress[i],
batch.currency[i],
batch.v[i],
batch.r[i],
batch.s[i]
)
);
if (!success) {
if (data.length == 0) revert();
assembly {
revert(add(32, data), mload(data))
}
}
}
}
function reserveERC721(
bytes32[] calldata merkleProof,
bytes32 merkleRoot,
uint256 minPrice,
uint256 mintsPerUser,
address tokenAddress,
address currency,
uint8 v,
bytes32 r,
bytes32 s
) public payable {
(bool success, bytes memory data) = launchPlatform.delegatecall(
abi.encodeWithSignature(
"reserveERC721(bytes32[],bytes32,uint256,uint256,address,address,uint8,bytes32,bytes32)",
merkleProof,
merkleRoot,
minPrice,
mintsPerUser,
tokenAddress,
currency,
v,
r,
s
)
);
if (!success) {
if (data.length == 0) revert();
assembly {
revert(add(32, data), mload(data))
}
}
}
function batchReserveERC721(OdysseyLib.BatchMint calldata batch)
public
payable
{
for (uint256 i = 0; i < batch.tokenAddress.length; i++) {
(bool success, bytes memory data) = launchPlatform.delegatecall(
abi.encodeWithSignature(
"reserveERC721(bytes32[],bytes32,uint256,uint256,address,address,uint8,bytes32,bytes32)",
batch.merkleProof[i],
batch.merkleRoot[i],
batch.minPrice[i],
batch.mintsPerUser[i],
batch.tokenAddress[i],
batch.currency[i],
batch.v[i],
batch.r[i],
batch.s[i]
)
);
if (!success) {
if (data.length == 0) revert();
assembly {
revert(add(32, data), mload(data))
}
}
}
}
function mintERC1155(
bytes32[] calldata merkleProof,
bytes32 merkleRoot,
uint256 minPrice,
uint256 mintsPerUser,
uint256 tokenId,
address tokenAddress,
address currency,
uint8 v,
bytes32 r,
bytes32 s
) public payable {
(bool success, bytes memory data) = launchPlatform.delegatecall(
abi.encodeWithSignature(
"mintERC1155(bytes32[],bytes32,uint256,uint256,uint256,address,address,uint8,bytes32,bytes32)",
merkleProof,
merkleRoot,
minPrice,
mintsPerUser,
tokenId,
tokenAddress,
currency,
v,
r,
s
)
);
if (!success) {
if (data.length == 0) revert();
assembly {
revert(add(32, data), mload(data))
}
}
}
function batchMintERC1155(OdysseyLib.BatchMint calldata batch)
public
payable
{
for (uint256 i = 0; i < batch.tokenAddress.length; i++) {
(bool success, bytes memory data) = launchPlatform.delegatecall(
abi.encodeWithSignature(
"mintERC1155(bytes32[],bytes32,uint256,uint256,uint256,address,address,uint8,bytes32,bytes32)",
batch.merkleProof[i],
batch.merkleRoot[i],
batch.minPrice[i],
batch.mintsPerUser[i],
batch.tokenId[i],
batch.tokenAddress[i],
batch.currency[i],
batch.v[i],
batch.r[i],
batch.s[i]
)
);
if (!success) {
if (data.length == 0) revert();
assembly {
revert(add(32, data), mload(data))
}
}
}
}
function reserveERC1155(
bytes32[] calldata merkleProof,
bytes32 merkleRoot,
uint256 minPrice,
uint256 mintsPerUser,
uint256 tokenId,
address tokenAddress,
address currency,
uint8 v,
bytes32 r,
bytes32 s
) public payable {
(bool success, bytes memory data) = launchPlatform.delegatecall(
abi.encodeWithSignature(
"reserveERC1155(bytes32[],bytes32,uint256,uint256,uint256,address,address,uint8,bytes32,bytes32)",
merkleProof,
merkleRoot,
minPrice,
mintsPerUser,
tokenId,
tokenAddress,
currency,
v,
r,
s
)
);
if (!success) {
if (data.length == 0) revert();
assembly {
revert(add(32, data), mload(data))
}
}
}
function batchReserveERC1155(OdysseyLib.BatchMint calldata batch)
public
payable
{
for (uint256 i = 0; i < batch.tokenAddress.length; i++) {
(bool success, bytes memory data) = launchPlatform.delegatecall(
abi.encodeWithSignature(
"reserveERC1155(bytes32[],bytes32,uint256,uint256,uint256,address,address,uint8,bytes32,bytes32)",
batch.merkleProof[i],
batch.merkleRoot[i],
batch.minPrice[i],
batch.mintsPerUser[i],
batch.tokenId[i],
batch.tokenAddress[i],
batch.currency[i],
batch.v[i],
batch.r[i],
batch.s[i]
)
);
if (!success) {
if (data.length == 0) revert();
assembly {
revert(add(32, data), mload(data))
}
}
}
}
function setWhitelistStatus(address addr, bool active) public {
if (msg.sender != ownerOf[addr]) {
revert OdysseyRouter_Unauthorized();
}
(bool success, ) = launchPlatform.delegatecall(
abi.encodeWithSignature(
"setWhitelistStatus(address,bool)",
addr,
active
)
);
if (!success) {
revert OdysseyRouter_WhitelistUpdateFail();
}
}
function ownerMint721(address token, address to) public {
if (ownerOf[token] != msg.sender) {
revert OdysseyRouter_Unauthorized();
}
(bool success, ) = launchPlatform.delegatecall(
abi.encodeWithSignature("ownerMint721(address,address)", token, to)
);
if (!success) {
revert OdysseyRouter_OwnerMintFailure();
}
}
function ownerMint1155(
uint256 id,
uint256 amount,
address token,
address to
) public {
if (ownerOf[token] != msg.sender) {
revert OdysseyRouter_Unauthorized();
}
(bool success, ) = launchPlatform.delegatecall(
abi.encodeWithSignature(
"ownerMint1155(uint256,uint256,address,address)",
id,
amount,
token,
to
)
);
if (!success) {
revert OdysseyRouter_OwnerMintFailure();
}
}
function setOwnerShip(address token, address newOwner) public {
if (token == address(0)) {
revert OdysseyRouter_BadTokenAddress();
}
if (newOwner == address(0)) {
revert OdysseyRouter_BadOwnerAddress();
}
if (msg.sender == address(0)) {
revert OdysseyRouter_BadSenderAddress();
}
if (ownerOf[token] != msg.sender) {
revert OdysseyRouter_Unauthorized();
}
ownerOf[token] = newOwner;
}
function setRoyaltyRecipient(address token, address recipient) public {
if (token == address(0)) {
revert OdysseyRouter_BadTokenAddress();
}
if (recipient == address(0)) {
revert OdysseyRouter_BadRecipientAddress();
}
if (msg.sender == address(0)) {
revert OdysseyRouter_BadSenderAddress();
}
if (ownerOf[token] != msg.sender) {
revert OdysseyRouter_Unauthorized();
}
royaltyRecipient[token] = recipient;
}
function setTreasury(address newTreasury) public {
if (msg.sender != admin) {
revert OdysseyRouter_Unauthorized();
}
if (msg.sender == address(0)) {
revert OdysseyRouter_BadSenderAddress();
}
if (newTreasury == address(0)) {
revert OdysseyRouter_BadTreasuryAddress();
}
treasury = newTreasury;
}
function setXP(address newXp) public {
if (msg.sender != admin) {
revert OdysseyRouter_Unauthorized();
}
if (msg.sender == address(0)) {
revert OdysseyRouter_BadSenderAddress();
}
if (newXp == address(0)) {
revert OdysseyRouter_BadTokenAddress();
}
xp = newXp;
}
function setAdmin(address newAdmin) public {
if (msg.sender != admin) {
revert OdysseyRouter_Unauthorized();
}
if (msg.sender == address(0)) {
revert OdysseyRouter_BadSenderAddress();
}
if (newAdmin == address(0)) {
revert OdysseyRouter_BadAdminAddress();
}
admin = newAdmin;
}
function setMaxSupply721(address token, uint256 amount) public {
if (ownerOf[token] != msg.sender) {
revert OdysseyRouter_Unauthorized();
}
maxSupply721[token] = amount;
}
function setMaxSupply1155(
address token,
uint256[] calldata tokenIds,
uint256[] calldata amounts
) public {
if (ownerOf[token] != msg.sender) {
revert OdysseyRouter_Unauthorized();
}
uint256 i;
for (; i < tokenIds.length; ++i) {
maxSupply1155[token][tokenIds[i]] = amounts[i];
}
}
}
| save an SLOAD from length reading
| NFT[] memory _customRewardTokens = customRewardTokens; | 5,906,449 | [
1,
5688,
392,
348,
7783,
628,
769,
6453,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
423,
4464,
8526,
3778,
389,
3662,
17631,
1060,
5157,
273,
1679,
17631,
1060,
5157,
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
]
|
pragma solidity 0.5.16;
import "../helpers/HitchensUnorderedAddressSetLib.sol";
/// @title Erasure_Users
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: [email protected]
/// @dev Version: 1.3.0
contract Erasure_Users {
using HitchensUnorderedAddressSetLib for HitchensUnorderedAddressSetLib.Set;
HitchensUnorderedAddressSetLib.Set private _users;
mapping (address => bytes) private _metadata;
event UserRegistered(address indexed user, bytes data);
event UserRemoved(address indexed user);
// state functions
function registerUser(bytes memory data) public {
require(!_users.exists(msg.sender), "user already exists");
// add user
_users.insert(msg.sender);
// set metadata
_metadata[msg.sender] = data;
// emit event
emit UserRegistered(msg.sender, data);
}
function removeUser() public {
// require user is registered
require(_users.exists(msg.sender), "user does not exist");
// remove user
_users.remove(msg.sender);
// delete metadata
delete _metadata[msg.sender];
// emit event
emit UserRemoved(msg.sender);
}
// view functions
function getUserData(address user) public view returns (bytes memory data) {
data = _metadata[user];
}
function getUsers() public view returns (address[] memory users) {
users = _users.keyList;
}
function getUserCount() public view returns (uint256 count) {
count = _users.count();
}
// Note: startIndex is inclusive, endIndex exclusive
function getPaginatedUsers(uint256 startIndex, uint256 endIndex) public view returns (address[] memory users) {
require(startIndex < endIndex, "startIndex must be less than endIndex");
require(endIndex <= _users.count(), "end index out of range");
// initialize fixed size memory array
address[] memory range = new address[](endIndex - startIndex);
// Populate array with addresses in range
for (uint256 i = startIndex; i < endIndex; i++) {
range[i - startIndex] = _users.keyAtIndex(i);
}
// return array of addresses
users = range;
}
}
| return array of addresses | users = range;
| 1,777,728 | [
1,
2463,
526,
434,
6138,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
3677,
273,
1048,
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,
-100
]
|
pragma solidity 0.5.8;
pragma experimental ABIEncoderV2;
import "./IERC20.sol";
import "./IERC721.sol";
import "./SafeMath.sol";
/// @title EthlanceJob
/// @dev A contract for issuing jobs on Ethereum paying in ETH, ERC20, or ERC721 tokens
/// @author Mark Beylin <[email protected]>, Gonçalo Sá <[email protected]>, Kevin Owocki <[email protected]>, Ricardo Guilherme Schmidt (@3esmit), Matt Garnett <[email protected]>, Craig Williams <[email protected]>
contract EthlanceJobs {
using SafeMath for uint256;
/*
* Structs
*/
struct Job {
address payable[] issuers; // An array of individuals who have complete control over the job, and can edit any of its parameters
address[] approvers; // An array of individuals who are allowed to accept the invoices for a particular job
address token; // The address of the token associated with the job (should be disregarded if the tokenVersion is 0)
uint tokenVersion; // The version of the token being used for the job (0 for ETH, 20 for ERC20, 721 for ERC721)
uint balance; // The number of tokens which the job is able to pay out or refund
Invoice[] invoices; // An array of Invoice which store the various submissions which have been made to the job
Contribution[] contributions; // An array of Contributions which store the contributions which have been made to the job
address[] hiredCandidates;
}
struct Invoice {
address payable issuer; // Address who should receive payouts for a given submission
address submitter;
uint amount;
bool cancelled;
}
struct Contribution {
address payable contributor; // The address of the individual who contributed
uint amount; // The amount of tokens the user contributed
bool refunded; // A boolean storing whether or not the contribution has been refunded yet
}
/*
* Storage
*/
uint public numJobs; // An integer storing the total number of jobs in the contract
mapping(uint => Job) public jobs; // A mapping of jobIDs to jobs
mapping (uint => mapping (uint => bool)) public tokenBalances; // A mapping of jobIds to tokenIds to booleans, storing whether a given job has a given ERC721 token in its balance
address public owner; // The address of the individual who's allowed to set the metaTxRelayer address
address public metaTxRelayer; // The address of the meta transaction relayer whose _sender is automatically trusted for all contract calls
bool public callStarted; // Ensures mutex for the entire contract
/*
* Modifiers
*/
modifier callNotStarted(){
require(!callStarted);
callStarted = true;
_;
callStarted = false;
}
modifier validateJobArrayIndex(
uint _index)
{
require(_index < numJobs);
_;
}
modifier validateContributionArrayIndex(
uint _jobId,
uint _index)
{
require(_index < jobs[_jobId].contributions.length);
_;
}
modifier validateInvoiceArrayIndex(
uint _jobId,
uint _index)
{
require(_index < jobs[_jobId].invoices.length);
_;
}
modifier validateIssuerArrayIndex(
uint _jobId,
uint _index)
{
require(_index < jobs[_jobId].issuers.length);
_;
}
modifier validateApproverArrayIndex(
uint _jobId,
uint _index)
{
require(_index < jobs[_jobId].approvers.length);
_;
}
modifier onlyIssuer(
address _sender,
uint _jobId,
uint _issuerId)
{
require(_sender == jobs[_jobId].issuers[_issuerId]);
_;
}
modifier onlyInvoiceIssuer(
address _sender,
uint _jobId,
uint _invoiceId)
{
require(_sender ==
jobs[_jobId].invoices[_invoiceId].issuer);
_;
}
modifier onlyContributor(
address _sender,
uint _jobId,
uint _contributionId)
{
require(_sender ==
jobs[_jobId].contributions[_contributionId].contributor);
_;
}
modifier isApprover(
address _sender,
uint _jobId,
uint _approverId)
{
require(_sender == jobs[_jobId].approvers[_approverId]);
_;
}
modifier hasNotRefunded(
uint _jobId,
uint _contributionId)
{
require(!jobs[_jobId].contributions[_contributionId].refunded);
_;
}
modifier senderIsValid(
address _sender)
{
require(msg.sender == _sender || msg.sender == metaTxRelayer);
_;
}
/*
* Public functions
*/
constructor() public {
// The owner of the contract is automatically designated to be the deployer of the contract
owner = msg.sender;
}
/// @dev setMetaTxRelayer(): Sets the address of the meta transaction relayer
/// @param _relayer the address of the relayer
function setMetaTxRelayer(address _relayer)
external
{
require(msg.sender == owner); // Checks that only the owner can call
require(metaTxRelayer == address(0)); // Ensures the meta tx relayer can only be set once
metaTxRelayer = _relayer;
}
function contains(address[] memory arr, address x) private pure returns(bool)
{
bool found = false;
uint i = 0;
while(i < arr.length && !found){
found = arr[i] == x;
i++;
}
return found;
}
function acceptCandidate(uint jobId, address candidate)
public
{
// Add the candidate as selected for the job
jobs[jobId].hiredCandidates.push(candidate);
emit CandidateAccepted(jobId, candidate);
}
/// @dev issueJob(): creates a new job
/// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer)
/// @param _issuers the array of addresses who will be the issuers of the job
/// @param _approvers the array of addresses who will be the approvers of the job
/// @param _ipfsHash the IPFS hash representing the JSON object storing the details of the job (see docs for schema details)
/// @param _token the address of the token which will be used for the job
/// @param _tokenVersion the version of the token being used for the job (0 for ETH, 20 for ERC20, 721 for ERC721)
function issueJob(
address payable _sender,
address payable[] memory _issuers,
address[] memory _approvers,
string memory _ipfsHash,
address _token,
uint _tokenVersion)
public
senderIsValid(_sender)
returns (uint)
{
require(_tokenVersion == 0 || _tokenVersion == 20 || _tokenVersion == 721); // Ensures a job can only be issued with a valid token version
require(_issuers.length > 0 || _approvers.length > 0); // Ensures there's at least 1 issuer or approver
uint jobId = numJobs; // The next job's index will always equal the number of existing jobs
Job storage newJob = jobs[jobId];
newJob.issuers = _issuers;
newJob.approvers = _approvers;
newJob.tokenVersion = _tokenVersion;
if (_tokenVersion != 0){
newJob.token = _token;
}
numJobs = numJobs.add(1); // Increments the number of jobs, since a new one has just been added
emit JobIssued(jobId,
_sender,
_issuers,
_approvers,
_ipfsHash, // Instead of storing the string on-chain, it is emitted within the event for easy off-chain consumption
_token,
_tokenVersion);
return (jobId);
}
/// @param _depositAmount the amount of tokens being deposited to the job, which will create a new contribution to the job
function issueAndContribute(
address payable _sender,
address payable[] memory _issuers,
address[] memory _approvers,
string memory _ipfsHash,
address _token,
uint _tokenVersion,
uint _depositAmount)
public
payable
returns(uint)
{
uint jobId = issueJob(_sender, _issuers, _approvers, _ipfsHash, _token, _tokenVersion);
contribute(_sender, jobId, _depositAmount);
return (jobId);
}
/// @dev contribute(): Allows users to contribute tokens to a given job.
/// Contributing merits no privelages to administer the
/// funds in the job or accept submissions. Contributions
/// has elapsed, and the job has not yet paid out any funds.
/// All funds deposited in a job are at the mercy of a
/// job's issuers and approvers, so please be careful!
/// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer)
/// @param _jobId the index of the job
/// @param _amount the amount of tokens being contributed
function contribute(
address payable _sender,
uint _jobId,
uint _amount)
public
payable
senderIsValid(_sender)
validateJobArrayIndex(_jobId)
callNotStarted
{
require(_amount > 0); // Contributions of 0 tokens or token ID 0 should fail
jobs[_jobId].contributions.push(
Contribution(_sender, _amount, false)); // Adds the contribution to the job
if (jobs[_jobId].tokenVersion == 0){
jobs[_jobId].balance = jobs[_jobId].balance.add(_amount); // Increments the balance of the job
require(msg.value == _amount);
} else if (jobs[_jobId].tokenVersion == 20){
jobs[_jobId].balance = jobs[_jobId].balance.add(_amount); // Increments the balance of the job
require(msg.value == 0); // Ensures users don't accidentally send ETH alongside a token contribution, locking up funds
require(IERC20(jobs[_jobId].token).transferFrom(_sender,
address(this),
_amount));
} else if (jobs[_jobId].tokenVersion == 721){
tokenBalances[_jobId][_amount] = true; // Adds the 721 token to the balance of the job
require(msg.value == 0); // Ensures users don't accidentally send ETH alongside a token contribution, locking up funds
IERC721(jobs[_jobId].token).transferFrom(_sender,
address(this),
_amount);
} else {
revert();
}
emit ContributionAdded(_jobId,
jobs[_jobId].contributions.length - 1, // The new contributionId
_sender,
_amount);
}
/// @dev refundContribution(): Allows users to refund the contributions they've
/// made to a particular job, but only if the job
/// has not yet paid out
/// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer)
/// @param _issuerId the issuer id for thre job
/// @param _jobId the index of the job
/// @param _contributionId the index of the contribution being refunded
function refundContribution(
address _sender,
uint _jobId,
uint _issuerId,
uint _contributionId)
public
senderIsValid(_sender)
validateJobArrayIndex(_jobId)
validateContributionArrayIndex(_jobId, _contributionId)
onlyIssuer(_sender, _jobId, _issuerId)
hasNotRefunded(_jobId, _contributionId)
callNotStarted
{
Contribution storage contribution = jobs[_jobId].contributions[_contributionId];
contribution.refunded = true;
transferTokens(_jobId, contribution.contributor, contribution.amount); // Performs the disbursal of tokens to the contributor
emit ContributionRefunded(_jobId, _contributionId);
}
/// @dev refundMyContributions(): Allows users to refund their contributions in bulk
/// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer)
/// @param _jobId the index of the job
/// @param _contributionIds the array of indexes of the contributions being refunded
function refundMyContributions(
address _sender,
uint _jobId,
uint _issuerId,
uint[] memory _contributionIds)
public
senderIsValid(_sender)
{
for (uint i = 0; i < _contributionIds.length; i++){
refundContribution(_sender, _jobId, _issuerId, _contributionIds[i]);
}
}
/// @dev refundContributions(): Allows users to refund their contributions in bulk
/// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer)
/// @param _jobId the index of the job
/// @param _issuerId the index of the issuer who is making the call
/// @param _contributionIds the array of indexes of the contributions being refunded
function refundContributions(
address _sender,
uint _jobId,
uint _issuerId,
uint[] memory _contributionIds)
public
senderIsValid(_sender)
validateJobArrayIndex(_jobId)
onlyIssuer(_sender, _jobId, _issuerId)
callNotStarted
{
for (uint i = 0; i < _contributionIds.length; i++){
require(_contributionIds[i] < jobs[_jobId].contributions.length);
Contribution storage contribution = jobs[_jobId].contributions[_contributionIds[i]];
require(!contribution.refunded);
contribution.refunded = true;
transferTokens(_jobId, contribution.contributor, contribution.amount); // Performs the disbursal of tokens to the contributor
}
emit ContributionsRefunded(_jobId, _sender, _contributionIds);
}
/// @dev drainJob(): Allows an issuer to drain the funds from the job
/// @notice when using this function, if an issuer doesn't drain the entire balance, some users may be able to refund their contributions, while others may not (which is unfair to them). Please use it wisely, only when necessary
/// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer)
/// @param _jobId the index of the job
/// @param _issuerId the index of the issuer who is making the call
/// @param _amounts an array of amounts of tokens to be sent. The length of the array should be 1 if the job is in ETH or ERC20 tokens. If it's an ERC721 job, the array should be the list of tokenIDs.
function drainJob(
address payable _sender,
uint _jobId,
uint _issuerId,
uint[] memory _amounts)
public
senderIsValid(_sender)
validateJobArrayIndex(_jobId)
onlyIssuer(_sender, _jobId, _issuerId)
callNotStarted
{
if (jobs[_jobId].tokenVersion == 0 || jobs[_jobId].tokenVersion == 20){
require(_amounts.length == 1); // ensures there's only 1 amount of tokens to be returned
require(_amounts[0] <= jobs[_jobId].balance); // ensures an issuer doesn't try to drain the job of more tokens than their balance permits
transferTokens(_jobId, _sender, _amounts[0]); // Performs the draining of tokens to the issuer
} else {
for (uint i = 0; i < _amounts.length; i++){
require(tokenBalances[_jobId][_amounts[i]]);// ensures an issuer doesn't try to drain the job of a token it doesn't have in its balance
transferTokens(_jobId, _sender, _amounts[i]);
}
}
emit JobDrained(_jobId, _sender, _amounts);
}
/// @dev invoiceJob(): Allows users to invoice the job to get paid out
/// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer)
/// @param _jobId the index of the job
/// @param _invoiceIssuer The invoice issuer, the addresses which will receive payouts for the submission
/// @param _ipfsHash the IPFS hash corresponding to a JSON object which contains the details of the submission (see docs for schema details)
function invoiceJob(
address _sender,
uint _jobId,
address payable _invoiceIssuer,
string memory _ipfsHash,
uint _amount)
public
senderIsValid(_sender)
validateJobArrayIndex(_jobId)
{
require(contains(jobs[_jobId].hiredCandidates, _sender));
jobs[_jobId].invoices.push(Invoice(_invoiceIssuer, _sender, _amount, false));
emit JobInvoice(_jobId,
(jobs[_jobId].invoices.length - 1),
_invoiceIssuer,
_ipfsHash, // The _ipfsHash string is emitted in an event for easy off-chain consumption
_sender,
_amount);
}
/// @dev cancelInvoice(): Allows the sender of the invoice to cancel it
/// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer)
/// @param _jobId the index of the job
/// @param _invoiceId the index of the invoice to be accepted
function cancelInvoice(
address _sender,
uint _jobId,
uint _invoiceId
)
public
senderIsValid(_sender)
validateJobArrayIndex(_jobId)
validateInvoiceArrayIndex(_jobId, _invoiceId)
{
Invoice storage invoice=jobs[_jobId].invoices[_invoiceId];
if(invoice.submitter != _sender){
revert("Only the original invoice sender can cancel it.");
}
invoice.cancelled=true;
emit InvoiceCancelled(_sender, _jobId, _invoiceId);
}
/// @dev acceptInvoice(): Allows any of the approvers to accept a given submission
/// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer)
/// @param _jobId the index of the job
/// @param _invoiceId the index of the invoice to be accepted
/// @param _approverId the index of the approver which is making the call
function acceptInvoice(
address _sender,
uint _jobId,
uint _invoiceId,
uint _approverId
)
public
senderIsValid(_sender)
validateJobArrayIndex(_jobId)
validateInvoiceArrayIndex(_jobId, _invoiceId)
isApprover(_sender, _jobId, _approverId)
callNotStarted
{
Invoice storage invoice = jobs[_jobId].invoices[_invoiceId];
if(invoice.cancelled){
revert("Can't accept a cancelled input");
}
transferTokens(_jobId, invoice.issuer,invoice.amount);
emit InvoiceAccepted(_jobId,
_invoiceId,
_sender,
invoice.amount);
}
/// @dev invoiceAndAccept(): Allows any of the approvers to invoice and accept a submission simultaneously
/// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer)
/// @param _jobId the index of the job
/// @param _invoiceIssuer the array of addresses which will receive payouts for the submission
/// @param _ipfsHash the IPFS hash corresponding to a JSON object which contains the details of the submission (see docs for schema details)
/// @param _approverId the index of the approver which is making the call
function invoiceAndAccept(
address _sender,
uint _jobId,
address payable _invoiceIssuer,
string memory _ipfsHash,
uint _approverId,
uint _amount)
public
senderIsValid(_sender)
{
// first invoice the job on behalf of the _invoiceIssuer
invoiceJob(_sender, _jobId, _invoiceIssuer, _ipfsHash, _amount);
// then accepts the invoice
acceptInvoice(_sender,
_jobId,
jobs[_jobId].invoices.length - 1,
_approverId
);
}
/// @dev changeJob(): Allows any of the issuers to change the job
/// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer)
/// @param _jobId the index of the job
/// @param _issuerId the index of the issuer who is calling the function
/// @param _issuers the new array of addresses who will be the issuers of the job
/// @param _approvers the new array of addresses who will be the approvers of the job
/// @param _ipfsHash the new IPFS hash representing the JSON object storing the details of the job (see docs for schema details)
function changeJob(
address _sender,
uint _jobId,
uint _issuerId,
address payable[] memory _issuers,
address payable[] memory _approvers,
string memory _ipfsHash
)
public
senderIsValid(_sender)
{
require(_jobId < numJobs); // makes the validateJobArrayIndex modifier in-line to avoid stack too deep errors
require(_issuerId < jobs[_jobId].issuers.length); // makes the validateIssuerArrayIndex modifier in-line to avoid stack too deep errors
require(_sender == jobs[_jobId].issuers[_issuerId]); // makes the onlyIssuer modifier in-line to avoid stack too deep errors
require(_issuers.length > 0 || _approvers.length > 0); // Ensures there's at least 1 issuer or approver, so funds don't get stuck
jobs[_jobId].issuers = _issuers;
jobs[_jobId].approvers = _approvers;
emit JobChanged(_jobId,
_sender,
_issuers,
_approvers,
_ipfsHash);
}
/// @dev changeIssuer(): Allows any of the issuers to change a particular issuer of the job
/// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer)
/// @param _jobId the index of the job
/// @param _issuerId the index of the issuer who is calling the function
/// @param _issuerIdToChange the index of the issuer who is being changed
/// @param _newIssuer the address of the new issuer
function changeIssuer(
address _sender,
uint _jobId,
uint _issuerId,
uint _issuerIdToChange,
address payable _newIssuer)
public
senderIsValid(_sender)
validateJobArrayIndex(_jobId)
validateIssuerArrayIndex(_jobId, _issuerIdToChange)
onlyIssuer(_sender, _jobId, _issuerId)
{
require(_issuerId < jobs[_jobId].issuers.length || _issuerId == 0);
jobs[_jobId].issuers[_issuerIdToChange] = _newIssuer;
emit JobIssuersUpdated(_jobId, _sender, jobs[_jobId].issuers);
}
/// @dev changeApprover(): Allows any of the issuers to change a particular approver of the job
/// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer)
/// @param _jobId the index of the job
/// @param _issuerId the index of the issuer who is calling the function
/// @param _approverId the index of the approver who is being changed
/// @param _approver the address of the new approver
function changeApprover(
address _sender,
uint _jobId,
uint _issuerId,
uint _approverId,
address payable _approver)
external
senderIsValid(_sender)
validateJobArrayIndex(_jobId)
onlyIssuer(_sender, _jobId, _issuerId)
validateApproverArrayIndex(_jobId, _approverId)
{
jobs[_jobId].approvers[_approverId] = _approver;
emit JobApproversUpdated(_jobId, _sender, jobs[_jobId].approvers);
}
/// @dev changeData(): Allows any of the issuers to change the data the job
/// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer)
/// @param _jobId the index of the job
/// @param _issuerId the index of the issuer who is calling the function
/// @param _ipfsHash the new IPFS hash representing the JSON object storing the details of the job (see docs for schema details)
function changeData(
address _sender,
uint _jobId,
uint _issuerId,
string memory _ipfsHash)
public
senderIsValid(_sender)
validateJobArrayIndex(_jobId)
validateIssuerArrayIndex(_jobId, _issuerId)
onlyIssuer(_sender, _jobId, _issuerId)
{
emit JobDataChanged(_jobId, _sender, _ipfsHash); // The new _ipfsHash is emitted within an event rather than being stored on-chain for minimized gas costs
}
/// @dev addIssuers(): Allows any of the issuers to add more issuers to the job
/// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer)
/// @param _jobId the index of the job
/// @param _issuerId the index of the issuer who is calling the function
/// @param _issuers the array of addresses to add to the list of valid issuers
function addIssuers(
address _sender,
uint _jobId,
uint _issuerId,
address payable[] memory _issuers)
public
senderIsValid(_sender)
validateJobArrayIndex(_jobId)
validateIssuerArrayIndex(_jobId, _issuerId)
onlyIssuer(_sender, _jobId, _issuerId)
{
for (uint i = 0; i < _issuers.length; i++){
jobs[_jobId].issuers.push(_issuers[i]);
}
emit JobIssuersUpdated(_jobId, _sender, jobs[_jobId].issuers);
}
/// @dev replaceIssuers(): Allows any of the issuers to replace the issuers of the job
/// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer)
/// @param _jobId the index of the job
/// @param _issuerId the index of the issuer who is calling the function
/// @param _issuers the array of addresses to replace the list of valid issuers
function replaceIssuers(
address _sender,
uint _jobId,
uint _issuerId,
address payable[] memory _issuers)
public
senderIsValid(_sender)
validateJobArrayIndex(_jobId)
validateIssuerArrayIndex(_jobId, _issuerId)
onlyIssuer(_sender, _jobId, _issuerId)
{
require(_issuers.length > 0 || jobs[_jobId].approvers.length > 0); // Ensures there's at least 1 issuer or approver, so funds don't get stuck
jobs[_jobId].issuers = _issuers;
emit JobIssuersUpdated(_jobId, _sender, jobs[_jobId].issuers);
}
/// @dev addApprovers(): Allows any of the issuers to add more approvers to the job
/// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer)
/// @param _jobId the index of the job
/// @param _issuerId the index of the issuer who is calling the function
/// @param _approvers the array of addresses to add to the list of valid approvers
function addApprovers(
address _sender,
uint _jobId,
uint _issuerId,
address[] memory _approvers)
public
senderIsValid(_sender)
validateJobArrayIndex(_jobId)
validateIssuerArrayIndex(_jobId, _issuerId)
onlyIssuer(_sender, _jobId, _issuerId)
{
for (uint i = 0; i < _approvers.length; i++){
jobs[_jobId].approvers.push(_approvers[i]);
}
emit JobApproversUpdated(_jobId, _sender, jobs[_jobId].approvers);
}
/// @dev replaceApprovers(): Allows any of the issuers to replace the approvers of the job
/// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer)
/// @param _jobId the index of the job
/// @param _issuerId the index of the issuer who is calling the function
/// @param _approvers the array of addresses to replace the list of valid approvers
function replaceApprovers(
address _sender,
uint _jobId,
uint _issuerId,
address[] memory _approvers)
public
senderIsValid(_sender)
validateJobArrayIndex(_jobId)
validateIssuerArrayIndex(_jobId, _issuerId)
onlyIssuer(_sender, _jobId, _issuerId)
{
require(jobs[_jobId].issuers.length > 0 || _approvers.length > 0); // Ensures there's at least 1 issuer or approver, so funds don't get stuck
jobs[_jobId].approvers = _approvers;
emit JobApproversUpdated(_jobId, _sender, jobs[_jobId].approvers);
}
/// @dev getJob(): Returns the details of the job
/// @param _jobId the index of the job
/// @return Returns a tuple for the job
function getJob(uint _jobId)
external
view
returns (Job memory)
{
return jobs[_jobId];
}
function transferTokens(uint _jobId, address payable _to, uint _amount)
internal
{
if (jobs[_jobId].tokenVersion == 0){
require(_amount > 0); // Sending 0 tokens should throw
require(jobs[_jobId].balance >= _amount);
jobs[_jobId].balance = jobs[_jobId].balance.sub(_amount);
_to.transfer(_amount);
} else if (jobs[_jobId].tokenVersion == 20){
require(_amount > 0); // Sending 0 tokens should throw
require(jobs[_jobId].balance >= _amount);
jobs[_jobId].balance = jobs[_jobId].balance.sub(_amount);
require(IERC20(jobs[_jobId].token).transfer(_to, _amount));
} else if (jobs[_jobId].tokenVersion == 721){
require(tokenBalances[_jobId][_amount]);
tokenBalances[_jobId][_amount] = false; // Removes the 721 token from the balance of the job
IERC721(jobs[_jobId].token).transferFrom(address(this),
_to,
_amount);
} else {
revert();
}
}
/*
* Events
*/
event JobIssued(uint _jobId, address payable _creator, address payable[] _issuers, address[] _approvers, string _ipfsHash, address _token, uint _tokenVersion);
event ContributionAdded(uint _jobId, uint _contributionId, address payable _contributor, uint _amount);
event ContributionRefunded(uint _jobId, uint _contributionId);
event ContributionsRefunded(uint _jobId, address _issuer, uint[] _contributionIds);
event JobDrained(uint _jobId, address _issuer, uint[] _amounts);
event JobInvoice(uint _jobId, uint _invoiceId, address payable _invoiceIssuer, string _ipfsHash, address _submitter, uint _amount);
event InvoiceAccepted(uint _jobId, uint _invoiceId, address _approver, uint _amount);
event JobChanged(uint _jobId, address _changer, address payable[] _issuers, address payable[] _approvers, string _ipfsHash);
event JobIssuersUpdated(uint _jobId, address _changer, address payable[] _issuers);
event JobApproversUpdated(uint _jobId, address _changer, address[] _approvers);
event JobDataChanged(uint _jobId, address _changer, string _ipfsHash);
event CandidateAccepted(uint _jobId, address _candidate);
event InvoiceCancelled(address _sender, uint _jobId, uint _invoiceId);
}
| @dev drainJob(): Allows an issuer to drain the funds from the job @notice when using this function, if an issuer doesn't drain the entire balance, some users may be able to refund their contributions, while others may not (which is unfair to them). Please use it wisely, only when necessary @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer) @param _jobId the index of the job @param _issuerId the index of the issuer who is making the call @param _amounts an array of amounts of tokens to be sent. The length of the array should be 1 if the job is in ETH or ERC20 tokens. If it's an ERC721 job, the array should be the list of tokenIDs. | function drainJob(
address payable _sender,
uint _jobId,
uint _issuerId,
uint[] memory _amounts)
public
senderIsValid(_sender)
validateJobArrayIndex(_jobId)
onlyIssuer(_sender, _jobId, _issuerId)
callNotStarted
{
if (jobs[_jobId].tokenVersion == 0 || jobs[_jobId].tokenVersion == 20){
for (uint i = 0; i < _amounts.length; i++){
transferTokens(_jobId, _sender, _amounts[i]);
}
}
emit JobDrained(_jobId, _sender, _amounts);
}
| 12,943,829 | [
1,
72,
7596,
2278,
13332,
25619,
392,
9715,
358,
15427,
326,
284,
19156,
628,
326,
1719,
225,
1347,
1450,
333,
445,
16,
309,
392,
9715,
3302,
1404,
15427,
326,
7278,
11013,
16,
2690,
3677,
2026,
506,
7752,
358,
16255,
3675,
13608,
6170,
16,
1323,
10654,
2026,
486,
261,
12784,
353,
640,
507,
481,
358,
2182,
2934,
7801,
999,
518,
341,
291,
2357,
16,
1338,
1347,
4573,
225,
389,
15330,
326,
5793,
434,
326,
2492,
3385,
22370,
326,
1719,
261,
13139,
506,
326,
1967,
487,
1234,
18,
15330,
3308,
326,
7827,
353,
2566,
635,
326,
2191,
2229,
1279,
1773,
13,
225,
389,
4688,
548,
326,
770,
434,
326,
1719,
225,
389,
17567,
548,
326,
770,
434,
326,
9715,
10354,
353,
10480,
326,
745,
225,
389,
8949,
87,
392,
526,
434,
30980,
434,
2430,
358,
506,
3271,
18,
1021,
769,
434,
326,
526,
1410,
506,
404,
309,
326,
1719,
353,
316,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
225,
445,
15427,
2278,
12,
203,
10792,
1758,
8843,
429,
389,
15330,
16,
203,
10792,
2254,
389,
4688,
548,
16,
203,
10792,
2254,
389,
17567,
548,
16,
203,
10792,
2254,
8526,
3778,
389,
8949,
87,
13,
203,
565,
1071,
203,
565,
5793,
20536,
24899,
15330,
13,
203,
565,
1954,
2278,
1076,
1016,
24899,
4688,
548,
13,
203,
565,
1338,
16667,
24899,
15330,
16,
389,
4688,
548,
16,
389,
17567,
548,
13,
203,
565,
745,
1248,
9217,
203,
225,
288,
203,
565,
309,
261,
10088,
63,
67,
4688,
548,
8009,
2316,
1444,
422,
374,
747,
6550,
63,
67,
4688,
548,
8009,
2316,
1444,
422,
4200,
15329,
203,
1377,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
389,
8949,
87,
18,
2469,
31,
277,
27245,
95,
203,
3639,
7412,
5157,
24899,
4688,
548,
16,
389,
15330,
16,
389,
8949,
87,
63,
77,
19226,
203,
1377,
289,
203,
565,
289,
203,
203,
565,
3626,
3956,
40,
354,
1920,
24899,
4688,
548,
16,
389,
15330,
16,
389,
8949,
87,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/421613/0xcECbe35263aA1D7bAa765617a6267C3B2a981d88/sources/project_/contracts/Quiz.sol | 1: true, 0: false;
| ListResultAnswersUser[user][0] = 1; | 11,576,447 | [
1,
21,
30,
638,
16,
374,
30,
629,
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,
5411,
987,
1253,
19543,
1299,
63,
1355,
6362,
20,
65,
273,
404,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/80001/0x1202b1aF445302f6f18E6112349d653253c29087/sources/src/MintpadERC721Base.sol | address[] memory _trustedForwarders, | {
using TWStrings for uint256;
State variables
bytes32 private transferRole;
bytes32 private minterRole;
uint256 private constant MAX_BPS = 10_000;
uint256 public maxTotalSupply;
event MaxTotalSupplyUpdated(uint256 maxTotalSupply);
constructor(
address _defaultAdmin,
string memory _name,
string memory _symbol,
string memory _contractURI,
address _saleRecipient,
address _royaltyRecipient,
uint128 _royaltyBps,
uint128 _platformFeeBps,
address _platformFeeRecipient
)
ERC721Base(
_name,
_symbol,
_royaltyRecipient,
_royaltyBps
)
pragma solidity ^0.8.0;
import "@thirdweb-dev/contracts/lib/CurrencyTransferLib.sol";
import "@thirdweb-dev/contracts/lib/TWStrings.sol";
import "@thirdweb-dev/contracts/extension/PlatformFee.sol";
{
bytes32 _transferRole = keccak256("TRANSFER_ROLE");
bytes32 _minterRole = keccak256("MINTER_ROLE");
_setupContractURI(_contractURI);
_setupRole(DEFAULT_ADMIN_ROLE, _defaultAdmin);
_setupRole(_minterRole, _defaultAdmin);
_setupRole(_transferRole, _defaultAdmin);
_setupPlatformFeeInfo(_platformFeeRecipient, _platformFeeBps);
_setupPrimarySaleRecipient(_saleRecipient);
transferRole = _transferRole;
minterRole = _minterRole;
}
ERC165 Logic
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
}
Overriden ERC721 logic
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
(uint256 batchId, ) = _getBatchId(_tokenId);
string memory batchUri = _getBaseURI(_tokenId);
if (isEncryptedBatch(batchId)) {
return string(abi.encodePacked(batchUri, "0"));
return string(abi.encodePacked(batchUri, _tokenId.toString()));
}
}
ERC-721 overrides
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
(uint256 batchId, ) = _getBatchId(_tokenId);
string memory batchUri = _getBaseURI(_tokenId);
if (isEncryptedBatch(batchId)) {
return string(abi.encodePacked(batchUri, "0"));
return string(abi.encodePacked(batchUri, _tokenId.toString()));
}
}
ERC-721 overrides
} else {
function setApprovalForAll(address operator, bool approved)
public
virtual
override
onlyAllowedOperatorApproval(operator)
{
super.setApprovalForAll(operator, approved);
}
function approve(address operator, uint256 tokenId)
public
virtual
override
onlyAllowedOperatorApproval(operator)
{
super.approve(operator, tokenId);
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override onlyAllowedOperator(from) {
super.transferFrom(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override onlyAllowedOperator(from) {
super.safeTransferFrom(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public virtual override onlyAllowedOperator(from) {
super.safeTransferFrom(from, to, tokenId, data);
}
Lazy minting + delayed-reveal logic
function lazyMint(
uint256 _amount,
string calldata _baseURIForTokens,
bytes calldata _data
) public override returns (uint256 batchId) {
if (_data.length > 0) {
(bytes memory encryptedURI, bytes32 provenanceHash) = abi.decode(_data, (bytes, bytes32));
if (encryptedURI.length != 0 && provenanceHash != "") {
_setEncryptedData(nextTokenIdToLazyMint + _amount, _data);
}
}
return super.lazyMint(_amount, _baseURIForTokens, _data);
}
function lazyMint(
uint256 _amount,
string calldata _baseURIForTokens,
bytes calldata _data
) public override returns (uint256 batchId) {
if (_data.length > 0) {
(bytes memory encryptedURI, bytes32 provenanceHash) = abi.decode(_data, (bytes, bytes32));
if (encryptedURI.length != 0 && provenanceHash != "") {
_setEncryptedData(nextTokenIdToLazyMint + _amount, _data);
}
}
return super.lazyMint(_amount, _baseURIForTokens, _data);
}
function lazyMint(
uint256 _amount,
string calldata _baseURIForTokens,
bytes calldata _data
) public override returns (uint256 batchId) {
if (_data.length > 0) {
(bytes memory encryptedURI, bytes32 provenanceHash) = abi.decode(_data, (bytes, bytes32));
if (encryptedURI.length != 0 && provenanceHash != "") {
_setEncryptedData(nextTokenIdToLazyMint + _amount, _data);
}
}
return super.lazyMint(_amount, _baseURIForTokens, _data);
}
function reveal(uint256 _index, bytes calldata _key)
external
onlyRole(minterRole)
returns (string memory revealedURI)
{
uint256 batchId = getBatchIdAtIndex(_index);
revealedURI = getRevealURI(batchId, _key);
_setEncryptedData(batchId, "");
_setBaseURI(batchId, revealedURI);
emit TokenURIRevealed(_index, revealedURI);
}
Setter functions
function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyRole(DEFAULT_ADMIN_ROLE) {
maxTotalSupply = _maxTotalSupply;
emit MaxTotalSupplyUpdated(_maxTotalSupply);
}
Internal (overrideable) functions
function _beforeClaim(
address,
uint256 _quantity,
address,
uint256,
AllowlistProof calldata,
bytes memory
) internal view override {
require(_currentIndex + _quantity <= nextTokenIdToLazyMint, "!Tokens");
require(maxTotalSupply == 0 || _currentIndex + _quantity <= maxTotalSupply, "exceed max total supply.");
}
function _collectPriceOnClaim(
address _primarySaleRecipient,
uint256 _quantityToClaim,
address _currency,
uint256 _pricePerToken
) internal override {
if (_pricePerToken == 0) {
return;
}
(address platformFeeRecipient, uint16 platformFeeBps) = getPlatformFeeInfo();
address saleRecipient = _primarySaleRecipient == address(0) ? primarySaleRecipient() : _primarySaleRecipient;
uint256 totalPrice = _quantityToClaim * _pricePerToken;
uint256 platformFees = (totalPrice * platformFeeBps) / MAX_BPS;
if (_currency == CurrencyTransferLib.NATIVE_TOKEN) {
if (msg.value != totalPrice) {
revert("!Price");
}
}
CurrencyTransferLib.transferCurrency(_currency, _msgSender(), platformFeeRecipient, platformFees);
CurrencyTransferLib.transferCurrency(_currency, _msgSender(), saleRecipient, totalPrice - platformFees);
}
function _collectPriceOnClaim(
address _primarySaleRecipient,
uint256 _quantityToClaim,
address _currency,
uint256 _pricePerToken
) internal override {
if (_pricePerToken == 0) {
return;
}
(address platformFeeRecipient, uint16 platformFeeBps) = getPlatformFeeInfo();
address saleRecipient = _primarySaleRecipient == address(0) ? primarySaleRecipient() : _primarySaleRecipient;
uint256 totalPrice = _quantityToClaim * _pricePerToken;
uint256 platformFees = (totalPrice * platformFeeBps) / MAX_BPS;
if (_currency == CurrencyTransferLib.NATIVE_TOKEN) {
if (msg.value != totalPrice) {
revert("!Price");
}
}
CurrencyTransferLib.transferCurrency(_currency, _msgSender(), platformFeeRecipient, platformFees);
CurrencyTransferLib.transferCurrency(_currency, _msgSender(), saleRecipient, totalPrice - platformFees);
}
function _collectPriceOnClaim(
address _primarySaleRecipient,
uint256 _quantityToClaim,
address _currency,
uint256 _pricePerToken
) internal override {
if (_pricePerToken == 0) {
return;
}
(address platformFeeRecipient, uint16 platformFeeBps) = getPlatformFeeInfo();
address saleRecipient = _primarySaleRecipient == address(0) ? primarySaleRecipient() : _primarySaleRecipient;
uint256 totalPrice = _quantityToClaim * _pricePerToken;
uint256 platformFees = (totalPrice * platformFeeBps) / MAX_BPS;
if (_currency == CurrencyTransferLib.NATIVE_TOKEN) {
if (msg.value != totalPrice) {
revert("!Price");
}
}
CurrencyTransferLib.transferCurrency(_currency, _msgSender(), platformFeeRecipient, platformFees);
CurrencyTransferLib.transferCurrency(_currency, _msgSender(), saleRecipient, totalPrice - platformFees);
}
function _collectPriceOnClaim(
address _primarySaleRecipient,
uint256 _quantityToClaim,
address _currency,
uint256 _pricePerToken
) internal override {
if (_pricePerToken == 0) {
return;
}
(address platformFeeRecipient, uint16 platformFeeBps) = getPlatformFeeInfo();
address saleRecipient = _primarySaleRecipient == address(0) ? primarySaleRecipient() : _primarySaleRecipient;
uint256 totalPrice = _quantityToClaim * _pricePerToken;
uint256 platformFees = (totalPrice * platformFeeBps) / MAX_BPS;
if (_currency == CurrencyTransferLib.NATIVE_TOKEN) {
if (msg.value != totalPrice) {
revert("!Price");
}
}
CurrencyTransferLib.transferCurrency(_currency, _msgSender(), platformFeeRecipient, platformFees);
CurrencyTransferLib.transferCurrency(_currency, _msgSender(), saleRecipient, totalPrice - platformFees);
}
function _transferTokensOnClaim(address _to, uint256 _quantityBeingClaimed)
internal
override
returns (uint256 startTokenId)
{
startTokenId = _currentIndex;
_safeMint(_to, _quantityBeingClaimed);
}
function _canSetPlatformFeeInfo() internal view override returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function _canSetPrimarySaleRecipient() internal view override returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function _canSetOwner() internal view override returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function _canSetRoyaltyInfo() internal view override returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function _canSetContractURI() internal view override returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function _canSetClaimConditions() internal view override returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function _canLazyMint() internal view virtual override returns (bool) {
return hasRole(minterRole, _msgSender());
}
function _canSetOperatorRestriction() internal virtual override returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
Miscellaneous
function totalMinted() external view returns (uint256) {
unchecked {
return _currentIndex - _startTokenId();
}
}
function totalMinted() external view returns (uint256) {
unchecked {
return _currentIndex - _startTokenId();
}
}
function nextTokenIdToMint() public view virtual override returns (uint256) {
return nextTokenIdToLazyMint;
}
function nextTokenIdToClaim() external view returns (uint256) {
return _currentIndex;
}
} | 9,479,860 | [
1,
2867,
8526,
3778,
389,
25247,
8514,
414,
16,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
95,
203,
565,
1450,
24722,
7957,
364,
2254,
5034,
31,
203,
203,
18701,
3287,
3152,
203,
203,
565,
1731,
1578,
3238,
7412,
2996,
31,
203,
565,
1731,
1578,
3238,
1131,
387,
2996,
31,
203,
203,
565,
2254,
5034,
3238,
5381,
4552,
67,
38,
5857,
273,
1728,
67,
3784,
31,
203,
203,
565,
2254,
5034,
1071,
943,
5269,
3088,
1283,
31,
203,
203,
565,
871,
4238,
5269,
3088,
1283,
7381,
12,
11890,
5034,
943,
5269,
3088,
1283,
1769,
203,
203,
565,
3885,
12,
203,
3639,
1758,
389,
1886,
4446,
16,
203,
3639,
533,
3778,
389,
529,
16,
203,
3639,
533,
3778,
389,
7175,
16,
203,
3639,
533,
3778,
389,
16351,
3098,
16,
203,
3639,
1758,
389,
87,
5349,
18241,
16,
203,
3639,
1758,
389,
3800,
15006,
18241,
16,
203,
3639,
2254,
10392,
389,
3800,
15006,
38,
1121,
16,
203,
3639,
2254,
10392,
389,
9898,
14667,
38,
1121,
16,
203,
3639,
1758,
389,
9898,
14667,
18241,
203,
565,
262,
203,
3639,
4232,
39,
27,
5340,
2171,
12,
203,
5411,
389,
529,
16,
203,
5411,
389,
7175,
16,
203,
5411,
389,
3800,
15006,
18241,
16,
203,
5411,
389,
3800,
15006,
38,
1121,
203,
3639,
262,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
203,
203,
203,
5666,
8787,
451,
6909,
4875,
17,
5206,
19,
16351,
87,
19,
2941,
19,
7623,
5912,
5664,
18,
18281,
14432,
203,
5666,
8787,
451,
6909,
4875,
17,
5206,
19,
16351,
87,
19,
2941,
19,
18869,
7957,
18,
18281,
14432,
203,
5666,
8787,
451,
6909,
4875,
17,
5206,
2
]
|
/**
*Submitted for verification at Etherscan.io on 2022-04-28
*/
// SPDX-License-Identifier: MIT
// 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\token\ERC721\IERC721Upgradeable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin\contracts-upgradeable\token\ERC721\IERC721ReceiverUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin\contracts-upgradeable\token\ERC721\extensions\IERC721MetadataUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin\contracts-upgradeable\utils\AddressUpgradeable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin\contracts-upgradeable\proxy\utils\Initializable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// File: @openzeppelin\contracts-upgradeable\utils\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 {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// File: @openzeppelin\contracts-upgradeable\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\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 {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// File: contracts\library\ERC721AUpgradeable.sol
// Creator: Chiru Labs
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
*/
contract ERC721AUpgradeable is ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
// For miscellaneous variable(s) pertaining to the address
// (e.g. number of whitelist mint slots used).
// If there are multiple variables, please pack them into a uint64.
uint64 aux;
}
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
// The number of tokens burned.
uint256 internal _burnCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
function __ERC721AUpgradeable_init(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens.
*/
function totalSupply() public view returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex - _startTokenId() times
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,
// and it is initialized to _startTokenId()
unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "BalanceQueryForZeroAddress");
return uint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
return _addressData[owner].aux;
}
/**
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
_addressData[owner].aux = aux;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert("OwnerQueryForNonexistentToken");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "URIQueryForNonexistentToken");
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return '';
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ownerOf(tokenId);
require(to != owner, "ApprovalToCurrentOwner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ApprovalCallerNotOwnerNorApproved");
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ApprovalQueryForNonexistentToken");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ApproveToCaller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
_transfer(from, to, tokenId);
if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert("TransferToNonERC721ReceiverImplementer");
}
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _startTokenId() <= tokenId && tokenId < _currentIndex &&
!_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
require(to != address(0), "MintToZeroAddress");
require(quantity > 0, "MintZeroQuantity");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
require(_checkContractOnERC721Received(address(0), to, updatedIndex++, _data), "TransferToNonERC721ReceiverImplementer");
} while (updatedIndex != end);
// Reentrancy protection
if (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
require(prevOwnership.addr == from, "TransferFromIncorrectOwner");
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
require(isApprovedOrOwner, "TransferCallerNotOwnerNorApproved");
require(to != address(0), "TransferToZeroAddress");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = to;
currSlot.startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev This is equivalent to _burn(tokenId, false)
*/
function _burn(uint256 tokenId) internal virtual {
_burn(tokenId, false);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
address from = prevOwnership.addr;
if (approvalCheck) {
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
require(isApprovedOrOwner, "TransferCallerNotOwnerNorApproved");
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
AddressData storage addressData = _addressData[from];
addressData.balance -= 1;
addressData.numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = from;
currSlot.startTimestamp = uint64(block.timestamp);
currSlot.burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert ("TransferToNonERC721ReceiverImplementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// File: @openzeppelin\contracts-upgradeable\access\OwnableUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// File: @openzeppelin\contracts-upgradeable\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: contracts\library\AccessControlUpgradeable.sol
pragma solidity ^0.8.0;
abstract contract AccessControlUpgradeable is ContextUpgradeable, OwnableUpgradeable {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
/**
* @dev Emitted when `account` is granted `role`.
*/
event RoleGranted(uint256 indexed role, address indexed account);
/**
* @dev Emitted when `account` is revoked `role`.
*/
event RoleRevoked(uint256 indexed role, address indexed account);
mapping(uint256 => EnumerableSetUpgradeable.AddressSet) private _roles;
function __AccessControlUpgradeable_init() public onlyInitializing {
}
modifier onlyRole(uint256 role) {
require(hasRole(role, _msgSender()), "BEYOND THE PERMISSIONS");
_;
}
modifier onlyRoleOrOwner(uint256 role) {
require(hasRole(role, _msgSender()) || (_msgSender() == owner()), "BEYOND THE PERMISSIONS");
_;
}
function hasRole(uint256 role, address account) public view returns (bool) {
return _roles[role].contains(account);
}
function allAccountOfRole(uint256 role) public view returns (address[] memory) {
return _roles[role].values();
}
function grantRole(uint256 role, address account) public virtual onlyOwner{
_grantRole(role, account);
}
function revokeRole(uint256 role, address account) public virtual onlyOwner {
_revokeRole(role, account);
}
function _grantRole(uint256 role, address account) internal {
if (!hasRole(role, account)) {
_roles[role].add(account);
emit RoleGranted(role, account);
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(uint256 role, address account) internal {
if (hasRole(role, account)) {
_roles[role].remove(account);
emit RoleRevoked(role, account);
}
}
}
// File: @openzeppelin\contracts\utils\introspection\IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin\contracts\token\ERC721\IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin\contracts\token\ERC721\extensions\IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @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: contracts\YoloFox.sol
pragma solidity ^0.8.4;
contract YoloFox is AccessControlUpgradeable, ERC721AUpgradeable {
uint16 public constant TOTAL_MAX_SUPPLY = 5555;
using StringsUpgradeable for uint256;
using AddressUpgradeable for address;
enum UserRole{
NORMAL_USER,
OG_USER,
WL_USER,
ADMIN_USER
}
string private _theBaseUrl;
struct TimeInfoCollection {
uint64 preSaleStartTime;
uint64 preSaleEndTime;
uint64 pubSaleEndTime;
}
TimeInfoCollection private _timeInfoCollection;
struct CountInfoCollection {
uint16 maxPreSaleCount;
uint16 maxAirDropCount;
uint16 airDropMintCount;
uint16 preSaleMintCount;
uint16 pubSaleMintCount;
uint8 OGUserBuyLimit;
uint8 WLUserBuyLimit;
}
CountInfoCollection private _countIntoCollection;
struct PriceInfoCollection {
uint80 OGUserBuyPrice;
uint80 WLUserBuyPrice;
uint80 pubSalePrice;
}
PriceInfoCollection private _priceInfoCollection;
function initialize(
string calldata tokenName,
string calldata tokenSymbol
) public initializer {
__ERC721AUpgradeable_init(tokenName, tokenSymbol);
__Context_init();
__Ownable_init();
}
//==========CONFIG SECTION============
function setBuyLimit(uint8 OGUserBuyLimit, uint8 WLUserBuyLimit) public onlyRoleOrOwner(uint256(UserRole.ADMIN_USER)) {
_countIntoCollection.OGUserBuyLimit = OGUserBuyLimit;
_countIntoCollection.WLUserBuyLimit = WLUserBuyLimit;
}
function getOGUserBuyLimit() public view returns(uint256) {
return _countIntoCollection.OGUserBuyLimit;
}
function getWLUserBuyLimit() public view returns(uint256) {
return _countIntoCollection.WLUserBuyLimit;
}
function setMaxCountLimit(uint16 maxPreSaleCount, uint16 maxAirDropCount) public onlyRoleOrOwner(uint256(UserRole.ADMIN_USER)) {
require(maxPreSaleCount >= _countIntoCollection.preSaleMintCount, "NEW PRESALE MAX SHOULD BE MORE THAN SOLD COUNT");
require(maxAirDropCount >= _countIntoCollection.airDropMintCount, "NEW AIR DROP MAX SHOULD BE MORE THAN AIR DROPED COUNT");
_countIntoCollection.maxPreSaleCount = maxPreSaleCount;
_countIntoCollection.maxAirDropCount = maxAirDropCount;
}
function getMaxPreSaleCount() public view returns(uint256) {
return _countIntoCollection.maxPreSaleCount;
}
function getpreSaleMintCount() public view returns(uint256) {
return _countIntoCollection.preSaleMintCount;
}
function getMaxAirDropCount() public view returns(uint256) {
return _countIntoCollection.maxAirDropCount;
}
function getAirDropMintCount() public view returns(uint256) {
return _countIntoCollection.airDropMintCount;
}
function setPrice(uint80 OGPrice, uint80 WLPrice, uint80 pubSalePrice) public onlyRoleOrOwner(uint256(UserRole.ADMIN_USER)) {
_priceInfoCollection.OGUserBuyPrice = OGPrice;
_priceInfoCollection.WLUserBuyPrice = WLPrice;
_priceInfoCollection.pubSalePrice = pubSalePrice;
}
function getOGUserBuyPrice() public view returns(uint256) {
return _priceInfoCollection.OGUserBuyPrice;
}
function getWLUserBuyPrice() public view returns(uint256) {
return _priceInfoCollection.WLUserBuyPrice;
}
function getPubSalePrice() public view returns(uint256) {
return _priceInfoCollection.pubSalePrice;
}
function setSaleTime(
uint64 presaleStart,
uint64 presaleEnd,
uint64 publicSaleEnd
) external onlyRoleOrOwner(uint256(UserRole.ADMIN_USER)) {
require((presaleStart < presaleEnd) && (presaleEnd < publicSaleEnd), "INVALID SALE TIME");
_timeInfoCollection.preSaleStartTime = presaleStart;
_timeInfoCollection.preSaleEndTime = presaleEnd;
_timeInfoCollection.pubSaleEndTime = publicSaleEnd;
}
function getPreSaleStartTime() public view returns(uint256) {
return _timeInfoCollection.preSaleStartTime;
}
function getPreSaleEndTime() public view returns(uint256) {
return _timeInfoCollection.preSaleEndTime;
}
function getPubSaleEndTime() public view returns(uint256) {
return _timeInfoCollection.pubSaleEndTime;
}
function setBaseUrl(string calldata newBaseUrl) external onlyRoleOrOwner(uint256(UserRole.ADMIN_USER)) {
_theBaseUrl = newBaseUrl;
}
//==========CONFIG SECTION============
//======= MINT SECTION ==========
function airDropMint(address[] calldata toAddrs, uint16[] calldata quantities) external onlyRoleOrOwner(uint256(UserRole.ADMIN_USER)) {
require(toAddrs.length == quantities.length, "THE INPUT ARRAY LENGTHS MUST BE EQUAL");
uint index;
uint16 mintSum;
do {
mintSum += quantities[index++];
} while(index != quantities.length);
require(
(_countIntoCollection.airDropMintCount + mintSum) <= _countIntoCollection.maxAirDropCount,
"AIR DROP COUNT EXCEEDED"
);
unchecked {
_countIntoCollection.airDropMintCount += mintSum;
for(index=0; index<toAddrs.length; index++) {
_safeMint(toAddrs[index], quantities[index]);
}
}
}
function _realLeftCount() internal view returns(uint16) {
return TOTAL_MAX_SUPPLY - _countIntoCollection.maxAirDropCount - _countIntoCollection.preSaleMintCount - _countIntoCollection.pubSaleMintCount;
}
function buy(uint16 count) external payable {
if (block.timestamp >= _timeInfoCollection.preSaleStartTime && block.timestamp < _timeInfoCollection.preSaleEndTime) {
if (hasRole(uint256(UserRole.OG_USER), _msgSender())) {
require(_numberMinted(_msgSender()) + count <= _countIntoCollection.OGUserBuyLimit, "Exceeded");
require(msg.value == _priceInfoCollection.OGUserBuyPrice * count, "InsufficientBalance");
} else if (hasRole(uint256(uint256(UserRole.WL_USER)), _msgSender())) {
require(_numberMinted(_msgSender()) + count <= _countIntoCollection.WLUserBuyLimit, "Exceeded");
require(msg.value == _priceInfoCollection.WLUserBuyPrice * count, "InsufficientBalance");
} else {
revert("PleaseWaitForPublicSale");
}
require(_countIntoCollection.preSaleMintCount + count <= _countIntoCollection.maxPreSaleCount, "Exceeded");
unchecked {
_countIntoCollection.preSaleMintCount += count;
}
_safeMint(_msgSender(), count);
} else if (block.timestamp >= _timeInfoCollection.preSaleEndTime && block.timestamp < _timeInfoCollection.pubSaleEndTime) {
require(count <= _realLeftCount(), "Exceeded");
require(msg.value == _priceInfoCollection.pubSalePrice * count, "InsufficientBalance");
unchecked {
_countIntoCollection.pubSaleMintCount += count;
}
_safeMint(_msgSender(), count);
} else {
revert("NotInSale");
}
}
//======= MINT SECTION ENDS==========
//======= ADMIN OP=================
function addWhiteList(address[] calldata newWhiteList) external onlyRoleOrOwner(uint256(UserRole.ADMIN_USER)) {
for (uint256 index = 0; index < newWhiteList.length; index++) {
_grantRole(uint256(uint256(UserRole.WL_USER)), newWhiteList[index]);
}
}
function removeWhiteList(address[] calldata removedWhiteList) external onlyRoleOrOwner(uint256(UserRole.ADMIN_USER)) {
for (uint256 index = 0; index < removedWhiteList.length; index++) {
_revokeRole(uint256(UserRole.WL_USER), removedWhiteList[index]);
}
}
function addOGList(address[] calldata newOGList) external onlyRoleOrOwner(uint256(UserRole.ADMIN_USER)) {
for (uint256 index = 0; index < newOGList.length; index++) {
_grantRole(uint256(UserRole.OG_USER), newOGList[index]);
}
}
function removeOGList(address[] calldata removedOGList) external onlyRoleOrOwner(uint256(UserRole.ADMIN_USER)) {
for (uint256 index = 0; index < removedOGList.length; index++) {
_revokeRole(uint256(UserRole.OG_USER), removedOGList[index]);
}
}
function takeOutNativeToken(address payable to, uint256 amount) external onlyOwner {
require(amount > 0, "AmountOfWithDrawDreaterThanZero");
require(address(this).balance >= amount, "InsufficientBalance");
to.transfer(amount);
}
//=======ADMIN OP ENDS=================
//=======QUERY OP =================
function queryBuyableCount(address account) external view returns (uint256) {
if (block.timestamp >= _timeInfoCollection.preSaleStartTime && block.timestamp < _timeInfoCollection.preSaleEndTime) {
if (hasRole(uint256(UserRole.OG_USER), account)) {
return
_countIntoCollection.OGUserBuyLimit > _numberMinted(account)
? _countIntoCollection.OGUserBuyLimit - _numberMinted(account)
: 0;
}
if (hasRole(uint256(UserRole.WL_USER), account)) {
return
_countIntoCollection.WLUserBuyLimit > _numberMinted(account)
? _countIntoCollection.WLUserBuyLimit -
_numberMinted(account)
: 0;
}
return 0;
}
if (block.timestamp >= _timeInfoCollection.preSaleEndTime && block.timestamp < _timeInfoCollection.pubSaleEndTime) {
return _realLeftCount();
}
return 0;
}
function queryUserType(address account) external view returns (UserRole) {
if (hasRole(uint256(UserRole.OG_USER), account)) {
return UserRole.OG_USER;
} else if (hasRole(uint256(UserRole.WL_USER), account)) {
return UserRole.WL_USER;
} else {
return UserRole.NORMAL_USER;
}
}
function queryLeft() external view returns (uint256) {
if (block.timestamp < _timeInfoCollection.preSaleStartTime) {
return TOTAL_MAX_SUPPLY;
} else if ((block.timestamp >= _timeInfoCollection.preSaleStartTime) && (block.timestamp < _timeInfoCollection.preSaleEndTime)) {
return _countIntoCollection.maxPreSaleCount - _countIntoCollection.preSaleMintCount;
} else if ((block.timestamp >= _timeInfoCollection.preSaleEndTime) && (block.timestamp < _timeInfoCollection.pubSaleEndTime)) {
return _realLeftCount();
}
return 0;
}
function queryPrice(address account, uint256 count) public view returns (uint256 finalPrice) {
uint256 thePrice;
if (block.timestamp <= _timeInfoCollection.preSaleEndTime) {
if (hasRole(uint256(UserRole.OG_USER), account)) {
thePrice = _priceInfoCollection.OGUserBuyPrice;
} else if (hasRole(uint256(UserRole.WL_USER), account)) {
thePrice = _priceInfoCollection.WLUserBuyPrice;
} else {
thePrice = _priceInfoCollection.pubSalePrice;
}
} else {
thePrice = _priceInfoCollection.pubSalePrice;
}
finalPrice = thePrice * count;
}
function _baseURI() internal view override returns (string memory) {
return _theBaseUrl;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner_, uint256 index) public view returns (uint256) {
require(index < balanceOf(owner_), "OwnerIndexOutOfBounds");
uint256 count;
address ownerOfCurrentToken;
for (uint256 i = _startTokenId(); i < _currentIndex; ++i) {
address user = _ownerships[i].addr;
if (!_ownerships[i].burned) {
if (user != address(0)) {
ownerOfCurrentToken = user;
}
if (ownerOfCurrentToken == owner_) {
if (index == count) return i;
count++;
}
}
}
revert("ERROR");
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply(), "GlobalIndexOutOfBounds");
uint256 count;
for (uint256 i = _startTokenId(); i < _currentIndex; ++i) {
if (!_ownerships[i].burned) {
if (index == count) return i;
count++;
}
}
revert("ERROR");
}
//=======QUERY OP ENDS=================
} | * @dev See {IERC721-setApprovalForAll}./ | function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ApproveToCaller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
| 2,350,932 | [
1,
9704,
288,
45,
654,
39,
27,
5340,
17,
542,
23461,
1290,
1595,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
444,
23461,
1290,
1595,
12,
2867,
3726,
16,
1426,
20412,
13,
1071,
5024,
3849,
288,
203,
3639,
2583,
12,
9497,
480,
389,
3576,
12021,
9334,
315,
12053,
537,
774,
11095,
8863,
203,
203,
3639,
389,
9497,
12053,
4524,
63,
67,
3576,
12021,
1435,
6362,
9497,
65,
273,
20412,
31,
203,
3639,
3626,
1716,
685,
1125,
1290,
1595,
24899,
3576,
12021,
9334,
3726,
16,
20412,
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
]
|
pragma solidity ^0.4.24;
// Author: Bruno Block
// Version: 0.5
interface contractInterface {
function balanceOf(address _owner) external constant returns (uint256 balance);
function transfer(address _to, uint256 _value) external;
}
contract DualSig {
address public directorA;
address public directorB;
address public proposalAuthor;
address public proposalContract;
address public proposalDestination;
uint256 public proposalAmount;
uint256 public proposalBlock;
uint256 public proposalNonce;
uint256 public overrideBlock;
uint256 public transferSafety;
event Proposal(uint256 _nonce, address _author, address _contract, uint256 _amount, address _destination, uint256 _timestamp);
event Accept(uint256 _nonce);
event NewDirectorA(address _director);
event NewDirectorB(address _director);
modifier onlyDirectors {
require(msg.sender == directorA || msg.sender == directorB);
_;
}
constructor() public {
overrideBlock = (60*60*24*30)/15;// One month override interval assuming 15 second blocks (172,800 blocks)
proposalNonce = 0;
transferSafety = 1 ether;
directorA = msg.sender;
directorB = msg.sender;
reset();
}
function () public payable {}
function proposal(address proposalContractSet, uint256 proposalAmountSet, address proposalDestinationSet) public onlyDirectors {
proposalNonce++;
proposalAuthor = msg.sender;
proposalContract = proposalContractSet;
proposalAmount = proposalAmountSet;
proposalDestination = proposalDestinationSet;
proposalBlock = block.number + overrideBlock;
emit Proposal(proposalNonce, proposalAuthor, proposalContract, proposalAmount, proposalDestination, proposalBlock);
}
function reset() public onlyDirectors {
proposalNonce++;
if (proposalNonce > 1000000) {
proposalNonce = 0;
}
proposalAuthor = 0x0;
proposalContract = 0x0;
proposalAmount = 0;
proposalDestination = 0x0;
proposalBlock = 0;
}
function accept(uint256 acceptNonce) public onlyDirectors {
require(proposalNonce == acceptNonce);
require(proposalAmount > 0);
require(proposalDestination != 0x0);
require(proposalAuthor != msg.sender || block.number >= proposalBlock);
address localContract = proposalContract;
address localDestination = proposalDestination;
uint256 localAmount = proposalAmount;
reset();
if (localContract==0x0) {
require(localAmount <= address(this).balance);
localDestination.transfer(localAmount);
}
else {
contractInterface tokenContract = contractInterface(localContract);
tokenContract.transfer(localDestination, localAmount);
}
emit Accept(acceptNonce);
}
function transferDirectorA(address newDirectorA) public payable {
require(msg.sender==directorA);
require(msg.value==transferSafety);// Prevents accidental transfer
directorA.transfer(transferSafety);// Reimburse safety deposit
reset();
directorA = newDirectorA;
emit NewDirectorA(directorA);
}
function transferDirectorB(address newDirectorB) public payable {
require(msg.sender==directorB);
require(msg.value==transferSafety);// Prevents accidental transfer
directorB.transfer(transferSafety);// Reimburse safety deposit
reset();
directorB = newDirectorB;
emit NewDirectorB(directorB);
}
} | One month override interval assuming 15 second blocks (172,800 blocks)
| overrideBlock = (60*60*24*30)/15; | 6,594,914 | [
1,
3335,
3138,
3849,
3673,
15144,
4711,
2205,
4398,
261,
28406,
16,
17374,
4398,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
3849,
1768,
273,
261,
4848,
14,
4848,
14,
3247,
14,
5082,
13176,
3600,
31,
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
]
|
pragma solidity ^0.4.4;
contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
//if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
//if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
//name this contract whatever you'd like
contract ERC20Token is StandardToken {
function () {
//if ether is sent to this address, send it back.
throw;
}
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme.
//
// CHANGE THESE VALUES FOR YOUR TOKEN
//
//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token
function ERC20Token(
) {
balances[msg.sender] = 10000000; // Give the creator all initial tokens (100000 for example)
totalSupply = 10000000; // Update total supply (100000 for example)
name = "International Rapid Asset"; // Set the name for display purposes
decimals = 0; // Amount of decimals for display purposes
symbol = "IRA"; // Set the symbol for display purposes
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | Set the name for display purposes
| name = "International Rapid Asset"; | 1,736,968 | [
1,
694,
326,
508,
364,
2562,
13694,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
508,
273,
315,
21843,
8371,
534,
438,
350,
10494,
14432,
4766,
565,
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
]
|
/**
*Submitted for verification at Etherscan.io on 2021-03-03
*/
// File: @openzeppelin/upgrades/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: contracts/ERC/ERC20Interface.sol
pragma solidity ^0.5.0;
/** ----------------------------------------------------------------------------
* @title ERC Token Standard #20 Interface
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* ----------------------------------------------------------------------------
*/
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed tokenOwner, address indexed spender, uint value);
}
// File: contracts/libs/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @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];
}
}
// File: contracts/libs/Ownable.sol
pragma solidity ^0.5.0;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "Ownable: sender is not owner");
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
owner = address(0);
emit OwnershipRenounced(owner);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0), "Ownable: transfer to zero address");
owner = _newOwner;
emit OwnershipTransferred(owner, _newOwner);
}
}
// File: contracts/libs/AccessControl.sol
pragma solidity ^0.5.0;
contract AccessControl is Ownable {
using Roles for Roles.Role;
//Contract admins
Roles.Role internal _admins;
// Events
event AddedAdmin(address _address);
event DeletedAdmin(address _addess);
function addAdmin(address newAdmin) public onlyOwner {
require(newAdmin != address(0), "AccessControl: Invalid new admin address");
_admins.add(newAdmin);
emit AddedAdmin(newAdmin);
}
function deletedAdmin(address deleteAdmin) public onlyOwner {
require(deleteAdmin != address(0), "AccessControl: Invalid new admin address");
_admins.remove(deleteAdmin);
emit DeletedAdmin(deleteAdmin);
}
}
// File: contracts/ERC/ERC20.sol
pragma solidity ^0.5.0;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
*/
contract ERC20 is ERC20Interface, AccessControl {
using SafeMath for uint256;
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => uint256)) internal _allowed;
uint256 internal _totalSupply;
event Burn(address indexed burner, uint256 value);
// Modifiers
modifier onlyOwnerOrAdmin() {
require(msg.sender == owner || _admins.has(msg.sender), "ERC20: sender is not owner or admin");
_;
}
// Functions
/**
* @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) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(value <= _allowed[from][msg.sender], "ERC20: account balance is lower than amount");
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* @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(addedValue > 0, "ERC20: value must be bigger than zero");
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* @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(subtractedValue > 0, "ERC20: value must be bigger than zero");
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "ERC20: value must be bigger than zero");
require(amount <= _balances[account], "ERC20: account balance is lower than amount");
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
emit Transfer(account, address(0), amount);
emit Burn(account, amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burnFrom(address account, uint256 amount) internal {
require(account != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "ERC20: value must be bigger than zero");
require(amount <= _allowed[account][msg.sender] || _admins.has(msg.sender), "ERC20: account allowed balance is lower than amount");
_burn(account, amount);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(amount));
}
/**
* @dev Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint256 value) internal {
require(_from != address(0), "ERC20: transfer to the zero address");
require(_to != address(0), "ERC20: transfer to the zero address");
require(value > 0, "ERC20: value must be bigger than zero");
require(value <= _balances[_from], "ERC20: balances from must be bigger than transfer amount");
require(_balances[_to] < _balances[_to] + value, "ERC20: value must be bigger than zero");
_balances[_from] = _balances[_from].sub(value);
_balances[_to] = _balances[_to].add(value);
emit Transfer(_from, _to, value);
}
/**
* @dev Internal function, minting new tokens
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
require(amount > 0, "ERC20: value must be bigger than zero");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
_allowed[account][account] = _balances[account];
emit Transfer(address(0), account, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowed[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
// File: contracts/libs/MintableToken.sol
pragma solidity ^0.5.0;
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120
*/
contract MintableToken is ERC20 {
event Mint(address indexed to, uint256 amount);
event MintFinished();
event MintStarted();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished, "MintableToken: minting is finished");
_;
}
modifier hasMintPermission() {
require(msg.sender == owner || _admins.has(msg.sender), "MintableToken: sender has not permissions");
_;
}
/**
* @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 this indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) public hasMintPermission canMint returns (bool) {
_mint(_to, _amount);
emit Mint(_to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwnerOrAdmin canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
function startMinting() public onlyOwnerOrAdmin returns (bool) {
mintingFinished = false;
emit MintStarted();
return true;
}
}
// File: contracts/libs/FreezableToken.sol
pragma solidity ^0.5.0;
/**
* @title Freezable token
* @dev Add ability froze accounts
*/
contract FreezableToken is MintableToken {
mapping(address => bool) public frozenAccounts;
event FrozenFunds(address target, bool frozen);
/**
* @dev Freze account
*/
function freezeAccount(address target, bool freeze) public onlyOwnerOrAdmin {
frozenAccounts[target] = freeze;
emit FrozenFunds(target, freeze);
}
/**
* @dev Ovveride base method _transfer from base ERC20 contract
*/
function _transfer(address _from, address _to, uint256 value) internal {
require(_to != address(0x0), "FreezableToken: transfer to the zero address");
require(_balances[_from] >= value, "FreezableToken: balance _from must br bigger than value");
require(_balances[_to] + value >= _balances[_to], "FreezableToken: balance to must br bigger than current balance");
require(!frozenAccounts[_from], "FreezableToken: account _from is frozen");
require(!frozenAccounts[_to], "FreezableToken: account _to is frozen");
_balances[_from] = _balances[_from].sub(value);
_balances[_to] = _balances[_to].add(value);
emit Transfer(_from, _to, value);
}
}
// File: contracts/libs/Pausable.sol
pragma solidity ^0.5.0;
/**
* @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, "Pausable: contract paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused, "Pausable: contract not paused");
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
// File: contracts/MainContract.sol
pragma solidity ^0.5.0;
/**
* @title Contract constants
* @dev Contract whose consisit base constants for contract
*/
contract ContractConstants {
uint256 internal TOKEN_BUY_PRICE;
uint256 internal TOKEN_BUY_PRICE_DECIMAL;
uint256 internal TOKENS_BUY_LIMIT;
}
/**
* @title MainContract
* @dev Base contract which using for initializing new contract
*/
contract MainContract is ContractConstants, FreezableToken, Pausable {
string private _name;
string private _symbol;
uint private _decimals;
uint private _decimalsMultiplier;
uint256 internal buyPrice;
uint256 internal buyPriceDecimals;
uint256 internal buyTokensLimit;
uint256 internal boughtTokensByCurrentPrice;
uint256 internal membersCount;
event Buy(address target, uint256 eth, uint256 tokens);
event NewLimit(uint256 prevLimit, uint256 newLimit);
event SetNewPrice(uint256 prevPrice, uint256 newPrice);
/**
* @return get token name
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return get token symbol
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return get token decimals
*/
function decimals() public view returns (uint) {
return _decimals;
}
/**
* @return return buy price
*/
function getBuyPrice() public view returns (uint256) {
return buyPrice;
}
/**
* @return return buy price decimals
*/
function getBuyPriceDecimals() public view returns (uint256) {
return buyPriceDecimals;
}
/**
* @return return count mebers
*/
function getMembersCount() public view returns (uint256) {
return membersCount;
}
/**
* @return return payable function buy limit
*/
function getBuyTokensLimit() public view returns (uint256) {
return buyTokensLimit;
}
/**
* @return return count of bought tokens for current price
*/
function getBoughtTokensByCurrentPrice() public view returns (uint256) {
return boughtTokensByCurrentPrice;
}
/**
* @dev set prices for sell tokens and buy tokens
*/
function setPrices(uint256 newBuyPrice) public onlyOwnerOrAdmin {
emit SetNewPrice(buyPrice, newBuyPrice);
buyPrice = newBuyPrice;
boughtTokensByCurrentPrice = 0;
}
/**
* @dev set max buy tokens
*/
function setLimit(uint256 newLimit) public onlyOwnerOrAdmin {
emit NewLimit(buyTokensLimit, newLimit);
buyTokensLimit = newLimit;
}
/**
* @dev set limit and reset price
*/
function setLimitAndPrice(uint256 newLimit, uint256 newBuyPrice) public onlyOwnerOrAdmin {
setLimit(newLimit);
setPrices(newBuyPrice);
}
/**
* @dev set prices for sell tokens and buy tokens
*/
function setPricesDecimals(uint256 newBuyDecimal) public onlyOwnerOrAdmin {
buyPriceDecimals = newBuyDecimal;
}
/**
* @dev override base method transferFrom
*/
function transferFrom(address _from, address _to, uint256 value) public whenNotPaused returns (bool _success) {
return super.transferFrom(_from, _to, value);
}
/**
* @dev Override base method transfer
*/
function transfer(address _to, uint256 value) public whenNotPaused returns (bool _success) {
return super.transfer(_to, value);
}
/**
* @dev Override base method increaseAllowance
*/
function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) {
return super.increaseAllowance(spender, addedValue);
}
/**
* @dev Override base method decreaseAllowance
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) {
return super.decreaseAllowance(spender, subtractedValue);
}
/**
* @dev Override base method approve
*/
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
/**
* @dev Burn user tokens
*/
function burn(uint256 _value) public whenNotPaused {
_burn(msg.sender, _value);
}
/**
* @dev Burn users tokens with allowance
*/
function burnFrom(address account, uint256 _value) public whenNotPaused {
_burnFrom(account, _value);
}
/**
* @dev Mint tokens by owner
*/
function addTokens(uint256 _amount) public hasMintPermission canMint {
_mint(msg.sender, _amount);
emit Mint(msg.sender, _amount);
}
/**
* @dev Function whose calling on initialize contract
*/
function init(string memory __name, string memory __symbol, uint __decimals, uint __totalSupply, address __owner, address __admin) public {
_name = __name;
_symbol = __symbol;
_decimals = __decimals;
_decimalsMultiplier = 10 ** _decimals;
if (paused) {
pause();
}
setPrices(TOKEN_BUY_PRICE);
setPricesDecimals(TOKEN_BUY_PRICE_DECIMAL);
uint256 generateTokens = __totalSupply * _decimalsMultiplier;
setLimit(TOKENS_BUY_LIMIT);
if (generateTokens > 0) {
mint(__owner, generateTokens);
approve(__owner, balanceOf(__owner));
}
addAdmin(__admin);
transferOwnership(__owner);
}
function() external payable {
buy(msg.sender, msg.value);
}
function calculateBuyTokens(uint256 _value) public view returns (uint256) {
uint256 buyDecimal = 10 ** buyPriceDecimals;
return (_value * _decimalsMultiplier) / (buyPrice * buyDecimal);
}
/**
* @dev buy tokens
*/
function buy(address _sender, uint256 _value) internal {
require(_value > 0, 'MainContract: Value must be bigger than zero');
require(buyPrice > 0, 'MainContract: Cannot buy tokens');
require(boughtTokensByCurrentPrice < buyTokensLimit, 'MainContract: Cannot buy tokens more than current limit');
uint256 amount = this.calculateBuyTokens(_value);
if (boughtTokensByCurrentPrice + amount > buyTokensLimit) {
amount = buyTokensLimit - boughtTokensByCurrentPrice;
}
membersCount = membersCount.add(1);
_transfer(owner, _sender, amount);
boughtTokensByCurrentPrice = boughtTokensByCurrentPrice.add(amount);
address(uint160(owner)).transfer(_value);
emit Buy(_sender, _value, amount);
}
}
// File: contracts/Esillium.sol
pragma solidity ^0.5.0;
contract Esillium is MainContract, Initializable {
constructor () public {initialize();}
function initialize() public initializer {
owner = msg.sender;
// First stage config, ETH/USD price : 1605.73
TOKEN_BUY_PRICE = 31172;
TOKEN_BUY_PRICE_DECIMAL = 10;
TOKENS_BUY_LIMIT = 359200000000;
init('Esillium', '8YB', 5, 7000000000, 0x158ad714bc7BEeaD490960eCB382717FA36Ef926, 0x51b8Aa6616B868a4F36b0b3C6Db46B015c5467D6);
}
} | * @dev Mint tokens by owner/ | function addTokens(uint256 _amount) public hasMintPermission canMint {
_mint(msg.sender, _amount);
emit Mint(msg.sender, _amount);
}
| 2,305,033 | [
1,
49,
474,
2430,
635,
3410,
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,
527,
5157,
12,
11890,
5034,
389,
8949,
13,
1071,
711,
49,
474,
5041,
848,
49,
474,
288,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
389,
8949,
1769,
203,
3639,
3626,
490,
474,
12,
3576,
18,
15330,
16,
389,
8949,
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
]
|
pragma solidity 0.4.18;
contract CrowdsaleParameters {
// Vesting time stamps:
// 1534672800 = August 19, 2018. 180 days from February 20, 2018. 10:00:00 GMT
// 1526896800 = May 21, 2018. 90 days from February 20, 2018. 10:00:00 GMT
uint32 internal vestingTime90Days = 1526896800;
uint32 internal vestingTime180Days = 1534672800;
uint256 internal constant presaleStartDate = 1513072800; // Dec-12-2017 10:00:00 GMT
uint256 internal constant presaleEndDate = 1515751200; // Jan-12-2018 10:00:00 GMT
uint256 internal constant generalSaleStartDate = 1516442400; // Jan-20-2018 00:00:00 GMT
uint256 internal constant generalSaleEndDate = 1519120800; // Feb-20-2018 00:00:00 GMT
struct AddressTokenAllocation {
address addr;
uint256 amount;
uint256 vestingTS;
}
AddressTokenAllocation internal presaleWallet = AddressTokenAllocation(0x43C5FB6b419E6dF1a021B9Ad205A18369c19F57F, 100e6, 0);
AddressTokenAllocation internal generalSaleWallet = AddressTokenAllocation(0x0635c57CD62dA489f05c3dC755bAF1B148FeEdb0, 550e6, 0);
AddressTokenAllocation internal wallet1 = AddressTokenAllocation(0xae46bae68D0a884812bD20A241b6707F313Cb03a, 20e6, vestingTime180Days);
AddressTokenAllocation internal wallet2 = AddressTokenAllocation(0xfe472389F3311e5ea19B4Cd2c9945b6D64732F13, 20e6, vestingTime180Days);
AddressTokenAllocation internal wallet3 = AddressTokenAllocation(0xE37dfF409AF16B7358Fae98D2223459b17be0B0B, 20e6, vestingTime180Days);
AddressTokenAllocation internal wallet4 = AddressTokenAllocation(0x39482f4cd374D0deDD68b93eB7F3fc29ae7105db, 10e6, vestingTime180Days);
AddressTokenAllocation internal wallet5 = AddressTokenAllocation(0x03736d5B560fE0784b0F5c2D0eA76A7F15E5b99e, 5e6, vestingTime180Days);
AddressTokenAllocation internal wallet6 = AddressTokenAllocation(0xD21726226c32570Ab88E12A9ac0fb2ed20BE88B9, 5e6, vestingTime180Days);
AddressTokenAllocation internal foundersWallet = AddressTokenAllocation(0xC66Cbb7Ba88F120E86920C0f85A97B2c68784755, 30e6, vestingTime90Days);
AddressTokenAllocation internal wallet7 = AddressTokenAllocation(0x24ce108d1975f79B57c6790B9d4D91fC20DEaf2d, 6e6, 0);
AddressTokenAllocation internal wallet8genesis = AddressTokenAllocation(0x0125c6Be773bd90C0747012f051b15692Cd6Df31, 5e6, 0);
AddressTokenAllocation internal wallet9 = AddressTokenAllocation(0xFCF0589B6fa8A3f262C4B0350215f6f0ed2F630D, 5e6, 0);
AddressTokenAllocation internal wallet10 = AddressTokenAllocation(0x0D016B233e305f889BC5E8A0fd6A5f99B07F8ece, 4e6, 0);
AddressTokenAllocation internal wallet11bounty = AddressTokenAllocation(0x68433cFb33A7Fdbfa74Ea5ECad0Bc8b1D97d82E9, 19e6, 0);
AddressTokenAllocation internal wallet12 = AddressTokenAllocation(0xd620A688adA6c7833F0edF48a45F3e39480149A6, 4e6, 0);
AddressTokenAllocation internal wallet13rsv = AddressTokenAllocation(0x8C393F520f75ec0F3e14d87d67E95adE4E8b16B1, 100e6, 0);
AddressTokenAllocation internal wallet14partners = AddressTokenAllocation(0x6F842b971F0076C4eEA83b051523d76F098Ffa52, 96e6, 0);
AddressTokenAllocation internal wallet15lottery = AddressTokenAllocation(0xcaA48d91D49f5363B2974bb4B2DBB36F0852cf83, 1e6, 0);
uint256 public minimumICOCap = 3333;
}
contract Owned {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* Constructor
*
* Sets contract owner to address of constructor caller
*/
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* Change Owner
*
* Changes ownership of this contract. Only owner can call this method.
*
* @param newOwner - new owner's address
*/
function changeOwner(address newOwner) onlyOwner public {
require(newOwner != address(0));
require(newOwner != owner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract TKLNToken is Owned, CrowdsaleParameters {
/* Public variables of the token */
string public standard = 'Token 0.1';
string public name = 'Taklimakan';
string public symbol = 'TKLN';
uint8 public decimals = 18;
/* Arrays of all balances, vesting, approvals, and approval uses */
mapping (address => uint256) private balances; // Total token balances
mapping (address => uint256) private balances90dayFreeze; // Balances frozen for 90 days after ICO end
mapping (address => uint256) private balances180dayFreeze; // Balances frozen for 180 days after ICO end
mapping (address => uint) private vestingTimesForPools;
mapping (address => mapping (address => uint256)) private allowed;
mapping (address => mapping (address => bool)) private allowanceUsed;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
event Transfer(address indexed spender, address indexed from, address indexed to, uint256 value);
event VestingTransfer(address indexed from, address indexed to, uint256 value, uint256 vestingTime);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Issuance(uint256 _amount); // triggered when the total supply is increased
event Destruction(uint256 _amount); // triggered when the total supply is decreased
event NewTKLNToken(address _token);
/* Miscellaneous */
uint256 public totalSupply = 0;
bool public transfersEnabled = true;
/**
* Constructor
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TKLNToken() public {
owner = msg.sender;
mintToken(presaleWallet);
mintToken(generalSaleWallet);
mintToken(wallet1);
mintToken(wallet2);
mintToken(wallet3);
mintToken(wallet4);
mintToken(wallet5);
mintToken(wallet6);
mintToken(foundersWallet);
mintToken(wallet7);
mintToken(wallet8genesis);
mintToken(wallet9);
mintToken(wallet10);
mintToken(wallet11bounty);
mintToken(wallet12);
mintToken(wallet13rsv);
mintToken(wallet14partners);
mintToken(wallet15lottery);
NewTKLNToken(address(this));
}
modifier transfersAllowed {
require(transfersEnabled);
_;
}
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
/**
* 1. Associate crowdsale contract address with this Token
* 2. Allocate general sale amount
*
* @param _crowdsaleAddress - crowdsale contract address
*/
function approveCrowdsale(address _crowdsaleAddress) external onlyOwner {
approveAllocation(generalSaleWallet, _crowdsaleAddress);
}
/**
* 1. Associate pre-sale contract address with this Token
* 2. Allocate presale amount
*
* @param _presaleAddress - pre-sale contract address
*/
function approvePresale(address _presaleAddress) external onlyOwner {
approveAllocation(presaleWallet, _presaleAddress);
}
function approveAllocation(AddressTokenAllocation tokenAllocation, address _crowdsaleAddress) internal {
uint uintDecimals = decimals;
uint exponent = 10**uintDecimals;
uint amount = tokenAllocation.amount * exponent;
allowed[tokenAllocation.addr][_crowdsaleAddress] = amount;
Approval(tokenAllocation.addr, _crowdsaleAddress, amount);
}
/**
* Get token balance of an address
*
* @param _address - address to query
* @return Token balance of _address
*/
function balanceOf(address _address) public constant returns (uint256 balance) {
return balances[_address];
}
/**
* Get vested token balance of an address
*
* @param _address - address to query
* @return balance that has vested
*/
function vestedBalanceOf(address _address) public constant returns (uint256 balance) {
return balances[_address] - balances90dayFreeze[_address] - balances180dayFreeze[_address];
}
/**
* Get token amount allocated for a transaction from _owner to _spender addresses
*
* @param _owner - owner address, i.e. address to transfer from
* @param _spender - spender address, i.e. address to transfer to
* @return Remaining amount allowed to be transferred
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* Send coins from sender's address to address specified in parameters
*
* @param _to - address to send to
* @param _value - amount to send in Wei
*/
function transfer(address _to, uint256 _value) public transfersAllowed onlyPayloadSize(2*32) returns (bool success) {
updateVesting(msg.sender);
require(vestedBalanceOf(msg.sender) >= _value);
// Subtract from the sender
// _value is never greater than balance of input validation above
balances[msg.sender] -= _value;
// If tokens issued from this address need to vest (i.e. this address is a pool), freeze them here
if (vestingTimesForPools[msg.sender] > 0) {
addToVesting(msg.sender, _to, vestingTimesForPools[msg.sender], _value);
}
// Overflow is never possible due to input validation above
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
/**
* Create token and credit it to target address
* Created tokens need to vest
*
*/
function mintToken(AddressTokenAllocation tokenAllocation) internal {
// Add vesting time for this pool
vestingTimesForPools[tokenAllocation.addr] = tokenAllocation.vestingTS;
uint uintDecimals = decimals;
uint exponent = 10**uintDecimals;
uint mintedAmount = tokenAllocation.amount * exponent;
// Mint happens right here: Balance becomes non-zero from zero
balances[tokenAllocation.addr] += mintedAmount;
totalSupply += mintedAmount;
// Emit Issue and Transfer events
Issuance(mintedAmount);
Transfer(address(this), tokenAllocation.addr, mintedAmount);
}
/**
* Allow another contract to spend some tokens on your behalf
*
* @param _spender - address to allocate tokens for
* @param _value - number of tokens to allocate
* @return True in case of success, otherwise false
*/
function approve(address _spender, uint256 _value) public onlyPayloadSize(2*32) returns (bool success) {
require(_value == 0 || allowanceUsed[msg.sender][_spender] == false);
allowed[msg.sender][_spender] = _value;
allowanceUsed[msg.sender][_spender] = false;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* Allow another contract to spend some tokens on your behalf
*
* @param _spender - address to allocate tokens for
* @param _currentValue - current number of tokens approved for allocation
* @param _value - number of tokens to allocate
* @return True in case of success, otherwise false
*/
function approve(address _spender, uint256 _currentValue, uint256 _value) public onlyPayloadSize(3*32) returns (bool success) {
require(allowed[msg.sender][_spender] == _currentValue);
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* A contract attempts to get the coins. Tokens should be previously allocated
*
* @param _to - address to transfer tokens to
* @param _from - address to transfer tokens from
* @param _value - number of tokens to transfer
* @return True in case of success, otherwise false
*/
function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed onlyPayloadSize(3*32) returns (bool success) {
updateVesting(_from);
// Check if the sender has enough
require(vestedBalanceOf(_from) >= _value);
// Check allowed
require(_value <= allowed[_from][msg.sender]);
// Subtract from the sender
// _value is never greater than balance because of input validation above
balances[_from] -= _value;
// Add the same to the recipient
// Overflow is not possible because of input validation above
balances[_to] += _value;
// Deduct allocation
// _value is never greater than allowed amount because of input validation above
allowed[_from][msg.sender] -= _value;
// If tokens issued from this address need to vest (i.e. this address is a pool), freeze them here
if (vestingTimesForPools[_from] > 0) {
addToVesting(_from, _to, vestingTimesForPools[_from], _value);
}
Transfer(msg.sender, _from, _to, _value);
allowanceUsed[_from][msg.sender] = true;
return true;
}
/**
* Default method
*
* This unnamed function is called whenever someone tries to send ether to
* it. Just revert transaction because there is nothing that Token can do
* with incoming ether.
*
* Missing payable modifier prevents accidental sending of ether
*/
function() public {
}
/**
* Enable or disable transfers
*
* @param _enable - True = enable, False = disable
*/
function toggleTransfers(bool _enable) external onlyOwner {
transfersEnabled = _enable;
}
/**
* Destroy unsold preICO tokens
*
*/
function closePresale() external onlyOwner {
// Destroyed amount is never greater than total supply,
// so no underflow possible here
uint destroyedAmount = balances[presaleWallet.addr];
totalSupply -= destroyedAmount;
balances[presaleWallet.addr] = 0;
Destruction(destroyedAmount);
Transfer(presaleWallet.addr, 0x0, destroyedAmount);
}
/**
* Destroy unsold general sale tokens
*
*/
function closeGeneralSale() external onlyOwner {
// Destroyed amount is never greater than total supply,
// so no underflow possible here
uint destroyedAmount = balances[generalSaleWallet.addr];
totalSupply -= destroyedAmount;
balances[generalSaleWallet.addr] = 0;
Destruction(destroyedAmount);
Transfer(generalSaleWallet.addr, 0x0, destroyedAmount);
}
function addToVesting(address _from, address _target, uint256 _vestingTime, uint256 _amount) internal {
if (CrowdsaleParameters.vestingTime90Days == _vestingTime) {
balances90dayFreeze[_target] += _amount;
VestingTransfer(_from, _target, _amount, _vestingTime);
} else if (CrowdsaleParameters.vestingTime180Days == _vestingTime) {
balances180dayFreeze[_target] += _amount;
VestingTransfer(_from, _target, _amount, _vestingTime);
}
}
function updateVesting(address sender) internal {
if (CrowdsaleParameters.vestingTime90Days < now) {
balances90dayFreeze[sender] = 0;
}
if (CrowdsaleParameters.vestingTime180Days < now) {
balances180dayFreeze[sender] = 0;
}
}
} | Dec-12-2017 10:00:00 GMT
| uint256 internal constant presaleStartDate = 1513072800; | 2,551,308 | [
1,
1799,
17,
2138,
17,
31197,
1728,
30,
713,
30,
713,
21706,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
2713,
5381,
4075,
5349,
22635,
273,
4711,
3437,
8642,
6030,
713,
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
]
|
./partial_match/5/0xe27e65bF9BDc148c6248B495386571fD49410f27/sources/LoanETH.sol | send eth back for change
| msg.sender.transfer(changeETH); | 16,891,983 | [
1,
4661,
13750,
1473,
364,
2549,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1234,
18,
15330,
18,
13866,
12,
3427,
1584,
44,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: BlueOak-1.0.0
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "contracts/plugins/assets/abstract/CompoundOracleMixin.sol";
import "contracts/plugins/assets/abstract/SelfReferentialCollateral.sol";
// ==== External Interfaces ====
// See: https://github.com/compound-finance/compound-protocol/blob/master/contracts/CToken.sol
interface ICToken {
/// @dev From Compound Docs:
/// The current (up to date) exchange rate, scaled by 10^(18 - 8 + Underlying Token Decimals).
function exchangeRateCurrent() external returns (uint256);
/// @dev From Compound Docs: The stored exchange rate, with 18 - 8 + UnderlyingAsset.Decimals.
function exchangeRateStored() external view returns (uint256);
}
/**
* @title CTokenSelfReferentialCollateral
* @notice Collateral plugin for a cToken of a self-referential asset. For example:
* - cETH
* - cRSR
* - ...
*/
contract CTokenSelfReferentialCollateral is CompoundOracleMixin, SelfReferentialCollateral {
using FixLib for uint192;
// All cTokens have 8 decimals, but their underlying may have 18 or 6 or something else.
// Default Status:
// whenDefault == NEVER: no risk of default (initial value)
// whenDefault > block.timestamp: delayed default may occur as soon as block.timestamp.
// In this case, the asset may recover, reachiving whenDefault == NEVER.
// whenDefault <= block.timestamp: default has already happened (permanently)
uint256 internal constant NEVER = type(uint256).max;
uint256 public whenDefault = NEVER;
IERC20Metadata public referenceERC20;
uint192 public prevReferencePrice; // previous rate, {collateral/reference}
IERC20 public override rewardERC20;
string public oracleLookupSymbol;
constructor(
IERC20Metadata erc20_,
uint192 maxTradeVolume_,
IERC20Metadata referenceERC20_,
IComptroller comptroller_,
IERC20 rewardERC20_,
string memory targetName_
)
SelfReferentialCollateral(erc20_, maxTradeVolume_, bytes32(bytes(targetName_)))
CompoundOracleMixin(comptroller_)
{
referenceERC20 = referenceERC20_;
rewardERC20 = rewardERC20_;
prevReferencePrice = refPerTok(); // {collateral/reference}
oracleLookupSymbol = targetName_;
}
/// @return {UoA/tok} Our best guess at the market price of 1 whole token in UoA
function price() public view returns (uint192) {
// {UoA/tok} = {UoA/ref} * {ref/tok}
return consultOracle(oracleLookupSymbol).mul(refPerTok());
}
/// Refresh exchange rates and update default status.
/// @custom:interaction RCEI
function refresh() external virtual override {
// == Refresh ==
// Update the Compound Protocol
ICToken(address(erc20)).exchangeRateCurrent();
if (whenDefault <= block.timestamp) return;
uint256 oldWhenDefault = whenDefault;
// Check for hard default
uint192 referencePrice = refPerTok();
if (referencePrice.lt(prevReferencePrice)) {
whenDefault = block.timestamp;
emit DefaultStatusChanged(oldWhenDefault, whenDefault, status());
}
prevReferencePrice = referencePrice;
// No interactions beyond the initial refresher
}
/// @return The collateral's status
function status() public view override returns (CollateralStatus) {
if (whenDefault == NEVER) {
return CollateralStatus.SOUND;
} else if (whenDefault <= block.timestamp) {
return CollateralStatus.DISABLED;
} else {
return CollateralStatus.IFFY;
}
}
/// @return {ref/tok} Quantity of whole reference units per whole collateral tokens
function refPerTok() public view override returns (uint192) {
uint256 rate = ICToken(address(erc20)).exchangeRateStored();
int8 shiftLeft = 8 - int8(referenceERC20.decimals()) - 18;
return shiftl_toFix(rate, shiftLeft);
}
/// @return {UoA/target} The price of a target unit in UoA
function pricePerTarget() public view override returns (uint192) {
return consultOracle(oracleLookupSymbol);
}
/// Get the message needed to call in order to claim rewards for holding this asset.
/// @return _to The address to send the call to
/// @return _cd The calldata to send
function getClaimCalldata() external view override returns (address _to, bytes memory _cd) {
_to = address(comptroller);
_cd = abi.encodeWithSignature("claimComp(address)", msg.sender);
}
}
| ==== External Interfaces ==== See: https:github.com/compound-finance/compound-protocol/blob/master/contracts/CToken.sol | interface ICToken {
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
pragma solidity 0.8.9;
}
| 12,922,189 | [
1,
894,
11352,
27152,
422,
631,
2164,
30,
2333,
30,
6662,
18,
832,
19,
22585,
17,
926,
1359,
19,
22585,
17,
8373,
19,
10721,
19,
7525,
19,
16351,
87,
19,
1268,
969,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
5831,
467,
1268,
969,
288,
203,
565,
445,
7829,
4727,
3935,
1435,
3903,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
7829,
4727,
18005,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
29,
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
]
|
./full_match/3/0xeE9977857789b0e41F7F1BB08821BF8eC3017176/sources/contracts/CompoundRateKeeperV2.sol | @notice Reset compound rate to 1. | function safeResetCompoundRate() internal {
require(
_calculatePotentialSafeCompoundRate(uint64(block.timestamp)) == 2**256 - 1,
"CompoundRateKeeperV2: compound rate has not reached the limit values."
);
compoundRate = _getDecimals();
compoundRateLastUpdate = uint64(block.timestamp);
}
| 8,208,898 | [
1,
7013,
11360,
4993,
358,
404,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4183,
7013,
16835,
4727,
1435,
2713,
288,
203,
3639,
2583,
12,
203,
5411,
389,
11162,
24947,
9890,
16835,
4727,
12,
11890,
1105,
12,
2629,
18,
5508,
3719,
422,
576,
636,
5034,
300,
404,
16,
203,
5411,
315,
16835,
4727,
17891,
58,
22,
30,
11360,
4993,
711,
486,
8675,
326,
1800,
924,
1199,
203,
3639,
11272,
203,
203,
3639,
11360,
4727,
273,
389,
588,
31809,
5621,
203,
3639,
11360,
4727,
3024,
1891,
273,
2254,
1105,
12,
2629,
18,
5508,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
/** @title Arbazaar. */
contract Arbazaar is Ownable, ReentrancyGuard {
using Counters for Counters.Counter;
Counters.Counter private _listings;
Counters.Counter private _sales;
Counters.Counter private _offers;
address payable deployerAddress;
address payable developerWallet;
address tokenAddress;
IERC20 public buckToken;
uint public tokens;
uint public rewardsAll;
uint public rewardsUnclaimed;
address[] public stakers;
uint totalVolume;
uint totalFees;
mapping(address => uint) public stake;
mapping(address => uint) public unclaimedRewards;
mapping(address => uint) public claimedRewards;
mapping(address => uint) public collectionVolume;
mapping(address => bool) public isStaker;
mapping(address => bool) public isStaking;
/** @dev Creates an NFT marketplace on Arbitrum.
* @param _developerWallet The address of the developer wallet.
* @param _buckTokenAddress The canonical BUCK token address.
*/
constructor(
address payable _developerWallet,
address _buckTokenAddress
) {
deployerAddress = payable(msg.sender);
developerWallet = _developerWallet;
tokenAddress = _buckTokenAddress;
buckToken = IERC20(tokenAddress);
}
struct Listing {
uint listingKey;
address collection;
uint tokenId;
address payable seller;
address payable owner;
uint price;
uint precision;
bool sold;
bool cancelled;
uint date;
}
mapping(uint => Listing) private listing;
event ListingAdded(
uint indexed listingKey,
address indexed collection,
uint indexed tokenId,
address seller,
address owner,
uint price,
uint precision,
bool sold,
bool cancelled,
uint date
);
event ListingRemoved(
uint indexed listingKey,
address indexed collection,
uint indexed tokenId,
address seller,
address owner,
uint price,
uint precision,
bool sold,
bool cancelled,
uint date
);
struct Offer {
uint offerKey;
address collection;
uint tokenId;
address payable bidder;
uint price;
uint precision;
bool sold;
bool cancelled;
uint date;
}
mapping(uint => Offer) private offer;
event OfferAdded(
uint indexed offerKey,
address indexed collection,
uint indexed tokenId,
address bidder,
uint price,
uint precision,
bool sold,
bool cancelled,
uint date
);
event OfferRemoved(
uint indexed offerKey,
address indexed collection,
uint indexed tokenId,
address bidder,
uint price,
uint precision,
bool sold,
bool cancelled,
uint date
);
/** @dev Calculates the fee paid out to stakers, provided a given sale.
* @param _value The total value of the given sale.
* @param _precision The precision with which to manipulate _value, to prevent overflow/underflow.
* @return 2% of _value.
*/
function calculateStakerFee(
uint _value,
uint _precision
) internal pure returns(uint) {
if (_precision == 15) {
return (_value / 1e15) * (20 * 1e12);
} else if (_precision == 16) {
return (_value / 1e16) * (20 * 1e13);
} else if (_precision == 17) {
return (_value / 1e17) * (20 * 1e14);
} else {
return (_value / 1e18) * (20 * 1e15);
}
}
/** @dev Calculates the fee paid out to the developer, provided a given sale.
* @param _value The total value of the given sale.
* @param _precision The precision with which to manipulate _value, to prevent overflow/underflow.
* @return 0.5% of _value.
*/
function calculateDeveloperFee(
uint _value,
uint _precision
) internal pure returns(uint) {
if (_precision == 15) {
return (_value / 1e15) * (5 * 1e12);
} else if (_precision == 16) {
return (_value / 1e16) * (5 * 1e13);
} else if (_precision == 17) {
return (_value / 1e17) * (5 * 1e14);
} else {
return (_value / 1e18) * (5 * 1e15);
}
}
/** @dev Calculates the precision needed to manipulate a given value, to prevent overflow/underflow.
* @param _value The value to calculate precision for.
* @return The highest number at which (_value / 1e<number>) will not overflow/underflow.
*/
function calculatePrecision(
uint _value
) internal pure returns (uint) {
if (_value >= 1000000000000000000) {
return 18;
} else if (_value >= 100000000000000000) {
return 17;
} else if (_value >= 10000000000000000) {
return 16;
} else if (_value >= 1000000000000000) {
return 15;
}
return 18;
}
/** @dev Multiplies the first two values together and divides the product by the third value (assuming 18 or less decimal places).
* @param _x The first value (factor).
* @param _y The second value (factor).
* @param _z The third value (divisor).
* @return ((_x * _y) / _z).
*/
function mulDiv (
uint _x,
uint _y,
uint _z
) public pure returns (uint) {
uint a = _x / _z;
uint b = _x % _z;
uint c = _y / _z;
uint d = _y % _z;
return a * b * _z + a * d + b * c + b * d / _z;
}
/** @dev Adds a listing to the marketplace.
* @param _collection The address of the collection that the listing is from.
* @param _tokenId The token ID of the listing.
* @param _price The price to list the token at.
*/
function addListing(
address _collection,
uint _tokenId,
uint _price
) public payable nonReentrant {
require(msg.sender == IERC721(_collection).ownerOf(_tokenId), "You do not own the item that you are trying to list.");
require(_price >= 1000000000000000, "Listings must be at least 0.001 ETH.");
require(msg.value == 0, "Do not attach extra ether to this transaction.");
_listings.increment();
uint listingKey = _listings.current();
uint precision = calculatePrecision(_price);
uint date = block.number;
listing[listingKey] = Listing(
listingKey,
_collection,
_tokenId,
payable(msg.sender),
payable(address(0)),
_price,
precision,
false,
false,
date
);
IERC721(_collection).transferFrom(msg.sender, address(this), _tokenId);
emit ListingAdded(
listingKey,
_collection,
_tokenId,
msg.sender,
address(0),
_price,
precision,
false,
false,
date
);
}
/** @dev Removes a listing from the marketplace.
* @param _listingKey The key of the listing to be removed.
*/
function removeListing (
uint _listingKey
) public payable nonReentrant {
require(msg.sender == listing[_listingKey].seller, "This listing is not under your custody.");
require(listing[_listingKey].cancelled == false, "This listing has been cancelled.");
listing[_listingKey].cancelled = true;
emit ListingRemoved(
_listingKey,
listing[_listingKey].collection,
listing[_listingKey].tokenId,
msg.sender,
msg.sender,
listing[_listingKey].price,
listing[_listingKey].precision,
false,
true,
block.number
);
}
/** @dev Purchases a listing from the marketplace.
* @param _collection The address of the collection that the listing is from.
* @param _listingKey The key of the listing to be purchased.
*/
function purchaseListing(
address _collection,
uint _listingKey
) public payable nonReentrant {
uint price = listing[_listingKey].price;
uint precision = listing[_listingKey].precision;
uint feeStaker = calculateStakerFee(price, precision);
uint feeDeveloper = calculateDeveloperFee(price, precision);
uint fees = feeStaker + feeDeveloper;
uint tokenId = listing[_listingKey].tokenId;
require(listing[_listingKey].cancelled == false, "This listing has been cancelled.");
require(listing[_listingKey].sold == false, "This listing has already been sold.");
require(listing[_listingKey].collection == _collection, "This listing is part of a different collection.");
require(listing[_listingKey].tokenId == tokenId, "This listing is of a different token ID.");
require(msg.value == price + fees, "Ensure the value of this transaction is 102.5% of the listing price.");
listing[_listingKey].seller.transfer(price);
IERC721(_collection).transferFrom(address(this), msg.sender, tokenId);
listing[_listingKey].owner = payable(msg.sender);
listing[_listingKey].sold = true;
_sales.increment();
collectionVolume[_collection] += price;
totalVolume += price;
totalFees += fees;
uint totalAmount = tokens;
if (totalAmount > 0) {
for (uint i = 0; i < stakers.length; i++) {
address staker = stakers[i];
unclaimedRewards[staker] += mulDiv(feeStaker, stake[staker], totalAmount);
}
rewardsUnclaimed += feeStaker;
rewardsAll += feeStaker;
}
payable(developerWallet).transfer(feeDeveloper);
}
/** @dev Adds an offer to the marketplace.
* @param _collection The address of the collection that the item is from.
* @param _tokenId The token ID of the item.
* @param _price The value of the offer.
*/
function addOffer(
address _collection,
uint _tokenId,
uint _price
) public payable nonReentrant {
require(_price >= 1000000000000000, "Offers must be at least 0.001 ETH.");
require(msg.value == _price, "The value of this transaction must match the amount offered.");
_offers.increment();
uint offerKey = _offers.current();
uint precision = calculatePrecision(_price);
uint date = block.number;
offer[offerKey] = Offer(
offerKey,
_collection,
_tokenId,
payable(msg.sender),
_price,
precision,
false,
false,
date
);
emit OfferAdded(
offerKey,
_collection,
_tokenId,
msg.sender,
_price,
precision,
false,
false,
date
);
}
/** @dev Removes an offer from the marketplace.
* @param _offerKey The key of the offer to be removed.
*/
function removeOffer(
uint _offerKey
) public payable nonReentrant {
require(offer[_offerKey].cancelled == false, "This offer has been cancelled.");
require(offer[_offerKey].sold == false, "This offer has been accepted.");
require(msg.sender == offer[_offerKey].bidder, "This offer is not under your custody.");
offer[_offerKey].cancelled = true;
payable(msg.sender).transfer(offer[_offerKey].price);
emit OfferRemoved(
_offerKey,
offer[_offerKey].collection,
offer[_offerKey].tokenId,
msg.sender,
offer[_offerKey].price,
offer[_offerKey].precision,
false,
true,
block.number
);
}
/** @dev Accepts an offer for an item.
* @param _collection The address of the collection that the item is from.
* @param _offerKey The key of the offer to be accepted.
*/
function acceptOffer(
address _collection,
uint _offerKey
) public payable nonReentrant {
uint price = offer[_offerKey].price;
uint precision = offer[_offerKey].precision;
uint feeStaker = calculateStakerFee(price, precision);
uint feeDeveloper = calculateDeveloperFee(price, precision);
uint fees = feeStaker + feeDeveloper;
uint tokenId = offer[_offerKey].tokenId;
require(offer[_offerKey].cancelled == false, "This offer has been cancelled.");
require(offer[_offerKey].sold == false, "This offer has already been accepted.");
require(offer[_offerKey].collection == _collection, "This offer is part of a different collection.");
require(offer[_offerKey].tokenId == tokenId, "This offer is of a different token ID.");
require(msg.sender == IERC721(offer[_offerKey].collection).ownerOf(tokenId), "You do not own the item that this offer is valid for.");
payable(msg.sender).transfer(offer[_offerKey].price - fees);
IERC721(_collection).transferFrom(msg.sender, offer[_offerKey].bidder, tokenId);
offer[_offerKey].sold = true;
collectionVolume[_collection] += price;
totalVolume += price;
totalFees += fees;
uint totalAmount = tokens;
if (totalAmount > 0) {
for (uint i = 0; i < stakers.length; i++) {
address staker = stakers[i];
unclaimedRewards[staker] += mulDiv(feeStaker, stake[staker], totalAmount);
}
rewardsUnclaimed += feeStaker;
rewardsAll += feeStaker;
}
payable(developerWallet).transfer(feeDeveloper);
}
/** @dev Retrieves the listings of a given item.
* @param _collection The address of the collection that the item is from.
* @param _tokenId The token ID of the item.
* @return The array of listings that match the query.
*/
function retrieveListingsByItem(
address _collection,
uint _tokenId
) public view returns (Listing[] memory) {
uint numListings = _listings.current();
uint matches = 0;
uint cursor = 0;
for (uint i = 0; i < numListings; i++) {
if (listing[i + 1].collection == _collection && listing[i + 1].tokenId == _tokenId) {
matches += 1;
}
}
Listing[] memory items = new Listing[](matches);
for (uint i = 0; i < numListings; i++) {
if (listing[i + 1].collection == _collection && listing[i + 1].tokenId == _tokenId) {
Listing storage currentItem = listing[i + 1];
items[cursor] = currentItem;
cursor += 1;
}
}
return items;
}
/** @dev Retrieves the listings in a given collection.
* @param _collection The address of the collection.
* @return The array of listings that match the query.
*/
function retrieveListingsByCollection(
address _collection
) public view returns (Listing[] memory) {
uint numListings = _listings.current();
uint matches = 0;
uint cursor = 0;
for (uint i = 0; i < numListings; i++) {
if (listing[i + 1].collection == _collection) {
matches += 1;
}
}
Listing[] memory items = new Listing[](matches);
for (uint i = 0; i < numListings; i++) {
if (listing[i + 1].collection == _collection) {
Listing storage currentItem = listing[i + 1];
items[cursor] = currentItem;
cursor += 1;
}
}
return items;
}
/** @dev Retrieves the listings from a given account.
* @param _account The address of the account to retrieve listings from.
* @return The array of listings that match the query.
*/
function retrieveListingsByAccount(
address _account
) public view returns (Listing[] memory) {
uint numListings = _listings.current();
uint matches = 0;
uint cursor = 0;
for (uint i = 0; i < numListings; i++) {
if (listing[i + 1].seller == _account) {
matches += 1;
}
}
Listing[] memory items = new Listing[](matches);
for (uint i = 0; i < numListings; i++) {
if (listing[i + 1].seller == _account) {
Listing storage currentItem = listing[i + 1];
items[cursor] = currentItem;
cursor += 1;
}
}
return items;
}
/** @dev Retrieves the listings after a given block height.
* @param _fromBlock The earliest block to retrieve listings from.
* @return The array of listings that match the query.
*/
function retrieveListingsFromBlock(
uint _fromBlock
) public view returns (Listing[] memory) {
uint numListings = _listings.current();
uint matches = 0;
uint cursor = 0;
for (uint i = 0; i < numListings; i++) {
if (listing[i + 1].date >= _fromBlock) {
matches += 1;
}
}
Listing[] memory items = new Listing[](matches);
for (uint i = 0; i < numListings; i++) {
if (listing[i + 1].date >= _fromBlock) {
Listing storage currentItem = listing[i + 1];
items[cursor] = currentItem;
cursor += 1;
}
}
return items;
}
/** @dev Retrieves all of the marketplace's active listings.
* @return The array of all listings that have not been sold or cancelled.
*/
function retrieveListingsActive() public view returns (Listing[] memory) {
uint numListings = _listings.current();
uint matches = 0;
uint cursor = 0;
for (uint i = 0; i < numListings; i++) {
if (listing[i + 1].sold == false && listing[i + 1].cancelled == false) {
matches += 1;
}
}
Listing[] memory items = new Listing[](matches);
for (uint i = 0; i < numListings; i++) {
if (listing[i + 1].sold == false && listing[i + 1].cancelled == false) {
Listing storage currentItem = listing[i + 1];
items[cursor] = currentItem;
cursor += 1;
}
}
return items;
}
/** @dev Retrieves all of the marketplace's sold listings.
* @return The array of all listings that have been sold.
*/
function retrieveListingsSold() public view returns (Listing[] memory) {
uint numListings = _listings.current();
uint matches = 0;
uint cursor = 0;
for (uint i = 0; i < numListings; i++) {
if (listing[i + 1].sold == true) {
matches += 1;
}
}
Listing[] memory items = new Listing[](matches);
for (uint i = 0; i < numListings; i++) {
if (listing[i + 1].sold == true) {
Listing storage currentItem = listing[i + 1];
items[cursor] = currentItem;
cursor += 1;
}
}
return items;
}
/** @dev Retrieves all of the marketplace's cancelled listings.
* @return The array of all listings that have been cancelled.
*/
function retrieveListingsCancelled() public view returns (Listing[] memory) {
uint numListings = _listings.current();
uint matches = 0;
uint cursor = 0;
for (uint i = 0; i < numListings; i++) {
if (listing[i + 1].cancelled == true) {
matches += 1;
}
}
Listing[] memory items = new Listing[](matches);
for (uint i = 0; i < numListings; i++) {
if (listing[i + 1].cancelled == true) {
Listing storage currentItem = listing[i + 1];
items[cursor] = currentItem;
cursor += 1;
}
}
return items;
}
/** @dev Retrieves all of the marketplace's listings.
* @return The array of all listings.
*/
function retrieveListingsAll() public view returns (Listing[] memory) {
uint numListings = _listings.current();
uint cursor = 0;
Listing[] memory items = new Listing[](numListings);
for (uint i = 0; i < numListings; i++) {
Listing storage currentItem = listing[i + 1];
items[cursor] = currentItem;
cursor += 1;
}
return items;
}
/** @dev Retrieves the offers for a given item.
* @param _collection The address of the collection that the item is from.
* @param _tokenId The token ID of the item.
* @return The array of offers that match the query.
*/
function retrieveOffersByItem(
address _collection,
uint _tokenId
) public view returns (Offer[] memory) {
uint numOffers = _offers.current();
uint matches = 0;
uint cursor = 0;
for (uint i = 0; i < numOffers; i++) {
if (offer[i + 1].collection == _collection && offer[i + 1].tokenId == _tokenId) {
matches += 1;
}
}
Offer[] memory items = new Offer[](matches);
for (uint i = 0; i < numOffers; i++) {
if (offer[i + 1].collection == _collection && offer[i + 1].tokenId == _tokenId) {
Offer storage currentItem = offer[i + 1];
items[cursor] = currentItem;
cursor += 1;
}
}
return items;
}
/** @dev Retrieves the offers in a given collection.
* @param _collection The address of the collection.
* @return The array of offers that match the query.
*/
function retrieveOffersByCollection(
address _collection
) public view returns (Offer[] memory) {
uint numOffers = _offers.current();
uint matches = 0;
uint cursor = 0;
for (uint i = 0; i < numOffers; i++) {
if (offer[i + 1].collection == _collection) {
matches += 1;
}
}
Offer[] memory items = new Offer[](matches);
for (uint i = 0; i < numOffers; i++) {
if (offer[i + 1].collection == _collection) {
Offer storage currentItem = offer[i + 1];
items[cursor] = currentItem;
cursor += 1;
}
}
return items;
}
/** @dev Retrieves the offers from a given account.
* @param _account The address of the account to retrieve offers from.
* @return The array of offers that match the query.
*/
function retrieveOffersByAccount(
address _account
) public view returns (Offer[] memory) {
uint numOffers = _offers.current();
uint matches = 0;
uint cursor = 0;
for (uint i = 0; i < numOffers; i++) {
if (offer[i + 1].bidder == _account) {
matches += 1;
}
}
Offer[] memory items = new Offer[](matches);
for (uint i = 0; i < numOffers; i++) {
if (offer[i + 1].bidder == _account) {
Offer storage currentItem = offer[i + 1];
items[cursor] = currentItem;
cursor += 1;
}
}
return items;
}
/** @dev Retrieves the offers after a given block height.
* @param _fromBlock The earliest block to retrieve offers from.
* @return The array of offers that match the query.
*/
function retrieveOffersFromBlock(
uint _fromBlock
) public view returns (Offer[] memory) {
uint numOffers = _offers.current();
uint matches = 0;
uint cursor = 0;
for (uint i = 0; i < numOffers; i++) {
if (offer[i + 1].date >= _fromBlock) {
matches += 1;
}
}
Offer[] memory items = new Offer[](matches);
for (uint i = 0; i < numOffers; i++) {
if (offer[i + 1].date >= _fromBlock) {
Offer storage currentItem = offer[i + 1];
items[cursor] = currentItem;
cursor += 1;
}
}
return items;
}
/** @dev Retrieves all of the marketplace's active offers.
* @return The array of all offers that have not been accepted or cancelled.
*/
function retrieveOffersActive() public view returns (Offer[] memory) {
uint numOffers = _offers.current();
uint matches = 0;
uint cursor = 0;
for (uint i = 0; i < numOffers; i++) {
if (offer[i + 1].sold == false && offer[i + 1].cancelled == false) {
matches += 1;
}
}
Offer[] memory items = new Offer[](matches);
for (uint i = 0; i < numOffers; i++) {
if (offer[i + 1].sold == false && offer[i + 1].cancelled == false) {
Offer storage currentItem = offer[i + 1];
items[cursor] = currentItem;
cursor += 1;
}
}
return items;
}
/** @dev Retrieves all of the marketplace's accepted offers.
* @return The array of all offers that have been accepted.
*/
function retrieveOffersSold() public view returns (Offer[] memory) {
uint numOffers = _offers.current();
uint matches = 0;
uint cursor = 0;
for (uint i = 0; i < numOffers; i++) {
if (offer[i + 1].sold == true) {
matches += 1;
}
}
Offer[] memory items = new Offer[](matches);
for (uint i = 0; i < numOffers; i++) {
if (offer[i + 1].sold == true) {
Offer storage currentItem = offer[i + 1];
items[cursor] = currentItem;
cursor += 1;
}
}
return items;
}
/** @dev Retrieves all of the marketplace's cancelled offers.
* @return The array of all offers that have been cancelled.
*/
function retrieveOffersCancelled() public view returns (Offer[] memory) {
uint numOffers = _offers.current();
uint matches = 0;
uint cursor = 0;
for (uint i = 0; i < numOffers; i++) {
if (offer[i + 1].cancelled == true) {
matches += 1;
}
}
Offer[] memory items = new Offer[](matches);
for (uint i = 0; i < numOffers; i++) {
if (offer[i + 1].cancelled == true) {
Offer storage currentItem = offer[i + 1];
items[cursor] = currentItem;
cursor += 1;
}
}
return items;
}
/** @dev Retrieves all of the marketplace's offers.
* @return The array of all offers.
*/
function retrieveOffersAll() public view returns (Offer[] memory) {
uint numOffers = _offers.current();
uint cursor = 0;
Offer[] memory items = new Offer[](numOffers);
for (uint i = 0; i < numOffers; i++) {
Offer storage currentItem = offer[i + 1];
items[cursor] = currentItem;
cursor += 1;
}
return items;
}
/** @dev Retrieves the deployer address.
* @return The address of the contract deployer.
*/
function getDeployerAddress() public view returns (address payable) {
return deployerAddress;
}
/** @dev Retrieves the developer wallet.
* @return The address of the contract developer.
*/
function getDeveloperWallet() public view returns (address payable) {
return developerWallet;
}
/** @dev Retrieves the total volume of a given collection.
* @param _collection The address of the collection.
* @return The cumulative lifetime value of purchased listings and accepted offers within _collection, denominated in Wei.
*/
function getVolumeByCollection(
address _collection
) public view returns (uint) {
return collectionVolume[_collection];
}
/** @dev Retrieves the total volume.
* @return The cumulative lifetime value of purchased listings and accepted offers, denominated in Wei.
*/
function getVolumeTotal() public view returns (uint) {
return totalVolume;
}
/** @dev Retrieves the total fees.
* @return The cumulative lifetime fees accrued, denominated in Wei.
*/
function getFeesTotal() public view returns (uint) {
return totalFees;
}
/** @dev Adds a stake.
* @param _amount The amount of BUCK tokens to stake.
*/
function addStake(
uint _amount
) public nonReentrant {
require(_amount >= 1000 * 1e18, "You must stake at least 1,000 BUCK tokens.");
require(buckToken.balanceOf(msg.sender) >= _amount, "Your stake cannot be greater than your balance.");
buckToken.transferFrom(msg.sender, address(this), _amount);
stake[msg.sender] = stake[msg.sender] + _amount;
if (!isStaker[msg.sender]) {
stakers.push(msg.sender);
isStaker[msg.sender] = true;
}
if (!isStaking[msg.sender]) {
isStaking[msg.sender] = true;
}
tokens += _amount;
}
/** @dev Removes a stake.
* @param _amount The amount of BUCK tokens to unstake.
*/
function removeStake(
uint _amount
) public nonReentrant {
uint balance = stake[msg.sender];
require(balance > 0, "You must own a stake of at least one token to do this.");
require(balance >= _amount, "You cannot claim more tokens than the balance of your stake.");
stake[msg.sender] = balance - _amount;
buckToken.transfer(msg.sender, _amount);
if (balance - _amount == 0) {
isStaking[msg.sender] = false;
}
tokens -= _amount;
}
/** @dev Claims staking rewards. */
function claimRewards() public payable nonReentrant {
require(isStaker[msg.sender] == true, "You must currently own or have previously owned a stake to do this.");
uint rewards = unclaimedRewards[msg.sender];
payable(msg.sender).transfer(rewards);
unclaimedRewards[msg.sender] = 0;
claimedRewards[msg.sender] += rewards;
rewardsUnclaimed -= rewards;
}
/** @dev Retrieves the total BUCK tokens staked.
* @return The number of currently staked BUCK tokens.
*/
function getStakeTotal() public view returns (uint) {
return tokens;
}
/** @dev Retrieves the total rewards generated by staking.
* @return The rewards generated by staking, denominated in Wei.
*/
function getRewardsTotal() public view returns (uint) {
return rewardsAll;
}
/** @dev Retrieves the total unclaimed rewards generated by staking.
* @return The unclaimed rewards generated by staking, denominated in Wei.
*/
function getUnclaimedRewardsTotal() public view returns (uint) {
return rewardsUnclaimed;
}
/** @dev Retrieves the stake of a given user.
* @param _user The address to check the stake of.
* @return The amount of BUCK tokens that _user currently has staked.
*/
function getStakeByUser(
address _user
) public view returns (uint) {
return stake[_user];
}
/** @dev Retrieves the unclaimed rewards of a given user.
* @param _user The address to check the unclaimed rewards of.
* @return The amount of unclaimed rewards that _user is entitled to, denominated in Wei.
*/
function getUnclaimedRewardsByUser(
address _user
) public view returns (uint) {
return unclaimedRewards[_user];
}
/** @dev Retrieves the claimed rewards offers a given user.
* @param _user The address to check the claimed rewards of.
* @return The amount of rewards that _user has already claimed, denominated in Wei.
*/
function getClaimedRewardsByUser(
address _user
) public view returns (uint) {
return claimedRewards[_user];
}
/** @dev Retrieves the canonical BUCK token address.
* @return The address of the BUCK token that this marketplace was constructed with.
*/
function getTokenAddress() public view returns (address) {
return tokenAddress;
}
} | * @dev Retrieves the listings of a given item. @param _collection The address of the collection that the item is from. @param _tokenId The token ID of the item. @return The array of listings that match the query./ | function retrieveListingsByItem(
address _collection,
uint _tokenId
) public view returns (Listing[] memory) {
uint numListings = _listings.current();
uint matches = 0;
uint cursor = 0;
for (uint i = 0; i < numListings; i++) {
if (listing[i + 1].collection == _collection && listing[i + 1].tokenId == _tokenId) {
matches += 1;
}
}
Listing[] memory items = new Listing[](matches);
for (uint i = 0; i < numListings; i++) {
if (listing[i + 1].collection == _collection && listing[i + 1].tokenId == _tokenId) {
Listing storage currentItem = listing[i + 1];
items[cursor] = currentItem;
cursor += 1;
}
}
return items;
}
| 13,071,063 | [
1,
6960,
326,
666,
899,
434,
279,
864,
761,
18,
225,
389,
5548,
1021,
1758,
434,
326,
1849,
716,
326,
761,
353,
628,
18,
225,
389,
2316,
548,
1021,
1147,
1599,
434,
326,
761,
18,
327,
1021,
526,
434,
666,
899,
716,
845,
326,
843,
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,
4614,
682,
899,
858,
1180,
12,
203,
3639,
1758,
389,
5548,
16,
203,
3639,
2254,
389,
2316,
548,
203,
565,
262,
1071,
1476,
1135,
261,
19081,
8526,
3778,
13,
288,
203,
3639,
2254,
818,
682,
899,
273,
389,
1098,
899,
18,
2972,
5621,
203,
3639,
2254,
1885,
273,
374,
31,
203,
3639,
2254,
3347,
273,
374,
31,
203,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
818,
682,
899,
31,
277,
27245,
288,
203,
5411,
309,
261,
21228,
63,
77,
397,
404,
8009,
5548,
422,
389,
5548,
597,
11591,
63,
77,
397,
404,
8009,
2316,
548,
422,
389,
2316,
548,
13,
288,
203,
7734,
1885,
1011,
404,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
987,
310,
8526,
3778,
1516,
273,
394,
987,
310,
8526,
12,
8436,
1769,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
818,
682,
899,
31,
277,
27245,
288,
203,
5411,
309,
261,
21228,
63,
77,
397,
404,
8009,
5548,
422,
389,
5548,
597,
11591,
63,
77,
397,
404,
8009,
2316,
548,
422,
389,
2316,
548,
13,
288,
203,
7734,
987,
310,
2502,
27471,
273,
11591,
63,
77,
397,
404,
15533,
203,
7734,
1516,
63,
9216,
65,
273,
27471,
31,
203,
7734,
3347,
1011,
404,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
1516,
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
]
|
pragma solidity ^0.8.0;
/**
* @title ISignableERC20 interface
*
* SPDX-License-Identifier: MIT
*/
interface ISignableERC20 {
event OperatorsDefined(address[] operators);
event Signature(address signer, address signee, bytes32 hash);
function transferFromWithSignature(
address _from,
address _to,
uint256 _value,
uint64 _signatureValidity,
bytes memory _signature) external returns (bool);
}
| * @title ISignableERC20 interface SPDX-License-Identifier: MIT/ | interface ISignableERC20 {
event OperatorsDefined(address[] operators);
event Signature(address signer, address signee, bytes32 hash);
function transferFromWithSignature(
address _from,
address _to,
uint256 _value,
uint64 _signatureValidity,
bytes memory _signature) external returns (bool);
}
| 12,625,164 | [
1,
45,
2766,
429,
654,
39,
3462,
1560,
11405,
28826,
17,
13211,
17,
3004,
30,
490,
1285,
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,
5831,
467,
2766,
429,
654,
39,
3462,
288,
203,
225,
871,
7692,
3062,
8116,
12,
2867,
8526,
12213,
1769,
203,
225,
871,
9249,
12,
2867,
10363,
16,
1758,
1573,
1340,
16,
1731,
1578,
1651,
1769,
203,
203,
225,
445,
7412,
1265,
1190,
5374,
12,
203,
565,
1758,
389,
2080,
16,
203,
565,
1758,
389,
869,
16,
203,
565,
2254,
5034,
389,
1132,
16,
203,
565,
2254,
1105,
389,
8195,
19678,
16,
203,
565,
1731,
3778,
389,
8195,
13,
3903,
1135,
261,
6430,
1769,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/* Deprecated solidity proxy call method. Refer to the asm implementation */
pragma solidity ^0.5.11;
/* Proxy contract that makes a call to the dapp contract to modify the dapp's state */
contract proxy {
// Public variables that are set by the call function.
bool public res;
bytes public val;
bytes public encoded_value;
bytes public encoding;
/* Events used for debugging */
event debug(string, bytes);
event debug(string, uint256);
// Function that converts a uint256 bytes to address type using assembly
function bytesToAddress(bytes memory bys) private pure returns (address addr) {
assembly {
// A Ethereum address is 20 bytes long or a uint160 type, thus it's represented by 40 Hex characters
// Since the original value given is Big endian with left padding, we only need the last 20 hex of the input
// Which is from Address 24-64
// Thus all that is needed is to load the last 20 bytes into the "addr" variable which is then returned
// Basically load from memory position bys + 32
addr := mload(add(bys,32))
}
}
// Function to get the returned value in address type
function getReturnedAddress () public view returns (address) {
return bytesToAddress(val);
}
function proxied_call(address addr, string memory fn_signature, uint256 _n) public returns (bytes memory value) {
return proxied_call(addr, fn_signature, new bytes(_n));
}
// @Note Problem with this is what if the user wants to pass things like structs and arrays in?
function proxied_call(address addr, string memory fn_signature, bytes memory _n) public returns (bytes memory value) {
// 1) Convert fn_signature from string type to bytes type
// 2) Get the keccak256 hash of the signature
// 3) Get the first 4 bytes of the signature hash as function selector
// 4) encode it together with the arguement for the function
encoded_value = abi.encodePacked(bytes4(keccak256(bytes(fn_signature))), _n);
// Make a proxied call to the method of given address and catch the result of the call with the returned value
// Using "call" code, Callee's contract state is modified, whereas caller's contract state is unchanged
(res, val) = addr.call(encoded_value);
return val;
}
// @Note Pseudo code below, showing a possible flow
function proxied_call(address addr, string memory fn_signature, bytes memory _n, bytes memory sig) public returns (bytes memory value) {
// 1) Convert fn_signature from string type to bytes type
// 2) Get the keccak256 hash of the signature
// 3) Get the first 4 bytes of the signature hash as function selector
// 4) encode it together with the arguement for the function
sigdata = concat(bytes(address), bytes(fn_signature), _n);
ecrecover(sigdata, sig)
encoding = abi.encodePacked(_n);
emit debug("encoded value is: ", encoding);
encoded_value = abi.encodePacked(bytes4(keccak256(bytes(fn_signature))), encoding);
// Make a proxied call to the method of given address and catch the result of the call with the returned value
// Using "call" code, Callee's contract state is modified, whereas caller's contract state is unchanged
(res, val) = addr.call(encoded_value);
return val;
}
// Wrapper function over proxied_call, with hardcoded function signature
function callSetN(address addr, uint256 _n) public {
// encoded_value = abi.encode(bytes4(keccak256("setN(uint256)")), _n);
proxied_call(addr, "setN(uint256)", _n);
}
// Wrapper function over proxied_call, with hardcoded function signature
function callSetN_getSender(address addr, uint256 _n) public {
// encoded_value = abi.encode(bytes4(keccak256("setN(uint256)")), _n);
proxied_call(addr, "setN_getSender(uint256)", _n);
}
} | @Note Problem with this is what if the user wants to pass things like structs and arrays in? 1) Convert fn_signature from string type to bytes type 2) Get the keccak256 hash of the signature 3) Get the first 4 bytes of the signature hash as function selector 4) encode it together with the arguement for the function Make a proxied call to the method of given address and catch the result of the call with the returned value Using "call" code, Callee's contract state is modified, whereas caller's contract state is unchanged | function proxied_call(address addr, string memory fn_signature, bytes memory _n) public returns (bytes memory value) {
encoded_value = abi.encodePacked(bytes4(keccak256(bytes(fn_signature))), _n);
(res, val) = addr.call(encoded_value);
return val;
}
| 14,042,842 | [
1,
36,
8067,
21685,
598,
333,
353,
4121,
309,
326,
729,
14805,
358,
1342,
9198,
3007,
8179,
471,
5352,
316,
35,
404,
13,
4037,
2295,
67,
8195,
628,
533,
618,
358,
1731,
618,
576,
13,
968,
326,
417,
24410,
581,
5034,
1651,
434,
326,
3372,
890,
13,
968,
326,
1122,
1059,
1731,
434,
326,
3372,
1651,
487,
445,
3451,
1059,
13,
2017,
518,
9475,
598,
326,
1501,
344,
475,
364,
326,
445,
4344,
279,
21875,
745,
358,
326,
707,
434,
864,
1758,
471,
1044,
326,
563,
434,
326,
745,
598,
326,
2106,
460,
11637,
315,
1991,
6,
981,
16,
3596,
11182,
1807,
6835,
919,
353,
4358,
16,
1625,
345,
4894,
1807,
6835,
919,
353,
14827,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
21875,
67,
1991,
12,
2867,
3091,
16,
533,
3778,
2295,
67,
8195,
16,
1731,
3778,
389,
82,
13,
1071,
1135,
261,
3890,
3778,
460,
13,
288,
203,
3639,
3749,
67,
1132,
273,
24126,
18,
3015,
4420,
329,
12,
3890,
24,
12,
79,
24410,
581,
5034,
12,
3890,
12,
4293,
67,
8195,
3719,
3631,
389,
82,
1769,
203,
203,
3639,
261,
455,
16,
1244,
13,
273,
3091,
18,
1991,
12,
10787,
67,
1132,
1769,
203,
3639,
327,
1244,
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
]
|
./partial_match/3/0xAe8F9d6c5b5853c1C4B0d5a207Fc7359AF4f9327/sources/ApostleItemBar.sol | function getLiquidity( address pair, address token, uint256 amount ) external view returns (uint256); function getLiquidityValue( address pair, address token, uint256 liquidity ) external view returns (uint256); | interface IMetaDataTeller {
function getMetaData(address _token, uint256 _id)
external
view
returns (uint16, uint16);
function getPrefer(bytes32 _name, address _token)
external
view
returns (uint256);
function getRate(
address _token,
uint256 _id,
uint256 _index
) external view returns (uint256);
}
| 5,207,754 | [
1,
915,
9014,
18988,
24237,
12,
225,
202,
2867,
3082,
16,
225,
202,
2867,
1147,
16,
225,
202,
11890,
5034,
3844,
262,
3903,
1476,
1135,
261,
11890,
5034,
1769,
445,
9014,
18988,
24237,
620,
12,
225,
202,
2867,
3082,
16,
225,
202,
2867,
1147,
16,
225,
202,
11890,
5034,
4501,
372,
24237,
262,
3903,
1476,
1135,
261,
11890,
5034,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5831,
467,
6998,
56,
292,
749,
288,
203,
202,
915,
23028,
12,
2867,
389,
2316,
16,
2254,
5034,
389,
350,
13,
203,
202,
202,
9375,
203,
202,
202,
1945,
203,
202,
202,
6154,
261,
11890,
2313,
16,
2254,
2313,
1769,
203,
203,
202,
915,
12822,
586,
12,
3890,
1578,
389,
529,
16,
1758,
389,
2316,
13,
203,
202,
202,
9375,
203,
202,
202,
1945,
203,
202,
202,
6154,
261,
11890,
5034,
1769,
203,
203,
202,
915,
4170,
340,
12,
203,
202,
202,
2867,
389,
2316,
16,
203,
202,
202,
11890,
5034,
389,
350,
16,
203,
202,
202,
11890,
5034,
389,
1615,
203,
202,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
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
]
|
pragma solidity ^0.4.16;
contract DC{
uint256 constant private MAX_UINT256 = 2**256 - 1;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
uint256 public totalSupply;
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show.
string public symbol; //An identifier: eg SBX
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function DC() public {
balances[msg.sender] = 9000000000000; // Give the creator all initial tokens
totalSupply = 9000000000000; // Update total supply
name = "Digital Games Capital"; // Set the name for display purposes
decimals =4; // Amount of decimals for display purposes
symbol = "DC"; // Set the symbol for display purposes
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
} | Update total supply
| totalSupply = 9000000000000; | 2,307,548 | [
1,
1891,
2078,
14467,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2078,
3088,
1283,
273,
2468,
12648,
2787,
31,
7682,
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 solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract PHAYCMarketplace is ReentrancyGuard, Pausable, Ownable {
IERC721 phaycContract;
struct Offer {
bool isForSale;
uint phaycIndex;
address seller;
uint minValue; // in ether
address onlySellTo;
}
struct Bid {
bool hasBid;
uint phaycIndex;
address bidder;
uint value;
}
// A record of PHAYC that are offered for sale at a specific minimum value, and perhaps to a specific person
mapping (uint => Offer) public phaycOfferedForSale;
// A record of the highest bid
mapping (uint => Bid) public phaycBids;
// A record of pending ETH withdrawals by address
mapping (address => uint) public pendingWithdrawals;
event PhaycOffered(uint indexed phaycIndex, uint minValue, address indexed toAddress);
event PhaycBidEntered(uint indexed phaycIndex, uint value, address indexed fromAddress);
event PhaycBidWithdrawn(uint indexed phaycIndex, uint value, address indexed fromAddress);
event PhaycBought(uint indexed phaycIndex, uint value, address indexed fromAddress, address indexed toAddress);
event PhaycNoLongerForSale(uint indexed phaycIndex);
/* Initializes contract with an instance of PHAYC contract, and sets deployer as owner */
constructor(address initialPhaycAddress) {
IERC721(initialPhaycAddress).balanceOf(address(this));
phaycContract = IERC721(initialPhaycAddress);
}
function pause() public whenNotPaused onlyOwner {
_pause();
}
function unpause() public whenPaused onlyOwner {
_unpause();
}
/* Returns the PHAYC contract address currently being used */
function phaycAddress() public view returns (address) {
return address(phaycContract);
}
/* Allows the owner of the contract to set a new PHAYC contract address */
function setPhaycContract(address newPhaycAddress) public onlyOwner {
phaycContract = IERC721(newPhaycAddress);
}
/* Allows the owner of a PHAYC to stop offering it for sale */
function phaycNoLongerForSale(uint phaycIndex) public nonReentrant() {
if (phaycIndex >= 10000) revert('token index not valid');
if (phaycContract.ownerOf(phaycIndex) != msg.sender) revert('you are not the owner of this token');
phaycOfferedForSale[phaycIndex] = Offer(false, phaycIndex, msg.sender, 0, address(0x0));
emit PhaycNoLongerForSale(phaycIndex);
}
/* Allows a PHAYC owner to offer it for sale */
function offerPhaycForSale(uint phaycIndex, uint minSalePriceInWei) public whenNotPaused nonReentrant() {
if (phaycIndex >= 10000) revert('token index not valid');
if (phaycContract.ownerOf(phaycIndex) != msg.sender) revert('you are not the owner of this token');
phaycOfferedForSale[phaycIndex] = Offer(true, phaycIndex, msg.sender, minSalePriceInWei, address(0x0));
emit PhaycOffered(phaycIndex, minSalePriceInWei, address(0x0));
}
/* Allows a PHAYC owner to offer it for sale to a specific address */
function offerPhaycForSaleToAddress(uint phaycIndex, uint minSalePriceInWei, address toAddress) public whenNotPaused nonReentrant() {
if (phaycIndex >= 10000) revert();
if (phaycContract.ownerOf(phaycIndex) != msg.sender) revert('you are not the owner of this token');
phaycOfferedForSale[phaycIndex] = Offer(true, phaycIndex, msg.sender, minSalePriceInWei, toAddress);
emit PhaycOffered(phaycIndex, minSalePriceInWei, toAddress);
}
/* Allows users to buy a PHAYC offered for sale */
function buyPhayc(uint phaycIndex) payable public whenNotPaused nonReentrant() {
if (phaycIndex >= 10000) revert('token index not valid');
Offer memory offer = phaycOfferedForSale[phaycIndex];
if (!offer.isForSale) revert('phayc is not for sale'); // phayc not actually for sale
if (offer.onlySellTo != address(0x0) && offer.onlySellTo != msg.sender) revert();
if (msg.value != offer.minValue) revert('not enough ether'); // Didn't send enough ETH
address seller = offer.seller;
if (seller == msg.sender) revert('seller == msg.sender');
if (seller != phaycContract.ownerOf(phaycIndex)) revert('seller no longer owner of phayc'); // Seller no longer owner of phayc
phaycOfferedForSale[phaycIndex] = Offer(false, phaycIndex, msg.sender, 0, address(0x0));
phaycContract.safeTransferFrom(seller, msg.sender, phaycIndex);
pendingWithdrawals[seller] += msg.value;
emit PhaycBought(phaycIndex, msg.value, seller, msg.sender);
// Check for the case where there is a bid from the new owner and refund it.
// Any other bid can stay in place.
Bid memory bid = phaycBids[phaycIndex];
if (bid.bidder == msg.sender) {
// Kill bid and refund value
pendingWithdrawals[msg.sender] += bid.value;
phaycBids[phaycIndex] = Bid(false, phaycIndex, address(0x0), 0);
}
}
/* Allows users to retrieve ETH from sales */
function withdraw() public nonReentrant() {
uint amount = pendingWithdrawals[msg.sender];
// Remember to zero the pending refund before
// sending to prevent re-entrancy attacks
pendingWithdrawals[msg.sender] = 0;
payable(msg.sender).transfer(amount);
}
/* Allows users to enter bids for any PHAYC */
function enterBidForPhayc(uint phaycIndex) payable public whenNotPaused nonReentrant() {
if (phaycIndex >= 10000) revert('token index not valid');
if (phaycContract.ownerOf(phaycIndex) == msg.sender) revert('you already own this phayc');
if (msg.value == 0) revert('cannot enter bid of zero');
Bid memory existing = phaycBids[phaycIndex];
if (msg.value <= existing.value) revert('your bid is too low');
if (existing.value > 0) {
// Refund the failing bid
pendingWithdrawals[existing.bidder] += existing.value;
}
phaycBids[phaycIndex] = Bid(true, phaycIndex, msg.sender, msg.value);
emit PhaycBidEntered(phaycIndex, msg.value, msg.sender);
}
/* Allows PHAYC owners to accept bids for their PHAYC */
function acceptBidForPhayc(uint phaycIndex, uint minPrice) public whenNotPaused nonReentrant() {
if (phaycIndex >= 10000) revert('token index not valid');
if (phaycContract.ownerOf(phaycIndex) != msg.sender) revert('you do not own this token');
address seller = msg.sender;
Bid memory bid = phaycBids[phaycIndex];
if (bid.value == 0) revert('cannot enter bid of zero');
if (bid.value < minPrice) revert('your bid is too low');
address bidder = bid.bidder;
if (seller == bidder) revert('you already own this token');
phaycOfferedForSale[phaycIndex] = Offer(false, phaycIndex, bidder, 0, address(0x0));
uint amount = bid.value;
phaycBids[phaycIndex] = Bid(false, phaycIndex, address(0x0), 0);
phaycContract.safeTransferFrom(msg.sender, bidder, phaycIndex);
pendingWithdrawals[seller] += amount;
emit PhaycBought(phaycIndex, bid.value, seller, bidder);
}
/* Allows bidders to withdraw their bids */
function withdrawBidForPhayc(uint phaycIndex) public nonReentrant() {
if (phaycIndex >= 10000) revert('token index not valid');
Bid memory bid = phaycBids[phaycIndex];
if (bid.bidder != msg.sender) revert('the bidder is not message sender');
emit PhaycBidWithdrawn(phaycIndex, bid.value, msg.sender);
uint amount = bid.value;
phaycBids[phaycIndex] = Bid(false, phaycIndex, address(0x0), 0);
// Refund the bid money
payable(msg.sender).transfer(amount);
}
}
| A record of the highest bid | mapping (uint => Bid) public phaycBids;
| 1,768,244 | [
1,
37,
1409,
434,
326,
9742,
9949,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
261,
11890,
516,
605,
350,
13,
1071,
1844,
528,
71,
38,
2232,
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
]
|
./full_match/42/0x54FFA1FDd576Bc890174302CC87bb0e19880cad3/sources/bswap.sol | @notice Transfers `amount` tokens from `msg.sender` to `to`. @param to The address to move the tokens. @param amount of the tokens to move. @return (bool) Returns True if succeeded. If `amount` is 0, or `msg.sender` is `to` nothing happens | function transfer(address to, uint256 amount) public returns (bool) {
if (amount != 0) {
uint256 srcBalance = balanceOf[msg.sender];
require(srcBalance >= amount, "BoshiERC20: balance too low");
if (msg.sender != to) {
}
}
emit Transfer(msg.sender, to, amount);
return true;
if (amount != 0) {
uint256 srcBalance = balanceOf[msg.sender];
require(srcBalance >= amount, "BoshiERC20: balance too low");
if (msg.sender != to) {
}
}
emit Transfer(msg.sender, to, amount);
return true;
}
| 16,293,015 | [
1,
1429,
18881,
1375,
8949,
68,
2430,
628,
1375,
3576,
18,
15330,
68,
358,
1375,
869,
8338,
225,
358,
1021,
1758,
358,
3635,
326,
2430,
18,
225,
3844,
434,
326,
2430,
358,
3635,
18,
327,
261,
6430,
13,
2860,
1053,
309,
15784,
18,
971,
1375,
8949,
68,
353,
374,
16,
578,
1375,
3576,
18,
15330,
68,
353,
1375,
869,
68,
5083,
10555,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
7412,
12,
2867,
358,
16,
2254,
5034,
3844,
13,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
309,
261,
8949,
480,
374,
13,
288,
203,
5411,
2254,
5034,
1705,
13937,
273,
11013,
951,
63,
3576,
18,
15330,
15533,
203,
5411,
2583,
12,
4816,
13937,
1545,
3844,
16,
315,
38,
538,
12266,
654,
39,
3462,
30,
11013,
4885,
4587,
8863,
203,
5411,
309,
261,
3576,
18,
15330,
480,
358,
13,
288,
203,
203,
5411,
289,
203,
3639,
289,
203,
3639,
3626,
12279,
12,
3576,
18,
15330,
16,
358,
16,
3844,
1769,
203,
3639,
327,
638,
31,
203,
3639,
309,
261,
8949,
480,
374,
13,
288,
203,
5411,
2254,
5034,
1705,
13937,
273,
11013,
951,
63,
3576,
18,
15330,
15533,
203,
5411,
2583,
12,
4816,
13937,
1545,
3844,
16,
315,
38,
538,
12266,
654,
39,
3462,
30,
11013,
4885,
4587,
8863,
203,
5411,
309,
261,
3576,
18,
15330,
480,
358,
13,
288,
203,
203,
5411,
289,
203,
3639,
289,
203,
3639,
3626,
12279,
12,
3576,
18,
15330,
16,
358,
16,
3844,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.