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 |
---|---|---|---|---|---|---|
//! The Secret Store service contract intefaces.
//!
//! Copyright 2017 Svyatoslav Nikolsky, Parity Technologies Ltd.
//!
//! Licensed under the Apache License, Version 2.0 (the "License");
//! you may not use this file except in compliance with the License.
//! You may obtain a copy of the License at
//!
//! http://www.apache.org/licenses/LICENSE-2.0
//!
//! Unless required by applicable law or agreed to in writing, software
//! distributed under the License is distributed on an "AS IS" BASIS,
//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//! See the License for the specific language governing permissions and
//! limitations under the License.
pragma solidity >0.4.99 <0.6.0;
import "./Owned.sol";
import "./KeyServerSet.sol";
/// Base contract for all Secret Store services.
contract SecretStoreServiceBase is Owned {
/// Response support.
enum ResponseSupport { Confirmed, Unconfirmed, Impossible }
/// Single service request responses.
struct RequestResponses {
/// Number of block when servers set has been changed last time.
/// This whole structure is valid when this value stays the same.
/// Once this changes, all previous responses are erased.
uint256 keyServerSetChangeBlock;
/// We only support up to 256 key servers. If bit is set, this means that key server
/// has already voted for some confirmation (we do not care about exact response).
uint256 respondedKeyServersMask;
/// Number of key servers that have responded to request (number of ones in respondedKeyServersMask).
uint8 respondedKeyServersCount;
/// Response => number of supporting key servers.
mapping (bytes32 => uint8) responsesSupport;
/// Maximal support of single response.
uint8 maxResponseSupport;
/// All responses that are in responsesSupport. In ideal world, when all
/// key servers are working correctly, there'll be 1 response. Max 256 responses.
bytes32[] responses;
}
/// Only pass when fee is paid.
modifier whenFeePaid(uint256 amount) {
require(msg.value >= amount, "Not enough value");
_;
}
/// Only pass when 'valid' public is passed.
modifier validPublic(bytes memory publicKey) {
require(publicKey.length == 64, "Invalid length");
_;
}
/// Constructor.
constructor(address keyServerSetAddressInit) internal {
keyServerSetAddress = keyServerSetAddressInit;
}
/// Return number of key servers.
function keyServersCount() public view returns (uint8) {
return KeyServerSet(keyServerSetAddress).getCurrentKeyServersCount();
}
/// Return index of key server at given address.
function requireKeyServer(address keyServer) public view returns (uint8) {
return KeyServerSet(keyServerSetAddress).getCurrentKeyServerIndex(keyServer);
}
/// Drain balance of sender key server.
function drain() public {
uint256 balance = balances[msg.sender];
require(balance != 0, "Should not 0");
balances[msg.sender] = 0;
msg.sender.transfer(balance);
}
/// Deposit equal share of amount to each of key servers.
function deposit() internal {
uint8 count = keyServersCount();
uint256 amount = msg.value;
uint256 share = amount / count;
for (uint8 i = 0; i < count - 1; i++) {
address keyServer = KeyServerSet(keyServerSetAddress).getCurrentKeyServer(i);
balances[keyServer] += share;
amount = amount - share;
}
address lastKeyServer = KeyServerSet(keyServerSetAddress).getCurrentKeyServer(count - 1);
balances[lastKeyServer] += amount;
}
/// Returns true if response from given keyServer is required.
function isResponseRequired(RequestResponses storage responses, uint8 keyServerIndex) internal view returns (bool) {
// if servers set has changed, new response is definitely required
uint256 keyServerSetChangeBlock = KeyServerSet(keyServerSetAddress).getCurrentLastChange();
if (keyServerSetChangeBlock != responses.keyServerSetChangeBlock) {
return true;
}
// only require response when server has not responded before
uint256 keyServerMask = (uint256(1) << keyServerIndex);
return ((responses.respondedKeyServersMask & keyServerMask) == 0);
}
/// Insert key server confirmation.
function insertResponse(
RequestResponses storage responses,
uint8 keyServerIndex,
uint8 threshold,
bytes32 response) internal returns (ResponseSupport)
{
// check that servers set is still the same (and all previous responses are valid)
uint256 keyServerSetChangeBlock = KeyServerSet(keyServerSetAddress).getCurrentLastChange();
if (responses.respondedKeyServersCount == 0) {
responses.keyServerSetChangeBlock = keyServerSetChangeBlock;
} else if (responses.keyServerSetChangeBlock != keyServerSetChangeBlock) {
resetResponses(responses, keyServerSetChangeBlock);
}
// check if key server has already responded
uint256 keyServerMask = (uint256(1) << keyServerIndex);
if ((responses.respondedKeyServersMask & keyServerMask) != 0) {
return ResponseSupport.Unconfirmed;
}
// insert response
uint8 responseSupport = responses.responsesSupport[response] + 1;
responses.respondedKeyServersMask |= keyServerMask;
responses.respondedKeyServersCount += 1;
responses.responsesSupport[response] = responseSupport;
if (responseSupport == 1) {
responses.responses.push(response);
}
if (responseSupport >= responses.maxResponseSupport) {
responses.maxResponseSupport = responseSupport;
// check if passed response has received enough support
if (threshold <= responseSupport - 1) {
return ResponseSupport.Confirmed;
}
}
// check if max confirmation CAN receive enough support
uint8 keyServersLeft = keyServersCount() - responses.respondedKeyServersCount;
if (threshold > responses.maxResponseSupport + keyServersLeft - 1) {
return ResponseSupport.Impossible;
}
return ResponseSupport.Unconfirmed;
}
/// Clear responses before removal.
function clearResponses(RequestResponses storage responses) internal {
for (uint256 i = 0; i < responses.responses.length; ++i) {
delete responses.responsesSupport[responses.responses[i]];
}
}
/// Remove request id from array.
function removeRequestKey(bytes32[] storage requests, bytes32 request) internal {
for (uint i = 0; i < requests.length; ++i) {
if (requests[i] == request) {
requests[i] = requests[requests.length - 1];
requests.length = requests.length - 1;
break;
}
}
}
/// Reset responses.
function resetResponses(RequestResponses storage responses, uint256 keyServerSetChangeBlock) private {
clearResponses(responses);
responses.keyServerSetChangeBlock = keyServerSetChangeBlock;
responses.respondedKeyServersMask = 0;
responses.respondedKeyServersCount = 0;
responses.maxResponseSupport = 0;
responses.responses.length = 0;
}
/// Address of KeyServerSet contract.
address private keyServerSetAddress;
/// Balances of key servers.
mapping (address => uint256) private balances;
/// Active requests.
mapping (bytes32 => RequestResponses) private requests;
}
| Remove request id from array. | function removeRequestKey(bytes32[] storage requests, bytes32 request) internal {
for (uint i = 0; i < requests.length; ++i) {
if (requests[i] == request) {
requests[i] = requests[requests.length - 1];
requests.length = requests.length - 1;
break;
}
}
}
| 7,281,879 | [
1,
4625,
348,
7953,
560,
30,
225,
3581,
590,
612,
628,
526,
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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
261,
11420,
63,
77,
65,
422,
590,
13,
288,
203,
9506,
202,
11420,
63,
77,
65,
273,
3285,
63,
11420,
18,
2469,
300,
404,
15533,
203,
9506,
202,
11420,
18,
2469,
273,
3285,
18,
2469,
300,
404,
31,
203,
9506,
202,
8820,
31,
203,
1082,
202,
97,
203,
202,
202,
97,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
interface IMultiSigManager {
function provideAddress(address origin, uint poolIndex) external returns (address payable);
function passedContract(address) external returns (bool);
function moderator() external returns(address);
}
interface ICustodianToken {
function emitTransfer(address from, address to, uint value) external returns (bool success);
}
interface IWETH {
function balanceOf(address) external returns (uint);
function transfer(address to, uint value) external returns (bool success);
function transferFrom(address from, address to, uint value) external returns (bool success);
function approve(address spender, uint value) external returns (bool success);
function allowance(address owner, address spender) external returns (uint);
function withdraw(uint value) external;
function deposit() external;
}
interface IOracle {
function getLastPrice() external returns(uint, uint);
function started() external returns(bool);
}
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || 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;
}
function diff(uint a, uint b) internal pure returns (uint) {
return a > b ? sub(a, b) : sub(b, a);
}
function gt(uint a, uint b) internal pure returns(bytes1) {
bytes1 c;
c = 0x00;
if (a > b) {
c = 0x01;
}
return c;
}
}
contract Managed {
IMultiSigManager roleManager;
address public roleManagerAddress;
address public operator;
uint public lastOperationTime;
uint public operationCoolDown;
uint constant BP_DENOMINATOR = 10000;
event UpdateRoleManager(address newManagerAddress);
event UpdateOperator(address updater, address newOperator);
modifier only(address addr) {
require(msg.sender == addr);
_;
}
modifier inUpdateWindow() {
uint currentTime = getNowTimestamp();
require(currentTime - lastOperationTime >= operationCoolDown);
_;
lastOperationTime = currentTime;
}
constructor(
address roleManagerAddr,
address opt,
uint optCoolDown
) public {
roleManagerAddress = roleManagerAddr;
roleManager = IMultiSigManager(roleManagerAddr);
operator = opt;
operationCoolDown = optCoolDown;
}
function updateRoleManager(address newManagerAddr)
inUpdateWindow()
public
returns (bool) {
require(roleManager.passedContract(newManagerAddr));
roleManagerAddress = newManagerAddr;
roleManager = IMultiSigManager(roleManagerAddress);
require(roleManager.moderator() != address(0));
emit UpdateRoleManager(newManagerAddr);
return true;
}
function updateOperator() public inUpdateWindow() returns (bool) {
address updater = msg.sender;
operator = roleManager.provideAddress(updater, 0);
emit UpdateOperator(updater, operator);
return true;
}
function getNowTimestamp() internal view returns (uint) {
return now;
}
}
/// @title Custodian - every derivative contract should has basic custodian properties
/// @author duo.network
contract Custodian is Managed {
using SafeMath for uint;
/*
* Constants
*/
uint constant decimals = 18;
uint constant WEI_DENOMINATOR = 1000000000000000000;
enum State {
Inception,
Trading,
PreReset,
Reset,
Matured
}
/*
* Storage
*/
IOracle oracle;
ICustodianToken aToken;
ICustodianToken bToken;
string public contractCode;
address payable feeCollector;
address oracleAddress;
address aTokenAddress;
address bTokenAddress;
mapping(address => uint)[2] public balanceOf;
mapping (address => mapping (address => uint))[2] public allowance;
address[] public users;
mapping (address => uint) public existingUsers;
State state;
uint minBalance = 10000000000000000; // set at constructor
uint public totalSupplyA;
uint public totalSupplyB;
uint ethCollateralInWei;
uint navAInWei;
uint navBInWei;
uint lastPriceInWei;
uint lastPriceTimeInSecond;
uint resetPriceInWei;
uint resetPriceTimeInSecond;
uint createCommInBP;
uint redeemCommInBP;
uint period;
uint maturityInSecond; // set to 0 for perpetuals
uint preResetWaitingBlocks;
uint priceFetchCoolDown;
// cycle state variables
uint lastPreResetBlockNo = 0;
uint nextResetAddrIndex;
/*
* Modifiers
*/
modifier inState(State _state) {
require(state == _state);
_;
}
/*
* Events
*/
event StartTrading(uint navAInWei, uint navBInWei);
event StartPreReset();
event StartReset(uint nextIndex, uint total);
event Matured(uint navAInWei, uint navBInWei);
event AcceptPrice(uint indexed priceInWei, uint indexed timeInSecond, uint navAInWei, uint navBInWei);
event Create(address indexed sender, uint ethAmtInWei, uint tokenAInWei, uint tokenBInWei, uint feeInWei);
event Redeem(address indexed sender, uint ethAmtInWei, uint tokenAInWei, uint tokenBInWei, uint feeInWei);
event TotalSupply(uint totalSupplyAInWei, uint totalSupplyBInWei);
// token events
event Transfer(address indexed from, address indexed to, uint value, uint index);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens, uint index);
// operation events
event CollectFee(address addr, uint feeInWei, uint feeBalanceInWei);
event UpdateOracle(address newOracleAddress);
event UpdateFeeCollector(address updater, address newFeeCollector);
/*
* Constructor
*/
/// @dev Contract constructor sets operation cool down and set address pool status.
/// @param code contract name
/// @param maturity marutiry time in second
/// @param roleManagerAddr roleManagerContract Address
/// @param fc feeCollector address
/// @param comm commission rate
/// @param pd period
/// @param preResetWaitBlk pre reset waiting block numbers
/// @param pxFetchCoolDown price fetching cool down
/// @param opt operator
/// @param optCoolDown operation cooldown
/// @param minimumBalance niminum balance required
constructor(
string memory code,
uint maturity,
address roleManagerAddr,
address payable fc,
uint comm,
uint pd,
uint preResetWaitBlk,
uint pxFetchCoolDown,
address opt,
uint optCoolDown,
uint minimumBalance
)
public
Managed(roleManagerAddr, opt, optCoolDown)
{
contractCode = code;
maturityInSecond = maturity;
state = State.Inception;
feeCollector = fc;
createCommInBP = comm;
redeemCommInBP = comm;
period = pd;
preResetWaitingBlocks = preResetWaitBlk;
priceFetchCoolDown = pxFetchCoolDown;
navAInWei = WEI_DENOMINATOR;
navBInWei = WEI_DENOMINATOR;
minBalance = minimumBalance;
}
/*
* Public functions
*/
/// @dev return totalUsers in the system.
function totalUsers() public view returns (uint) {
return users.length;
}
function feeBalanceInWei() public view returns(uint) {
return address(this).balance.sub(ethCollateralInWei);
}
/*
* ERC token functions
*/
/// @dev transferInternal function.
/// @param index 0 is classA , 1 is class B
/// @param from from address
/// @param to to address
/// @param tokens num of tokens transferred
function transferInternal(uint index, address from, address to, uint tokens)
internal
inState(State.Trading)
returns (bool success)
{
// Prevent transfer to 0x0 address. Use burn() instead
require(to != address(0));
// Check if the sender has enough
require(balanceOf[index][from] >= tokens);
// Save this for an assertion in the future
uint previousBalances = balanceOf[index][from].add(balanceOf[index][to]);
// Subtract from the sender
balanceOf[index][from] = balanceOf[index][from].sub(tokens);
// Add the same to the recipient
balanceOf[index][to] = balanceOf[index][to].add(tokens);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[index][from].add(balanceOf[index][to]) == previousBalances);
emit Transfer(from, to, tokens, index);
checkUser(from, balanceOf[index][from], balanceOf[1 - index][from]);
checkUser(to, balanceOf[index][to], balanceOf[1 - index][to]);
return true;
}
function determineAddress(uint index, address from) internal view returns (address) {
return index == 0 && msg.sender == aTokenAddress ||
index == 1 && msg.sender == bTokenAddress
? from : msg.sender;
}
function transfer(uint index, address from, address to, uint tokens)
public
inState(State.Trading)
returns (bool success)
{
require(index == 0 || index == 1);
return transferInternal(index, determineAddress(index, from), to, tokens);
}
function transferFrom(uint index, address spender, address from, address to, uint tokens)
public
inState(State.Trading)
returns (bool success)
{
require(index == 0 || index == 1);
address spenderToUse = determineAddress(index, spender);
require(tokens <= allowance[index][from][spenderToUse]); // Check allowance
allowance[index][from][spenderToUse] = allowance[index][from][spenderToUse].sub(tokens);
return transferInternal(index, from, to, tokens);
}
function approve(uint index, address sender, address spender, uint tokens)
public
returns (bool success)
{
require(index == 0 || index == 1);
address senderToUse = determineAddress(index, sender);
allowance[index][senderToUse][spender] = tokens;
emit Approval(senderToUse, spender, tokens, index);
return true;
}
// end of token functions
/*
* Internal Functions
*/
// start of internal utility functions
function checkUser(address user, uint256 balanceA, uint256 balanceB) internal {
uint userIdx = existingUsers[user];
if ( userIdx > 0) {
if (balanceA < minBalance && balanceB < minBalance) {
uint lastIdx = users.length;
address lastUser = users[lastIdx - 1];
if (userIdx < lastIdx) {
users[userIdx - 1] = lastUser;
existingUsers[lastUser] = userIdx;
}
delete users[lastIdx - 1];
existingUsers[user] = 0;
users.length--;
}
} else if (balanceA >= minBalance || balanceB >= minBalance) {
users.push(user);
existingUsers[user] = users.length;
}
}
// end of internal utility functions
/*
* Operation Functions
*/
function collectFee(uint amountInWei)
public
only(feeCollector)
inState(State.Trading)
returns (bool success)
{
uint feeBalance = feeBalanceInWei().sub(amountInWei);
feeCollector.transfer(amountInWei);
emit CollectFee(feeCollector, amountInWei, feeBalance);
return true;
}
function updateOracle(address newOracleAddr)
only(roleManager.moderator())
inUpdateWindow()
public
returns (bool) {
require(roleManager.passedContract(newOracleAddr));
oracleAddress = newOracleAddr;
oracle = IOracle(oracleAddress);
(uint lastPrice, uint lastPriceTime) = oracle.getLastPrice();
require(lastPrice > 0 && lastPriceTime > 0);
emit UpdateOracle(newOracleAddr);
return true;
}
function updateFeeCollector()
public
inUpdateWindow()
returns (bool) {
address updater = msg.sender;
feeCollector = roleManager.provideAddress(updater, 0);
emit UpdateFeeCollector(updater, feeCollector);
return true;
}
}
/// @title DualClassCustodian - dual class token contract
/// @author duo.network
contract DualClassCustodian is Custodian {
/*
* Storage
*/
uint alphaInBP;
uint betaInWei;
uint limitUpperInWei;
uint limitLowerInWei;
uint iterationGasThreshold;
uint periodCouponInWei;
uint limitPeriodicInWei;
// reset intermediate values
uint newAFromAPerA;
uint newAFromBPerB;
uint newBFromAPerA;
uint newBFromBPerB;
enum ResetState {
UpwardReset,
DownwardReset,
PeriodicReset
}
ResetState resetState;
/*
* Events
*/
event SetValue(uint index, uint oldValue, uint newValue);
function() external payable {}
/*
* Constructor
*/
constructor(
string memory code,
uint maturity,
address roleManagerAddr,
address payable fc,
uint alpha,
uint r,
uint hp,
uint hu,
uint hd,
uint comm,
uint pd,
uint optCoolDown,
uint pxFetchCoolDown,
uint iteGasTh,
uint preResetWaitBlk,
uint minimumBalance
)
public
Custodian (
code,
maturity,
roleManagerAddr,
fc,
comm,
pd,
preResetWaitBlk,
pxFetchCoolDown,
msg.sender,
optCoolDown,
minimumBalance
)
{
alphaInBP = alpha;
betaInWei = WEI_DENOMINATOR;
periodCouponInWei = r;
limitPeriodicInWei = hp;
limitUpperInWei = hu;
limitLowerInWei = hd;
iterationGasThreshold = iteGasTh; // 65000;
}
/*
* Public Functions
*/
/// @dev startCustodian
/// @param aAddr contract address of Class A
/// @param bAddr contract address of Class B
/// @param oracleAddr contract address of Oracle
function startCustodian(
address aAddr,
address bAddr,
address oracleAddr
)
public
inState(State.Inception)
only(operator)
returns (bool success)
{
aTokenAddress = aAddr;
aToken = ICustodianToken(aTokenAddress);
bTokenAddress = bAddr;
bToken = ICustodianToken(bTokenAddress);
oracleAddress = oracleAddr;
oracle = IOracle(oracleAddress);
(uint priceInWei, uint timeInSecond) = oracle.getLastPrice();
require(priceInWei > 0 && timeInSecond > 0);
lastPriceInWei = priceInWei;
lastPriceTimeInSecond = timeInSecond;
resetPriceInWei = priceInWei;
resetPriceTimeInSecond = timeInSecond;
roleManager = IMultiSigManager(roleManagerAddress);
state = State.Trading;
emit AcceptPrice(priceInWei, timeInSecond, WEI_DENOMINATOR, WEI_DENOMINATOR);
emit StartTrading(navAInWei, navBInWei);
return true;
}
/// @dev create with ETH
function create()
public
payable
inState(State.Trading)
returns (bool)
{
return createInternal(msg.sender, msg.value);
}
/// @dev create with ETH
/// @param amount amount of WETH to create
/// @param wethAddr wrapEth contract address
function createWithWETH(uint amount, address wethAddr)
public
inState(State.Trading)
returns (bool success)
{
require(amount > 0 && wethAddr != address(0));
IWETH wethToken = IWETH(wethAddr);
wethToken.transferFrom(msg.sender, address(this), amount);
uint wethBalance = wethToken.balanceOf(address(this));
require(wethBalance >= amount);
uint beforeEthBalance = address(this).balance;
wethToken.withdraw(wethBalance);
uint ethIncrement = address(this).balance.sub(beforeEthBalance);
require(ethIncrement >= wethBalance);
return createInternal(msg.sender, amount);
}
function createInternal(address sender, uint ethAmtInWei)
internal
returns(bool)
{
require(ethAmtInWei > 0);
uint feeInWei;
(ethAmtInWei, feeInWei) = deductFee(ethAmtInWei, createCommInBP);
ethCollateralInWei = ethCollateralInWei.add(ethAmtInWei);
uint numeritor = ethAmtInWei
.mul(resetPriceInWei)
.mul(betaInWei)
.mul(BP_DENOMINATOR
);
uint denominator = WEI_DENOMINATOR
.mul(WEI_DENOMINATOR)
.mul(alphaInBP
.add(BP_DENOMINATOR)
);
uint tokenValueB = numeritor.div(denominator);
uint tokenValueA = tokenValueB.mul(alphaInBP).div(BP_DENOMINATOR);
balanceOf[0][sender] = balanceOf[0][sender].add(tokenValueA);
balanceOf[1][sender] = balanceOf[1][sender].add(tokenValueB);
checkUser(sender, balanceOf[0][sender], balanceOf[1][sender]);
totalSupplyA = totalSupplyA.add(tokenValueA);
totalSupplyB = totalSupplyB.add(tokenValueB);
emit Create(
sender,
ethAmtInWei,
tokenValueA,
tokenValueB,
feeInWei
);
emit TotalSupply(totalSupplyA, totalSupplyB);
aToken.emitTransfer(address(0), sender, tokenValueA);
bToken.emitTransfer(address(0), sender, tokenValueB);
return true;
}
function redeem(uint amtInWeiA, uint amtInWeiB)
public
inState(State.Trading)
returns (bool success)
{
uint adjAmtInWeiA = amtInWeiA.mul(BP_DENOMINATOR).div(alphaInBP);
uint deductAmtInWeiB = adjAmtInWeiA < amtInWeiB ? adjAmtInWeiA : amtInWeiB;
uint deductAmtInWeiA = deductAmtInWeiB.mul(alphaInBP).div(BP_DENOMINATOR);
address payable sender = msg.sender;
require(balanceOf[0][sender] >= deductAmtInWeiA && balanceOf[1][sender] >= deductAmtInWeiB);
uint ethAmtInWei = deductAmtInWeiA
.add(deductAmtInWeiB)
.mul(WEI_DENOMINATOR)
.mul(WEI_DENOMINATOR)
.div(resetPriceInWei)
.div(betaInWei);
return redeemInternal(sender, ethAmtInWei, deductAmtInWeiA, deductAmtInWeiB);
}
function redeemAll() public inState(State.Matured) returns (bool success) {
address payable sender = msg.sender;
uint balanceAInWei = balanceOf[0][sender];
uint balanceBInWei = balanceOf[1][sender];
require(balanceAInWei > 0 || balanceBInWei > 0);
uint ethAmtInWei = balanceAInWei
.mul(navAInWei)
.add(balanceBInWei
.mul(navBInWei))
.div(lastPriceInWei);
return redeemInternal(sender, ethAmtInWei, balanceAInWei, balanceBInWei);
}
function redeemInternal(
address payable sender,
uint ethAmtInWei,
uint deductAmtInWeiA,
uint deductAmtInWeiB)
internal
returns(bool)
{
require(ethAmtInWei > 0);
ethCollateralInWei = ethCollateralInWei.sub(ethAmtInWei);
uint feeInWei;
(ethAmtInWei, feeInWei) = deductFee(ethAmtInWei, redeemCommInBP);
balanceOf[0][sender] = balanceOf[0][sender].sub(deductAmtInWeiA);
balanceOf[1][sender] = balanceOf[1][sender].sub(deductAmtInWeiB);
checkUser(sender, balanceOf[0][sender], balanceOf[1][sender]);
totalSupplyA = totalSupplyA.sub(deductAmtInWeiA);
totalSupplyB = totalSupplyB.sub(deductAmtInWeiB);
sender.transfer(ethAmtInWei);
emit Redeem(
sender,
ethAmtInWei,
deductAmtInWeiA,
deductAmtInWeiB,
feeInWei
);
emit TotalSupply(totalSupplyA, totalSupplyB);
aToken.emitTransfer(sender, address(0), deductAmtInWeiA);
bToken.emitTransfer(sender, address(0), deductAmtInWeiB);
return true;
}
function deductFee(
uint ethAmtInWei,
uint commInBP
)
internal pure
returns (
uint ethAmtAfterFeeInWei,
uint feeInWei)
{
require(ethAmtInWei > 0);
feeInWei = ethAmtInWei.mul(commInBP).div(BP_DENOMINATOR);
ethAmtAfterFeeInWei = ethAmtInWei.sub(feeInWei);
}
// end of conversion
// start of operator functions
function setValue(uint idx, uint newValue) public only(operator) inState(State.Trading) inUpdateWindow() returns (bool success) {
uint oldValue;
if (idx == 0) {
require(newValue <= BP_DENOMINATOR);
oldValue = createCommInBP;
createCommInBP = newValue;
} else if (idx == 1) {
require(newValue <= BP_DENOMINATOR);
oldValue = redeemCommInBP;
redeemCommInBP = newValue;
} else if (idx == 2) {
oldValue = iterationGasThreshold;
iterationGasThreshold = newValue;
} else if (idx == 3) {
oldValue = preResetWaitingBlocks;
preResetWaitingBlocks = newValue;
} else {
revert();
}
emit SetValue(idx, oldValue, newValue);
return true;
}
// end of operator functions
function getStates() public view returns (uint[30] memory) {
return [
// managed
lastOperationTime,
operationCoolDown,
// custodian
uint(state),
minBalance,
totalSupplyA,
totalSupplyB,
ethCollateralInWei,
navAInWei,
navBInWei,
lastPriceInWei,
lastPriceTimeInSecond,
resetPriceInWei,
resetPriceTimeInSecond,
createCommInBP,
redeemCommInBP,
period,
maturityInSecond,
preResetWaitingBlocks,
priceFetchCoolDown,
nextResetAddrIndex,
totalUsers(),
feeBalanceInWei(),
// dual class custodian
uint(resetState),
alphaInBP,
betaInWei,
periodCouponInWei,
limitPeriodicInWei,
limitUpperInWei,
limitLowerInWei,
iterationGasThreshold
];
}
function getAddresses() public view returns (address[6] memory) {
return [
roleManagerAddress,
operator,
feeCollector,
oracleAddress,
aTokenAddress,
bTokenAddress
];
}
}
/// @title Beethoven - dual class token contract
/// @author duo.network
contract Beethoven is DualClassCustodian {
/*
* Storage
*/
// reset intermediate values
uint bAdj;
/*
* Constructor
*/
constructor(
string memory code,
uint maturity,
address roleManagerAddr,
address payable fc,
uint alpha,
uint r,
uint hp,
uint hu,
uint hd,
uint comm,
uint pd,
uint optCoolDown,
uint pxFetchCoolDown,
uint iteGasTh,
uint preResetWaitBlk,
uint minimumBalance
)
public
DualClassCustodian (
code,
maturity,
roleManagerAddr,
fc,
alpha,
r,
hp,
hu,
hd,
comm,
pd,
optCoolDown,
pxFetchCoolDown,
iteGasTh,
preResetWaitBlk,
minimumBalance
)
{
bAdj = alphaInBP.add(BP_DENOMINATOR).mul(WEI_DENOMINATOR).div(BP_DENOMINATOR);
}
// start of priceFetch funciton
function fetchPrice() public inState(State.Trading) returns (bool) {
uint currentTime = getNowTimestamp();
require(currentTime > lastPriceTimeInSecond.add(priceFetchCoolDown));
(uint priceInWei, uint timeInSecond) = oracle.getLastPrice();
require(timeInSecond > lastPriceTimeInSecond && timeInSecond <= currentTime && priceInWei > 0);
lastPriceInWei = priceInWei;
lastPriceTimeInSecond = timeInSecond;
(navAInWei, navBInWei) = calculateNav(
priceInWei,
timeInSecond,
resetPriceInWei,
resetPriceTimeInSecond,
betaInWei);
if (maturityInSecond > 0 && timeInSecond > maturityInSecond) {
state = State.Matured;
emit Matured(navAInWei, navBInWei);
} else if (navBInWei >= limitUpperInWei || navBInWei <= limitLowerInWei || (limitPeriodicInWei > 0 && navAInWei >= limitPeriodicInWei)) {
state = State.PreReset;
lastPreResetBlockNo = block.number;
emit StartPreReset();
}
emit AcceptPrice(priceInWei, timeInSecond, navAInWei, navBInWei);
return true;
}
function calculateNav(
uint priceInWei,
uint timeInSecond,
uint rstPriceInWei,
uint rstTimeInSecond,
uint bInWei)
internal
view
returns (uint, uint)
{
uint numOfPeriods = timeInSecond.sub(rstTimeInSecond).div(period);
uint navParent = priceInWei.mul(WEI_DENOMINATOR).div(rstPriceInWei);
navParent = navParent
.mul(WEI_DENOMINATOR)
.mul(alphaInBP.add(BP_DENOMINATOR))
.div(BP_DENOMINATOR)
.div(bInWei
);
uint navA = periodCouponInWei.mul(numOfPeriods).add(WEI_DENOMINATOR);
uint navAAdj = navA.mul(alphaInBP).div(BP_DENOMINATOR);
if (navParent <= navAAdj)
return (navParent.mul(BP_DENOMINATOR).div(alphaInBP), 0);
else
return (navA, navParent.sub(navAAdj));
}
// end of priceFetch function
// start of reset function
function startPreReset() public inState(State.PreReset) returns (bool success) {
if (block.number - lastPreResetBlockNo >= preResetWaitingBlocks) {
uint newBFromA;
uint newAFromA;
if (navBInWei >= limitUpperInWei) {
state = State.Reset;
resetState = ResetState.UpwardReset;
betaInWei = WEI_DENOMINATOR;
uint excessAInWei = navAInWei.sub(WEI_DENOMINATOR);
uint excessBInWei = navBInWei.sub(WEI_DENOMINATOR);
// excessive B is enough to cover excessive A
//if (excessBInWei >= excessAInWei) {
uint excessBAfterAInWei = excessBInWei.sub(excessAInWei);
newAFromAPerA = excessAInWei;
newBFromAPerA = 0;
uint newBFromExcessBPerB = excessBAfterAInWei.mul(betaInWei).div(bAdj);
newAFromBPerB = newBFromExcessBPerB.mul(alphaInBP).div(BP_DENOMINATOR);
newBFromBPerB = excessAInWei.add(newBFromExcessBPerB);
// ignore this case for now as it requires a very high coupon rate
// and very low upper limit for upward reset and a very high periodic limit
/*} else {
uint excessAForBInWei = excessBInWei.mul(alphaInBP).div(BP_DENOMINATOR);
uint excessAAfterBInWei = excessAInWei.sub(excessAForBInWei);
newAFromBPerB = 0;
newBFromBPerB = excessBInWei;
newBFromAPerA = excessAAfterBInWei.mul(betaInWei).div(bAdj);
newAFromAPerA = excessAForBInWei.add(newBFromAPerA.mul(alphaInBP).div(BP_DENOMINATOR));
}*/
// adjust total supply
totalSupplyA = totalSupplyA
.add(totalSupplyA
.mul(newAFromAPerA)
.add(totalSupplyB
.mul(newAFromBPerB))
.div(WEI_DENOMINATOR)
);
totalSupplyB = totalSupplyB
.add(totalSupplyA
.mul(newBFromAPerA)
.add(totalSupplyB
.mul(newBFromBPerB))
.div(WEI_DENOMINATOR)
);
} else if (navBInWei <= limitLowerInWei) {
state = State.Reset;
resetState = ResetState.DownwardReset;
betaInWei = WEI_DENOMINATOR;
newBFromAPerA = navAInWei.sub(navBInWei).mul(betaInWei).div(bAdj);
// below are not used and set to 0
newAFromAPerA = 0;
newBFromBPerB = 0;
newAFromBPerB = 0;
// adjust total supply
newBFromA = totalSupplyA.mul(newBFromAPerA).div(WEI_DENOMINATOR);
newAFromA = newBFromA.mul(alphaInBP).div(BP_DENOMINATOR);
totalSupplyA = totalSupplyA.mul(navBInWei).div(WEI_DENOMINATOR).add(newAFromA);
totalSupplyB = totalSupplyB.mul(navBInWei).div(WEI_DENOMINATOR).add(newBFromA);
} else { // limitPeriodicInWei > 0 && navAInWei >= limitPeriodicInWei
state = State.Reset;
resetState = ResetState.PeriodicReset;
uint num = alphaInBP
.add(BP_DENOMINATOR)
.mul(lastPriceInWei);
uint den = num
.sub(
resetPriceInWei
.mul(alphaInBP)
.mul(betaInWei)
.mul(navAInWei
.sub(WEI_DENOMINATOR))
.div(WEI_DENOMINATOR)
.div(WEI_DENOMINATOR)
);
betaInWei = betaInWei.mul(num).div(den);
newBFromAPerA = navAInWei.sub(WEI_DENOMINATOR).mul(betaInWei).div(bAdj);
// below are not used and set to 0
newBFromBPerB = 0;
newAFromAPerA = 0;
newAFromBPerB = 0;
// adjust total supply
newBFromA = totalSupplyA.mul(newBFromAPerA).div(WEI_DENOMINATOR);
newAFromA = newBFromA.mul(alphaInBP).div(BP_DENOMINATOR);
totalSupplyA = totalSupplyA.add(newAFromA);
totalSupplyB = totalSupplyB.add(newBFromA);
}
emit TotalSupply(totalSupplyA, totalSupplyB);
emit StartReset(nextResetAddrIndex, users.length);
} else
emit StartPreReset();
return true;
}
function startReset() public inState(State.Reset) returns (bool success) {
uint currentBalanceA;
uint currentBalanceB;
uint newBalanceA;
uint newBalanceB;
uint newAFromA;
uint newBFromA;
address currentAddress;
uint localResetAddrIndex = nextResetAddrIndex;
while (localResetAddrIndex < users.length && gasleft() > iterationGasThreshold) {
currentAddress = users[localResetAddrIndex];
currentBalanceA = balanceOf[0][currentAddress];
currentBalanceB = balanceOf[1][currentAddress];
if (resetState == ResetState.DownwardReset) {
newBFromA = currentBalanceA.mul(newBFromAPerA).div(WEI_DENOMINATOR);
newAFromA = newBFromA.mul(alphaInBP).div(BP_DENOMINATOR);
newBalanceA = currentBalanceA.mul(navBInWei).div(WEI_DENOMINATOR).add(newAFromA);
newBalanceB = currentBalanceB.mul(navBInWei).div(WEI_DENOMINATOR).add(newBFromA);
}
else if (resetState == ResetState.UpwardReset) {
newBalanceA = currentBalanceA
.add(currentBalanceA
.mul(newAFromAPerA)
.add(currentBalanceB
.mul(newAFromBPerB))
.div(WEI_DENOMINATOR)
);
newBalanceB = currentBalanceB
.add(currentBalanceA
.mul(newBFromAPerA)
.add(currentBalanceB
.mul(newBFromBPerB))
.div(WEI_DENOMINATOR)
);
} else {
newBFromA = currentBalanceA.mul(newBFromAPerA).div(WEI_DENOMINATOR);
newAFromA = newBFromA.mul(alphaInBP).div(BP_DENOMINATOR);
newBalanceA = currentBalanceA.add(newAFromA);
newBalanceB = currentBalanceB.add(newBFromA);
}
balanceOf[0][currentAddress] = newBalanceA;
balanceOf[1][currentAddress] = newBalanceB;
localResetAddrIndex++;
}
if (localResetAddrIndex >= users.length) {
if (resetState != ResetState.PeriodicReset) {
resetPriceInWei = lastPriceInWei;
navBInWei = WEI_DENOMINATOR;
}
resetPriceTimeInSecond = lastPriceTimeInSecond;
navAInWei = WEI_DENOMINATOR;
nextResetAddrIndex = 0;
state = State.Trading;
emit StartTrading(navAInWei, navBInWei);
return true;
} else {
nextResetAddrIndex = localResetAddrIndex;
emit StartReset(localResetAddrIndex, users.length);
return false;
}
}
// end of reset function
} | set at constructor
| uint minBalance = 10000000000000000; | 15,885,127 | [
1,
4625,
348,
7953,
560,
30,
225,
444,
622,
3885,
203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
11890,
1131,
13937,
273,
2130,
12648,
9449,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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: 0xf180e0f0b8ae56f01427817c2627f1fc75202929
//Contract name: Gods
//Balance: 0 Ether
//Verification Date: 5/9/2017
//Transacion Count: 3
// CODE STARTS HERE
pragma solidity ^0.4.2;
/* Родительский контракт */
contract Owned {
/* Адрес владельца контракта*/
address owner;
/* Конструктор контракта, вызывается при первом запуске */
function Owned() {
owner = msg.sender;
}
/* Изменить владельца контракта, newOwner - адрес нового владельца */
function changeOwner(address newOwner) onlyowner {
owner = newOwner;
}
/* Модификатор для ограничения доступа к функциям только для владельца */
modifier onlyowner() {
if (msg.sender==owner) _;
}
/* Удалить контракт */
function kill() onlyowner {
if (msg.sender == owner) suicide(owner);
}
}
/* Основной контракт, наследует контракт Owned */
contract Gods is Owned {
/* Структура представляющая участника */
struct Member {
address member;
string name;
string surname;
string patronymic;
uint birthDate;
string birthPlace;
string avatarHash;
uint avatarID;
bool approved;
uint memberSince;
}
/* Массив участников */
Member[] public members;
/* Маппинг адрес участника -> id участника */
mapping (address => uint) public memberId;
/* Маппинг id участника -> приватный ключ кошелька */
mapping (uint => string) public pks;
/* Маппинг id участника -> дополнительные данные на участника в формате JSON */
mapping (uint => string) public memberData;
/* Событие при добавлении участника, параметры - адрес, ID */
event MemberAdded(address member, uint id);
/* Событие при изменении участника, параметры - адрес, ID */
event MemberChanged(address member, uint id);
/* Конструктор контракта, вызывается при первом запуске */
function Gods() {
/* Добавляем пустого участника для инициализации */
addMember('', '', '', 0, '', '', 0, '');
}
/* функция добавления и обновления участника, параметры - адрес, имя, фамилия,
отчество, дата рождения (linux time), место рождения, хэш аватара, ID аватара
если пользователь с таким адресом не найден, то будет создан новый, в конце вызовется событие
MemberAdded, если пользователь найден, то будет произведено обновление полей и проставлен флаг
подтверждения approved */
function addMember(string name,
string surname,
string patronymic,
uint birthDate,
string birthPlace,
string avatarHash,
uint avatarID,
string data) onlyowner {
uint id;
address member = msg.sender;
if (memberId[member] == 0) {
memberId[member] = members.length;
id = members.length++;
members[id] = Member({
member: member,
name: name,
surname: surname,
patronymic: patronymic,
birthDate: birthDate,
birthPlace: birthPlace,
avatarHash: avatarHash,
avatarID: avatarID,
approved: (owner == member),
memberSince: now
});
memberData[id] = data;
if (member != 0) {
MemberAdded(member, id);
}
} else {
id = memberId[member];
Member m = members[id];
m.approved = true;
m.name = name;
m.surname = surname;
m.patronymic = patronymic;
m.birthDate = birthDate;
m.birthPlace = birthPlace;
m.avatarHash = avatarHash;
m.avatarID = avatarID;
memberData[id] = data;
MemberChanged(member, id);
}
}
/* Функция получения приватного ключа по ID юзера */
function getPK(uint id) onlyowner constant returns (string) {
return pks[id];
}
/* Функция получения количества юзеров */
function getMemberCount() constant returns (uint) {
return members.length - 1;
}
/* Функция получения юзера по id
возвращает массив из полей [имя, фамилия, отчество, дата_рождения, хэш аватара, id аватара] */
function getMember(uint id) constant returns (
string name,
string surname,
string patronymic,
uint birthDate,
string birthPlace,
string avatarHash,
uint avatarID,
string data) {
Member m = members[id];
name = m.name;
surname = m.surname;
patronymic = m.patronymic;
birthDate = m.birthDate;
birthPlace = m.birthPlace;
avatarHash = m.avatarHash;
avatarID = m.avatarID;
data = memberData[id];
}
}
| Функция получения приватного ключа по ID юзера */ | function getPK(uint id) onlyowner constant returns (string) {
return pks[id];
}
| 14,068,546 | [
1,
4625,
348,
7953,
560,
30,
225,
225,
145,
102,
146,
230,
145,
126,
145,
123,
146,
233,
145,
121,
146,
242,
225,
145,
128,
145,
127,
145,
124,
146,
230,
146,
234,
145,
118,
145,
126,
145,
121,
146,
242,
225,
145,
128,
146,
227,
145,
121,
145,
115,
145,
113,
146,
229,
145,
126,
145,
127,
145,
116,
145,
127,
225,
145,
123,
145,
124,
146,
241,
146,
234,
145,
113,
225,
145,
128,
145,
127,
1599,
225,
146,
241,
145,
120,
145,
118,
146,
227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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1689,
47,
12,
11890,
612,
13,
1338,
8443,
5381,
1135,
261,
1080,
13,
288,
203,
3639,
327,
24871,
63,
350,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/4/0x31d4Bb87526560A71A8bf5F599a661C70A8a4420/sources/LOAD.sol | 1:up 2:down 3.draw 0:default
| mapping(address => mapping(uint => uint8)) public userGuess; | 8,677,002 | [
1,
4625,
348,
7953,
560,
30,
225,
404,
30,
416,
565,
576,
30,
2378,
225,
890,
18,
9446,
282,
374,
30,
1886,
203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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-30
*/
pragma solidity >=0.4.24 <0.6.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) {
// 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 Select
* @dev Median Selection Library
*/
library Select {
using SafeMath for uint256;
/**
* @dev Sorts the input array up to the denoted size, and returns the median.
* @param array Input array to compute its median.
* @param size Number of elements in array to compute the median for.
* @return Median of array.
*/
function computeMedian(uint256[] array, uint256 size)
internal
pure
returns (uint256)
{
require(size > 0 && array.length >= size);
for (uint256 i = 1; i < size; i++) {
for (uint256 j = i; j > 0 && array[j - 1] > array[j]; j--) {
uint256 tmp = array[j];
array[j] = array[j - 1];
array[j - 1] = tmp;
}
}
if (size % 2 == 1) {
return array[size / 2];
} else {
return array[size / 2].add(array[size / 2 - 1]) / 2;
}
}
}
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool wasInitializing = initializing;
initializing = true;
initialized = true;
_;
initializing = wasInitializing;
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
uint256 cs;
assembly { cs := extcodesize(address) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable is Initializable {
address private _owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function initialize(address sender) public initializer {
_owner = sender;
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(_owner);
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[50] private ______gap;
}
interface IOracle {
function getData() external returns (uint256, bool);
}
/**
* @title Median Oracle
*
* @notice Provides a value onchain that's aggregated from a whitelisted set of
* providers.
*/
contract CommodityOracle is Ownable, IOracle {
using SafeMath for uint256;
struct Report {
uint256 timestamp;
uint256 payload;
}
// Addresses of providers authorized to push reports.
address[] public providers;
// Reports indexed by provider address. Report[0].timestamp > 0
// indicates provider existence.
mapping(address => Report[2]) public providerReports;
event ProviderAdded(address provider);
event ProviderRemoved(address provider);
event ReportTimestampOutOfRange(address provider);
event ProviderReportPushed(
address indexed provider,
uint256 payload,
uint256 timestamp
);
// The number of seconds after which the report is deemed expired.
uint256 public reportExpirationTimeSec;
// The number of seconds since reporting that has to pass before a report
// is usable.
uint256 public reportDelaySec;
// The minimum number of providers with valid reports to consider the
// aggregate report valid.
uint256 public minimumProviders = 1;
// Timestamp of 1 is used to mark uninitialized and invalidated data.
// This is needed so that timestamp of 1 is always considered expired.
uint256 private constant MAX_REPORT_EXPIRATION_TIME = 520 weeks;
/**
* @param reportExpirationTimeSec_ The number of seconds after which the
* report is deemed expired.
* @param reportDelaySec_ The number of seconds since reporting that has to
* pass before a report is usable
* @param minimumProviders_ The minimum number of providers with valid
* reports to consider the aggregate report valid.
*/
constructor(
uint256 reportExpirationTimeSec_,
uint256 reportDelaySec_,
uint256 minimumProviders_
) public {
require(reportExpirationTimeSec_ <= MAX_REPORT_EXPIRATION_TIME);
require(minimumProviders_ > 0);
Ownable.initialize(msg.sender);
reportExpirationTimeSec = reportExpirationTimeSec_;
reportDelaySec = reportDelaySec_;
minimumProviders = minimumProviders_;
}
/**
* @notice Sets the report expiration period.
* @param reportExpirationTimeSec_ The number of seconds after which the
* report is deemed expired.
*/
function setReportExpirationTimeSec(uint256 reportExpirationTimeSec_)
external
onlyOwner
{
require(reportExpirationTimeSec_ <= MAX_REPORT_EXPIRATION_TIME);
reportExpirationTimeSec = reportExpirationTimeSec_;
}
/**
* @notice Sets the time period since reporting that has to pass before a
* report is usable.
* @param reportDelaySec_ The new delay period in seconds.
*/
function setReportDelaySec(uint256 reportDelaySec_) external onlyOwner {
reportDelaySec = reportDelaySec_;
}
/**
* @notice Sets the minimum number of providers with valid reports to
* consider the aggregate report valid.
* @param minimumProviders_ The new minimum number of providers.
*/
function setMinimumProviders(uint256 minimumProviders_) external onlyOwner {
require(minimumProviders_ > 0);
minimumProviders = minimumProviders_;
}
/**
* @notice Pushes a report for the calling provider.
* @param payload is expected to be 18 decimal fixed point number.
*/
function pushReport(uint256 payload) external {
address providerAddress = msg.sender;
Report[2] storage reports = providerReports[providerAddress];
uint256[2] memory timestamps =
[reports[0].timestamp, reports[1].timestamp];
require(timestamps[0] > 0);
uint8 index_recent = timestamps[0] >= timestamps[1] ? 0 : 1;
uint8 index_past = 1 - index_recent;
// Check that the push is not too soon after the last one.
require(timestamps[index_recent].add(reportDelaySec) <= now);
reports[index_past].timestamp = now;
reports[index_past].payload = payload;
emit ProviderReportPushed(providerAddress, payload, now);
}
/**
* @notice Invalidates the reports of the calling provider.
*/
function purgeReports() external {
address providerAddress = msg.sender;
require(providerReports[providerAddress][0].timestamp > 0);
providerReports[providerAddress][0].timestamp = 1;
providerReports[providerAddress][1].timestamp = 1;
}
/**
* @notice Computes median of provider reports whose timestamps are in the
* valid timestamp range.
* @return AggregatedValue: Median of providers reported values.
* valid: Boolean indicating an aggregated value was computed successfully.
*/
function getData() external returns (uint256, bool) {
uint256 reportsCount = providers.length;
uint256[] memory validReports = new uint256[](reportsCount);
uint256 size = 0;
uint256 minValidTimestamp = now.sub(reportExpirationTimeSec);
uint256 maxValidTimestamp = now.sub(reportDelaySec);
for (uint256 i = 0; i < reportsCount; i++) {
address providerAddress = providers[i];
Report[2] memory reports = providerReports[providerAddress];
uint8 index_recent =
reports[0].timestamp >= reports[1].timestamp ? 0 : 1;
uint8 index_past = 1 - index_recent;
uint256 reportTimestampRecent = reports[index_recent].timestamp;
if (reportTimestampRecent > maxValidTimestamp) {
// Recent report is too recent.
uint256 reportTimestampPast =
providerReports[providerAddress][index_past].timestamp;
if (reportTimestampPast < minValidTimestamp) {
// Past report is too old.
emit ReportTimestampOutOfRange(providerAddress);
} else if (reportTimestampPast > maxValidTimestamp) {
// Past report is too recent.
emit ReportTimestampOutOfRange(providerAddress);
} else {
// Using past report.
validReports[size++] = providerReports[providerAddress][
index_past
]
.payload;
}
} else {
// Recent report is not too recent.
if (reportTimestampRecent < minValidTimestamp) {
// Recent report is too old.
emit ReportTimestampOutOfRange(providerAddress);
} else {
// Using recent report.
validReports[size++] = providerReports[providerAddress][
index_recent
]
.payload;
}
}
}
if (size < minimumProviders) {
return (0, false);
}
return (Select.computeMedian(validReports, size), true);
}
/**
* @notice Authorizes a provider.
* @param provider Address of the provider.
*/
function addProvider(address provider) external onlyOwner {
require(providerReports[provider][0].timestamp == 0);
providers.push(provider);
providerReports[provider][0].timestamp = 1;
emit ProviderAdded(provider);
}
/**
* @notice Revokes provider authorization.
* @param provider Address of the provider.
*/
function removeProvider(address provider) external onlyOwner {
delete providerReports[provider];
for (uint256 i = 0; i < providers.length; i++) {
if (providers[i] == provider) {
if (i + 1 != providers.length) {
providers[i] = providers[providers.length - 1];
}
providers.length--;
emit ProviderRemoved(provider);
break;
}
}
}
/**
* @return The number of authorized providers.
*/
function providersSize() external view returns (uint256) {
return providers.length;
}
} | Reserved storage space to allow for layout changes in the future. | uint256[50] private ______gap;
| 22,413 | [
1,
4625,
348,
7953,
560,
30,
225,
16237,
2502,
3476,
358,
1699,
364,
3511,
3478,
316,
326,
3563,
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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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1377,
2254,
5034,
63,
3361,
65,
3238,
389,
7198,
67,
14048,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xcAc012377C7C470C64EFD0c8776C788f774f5A88/sources/ManagerFactory.sol | File contracts/ManagerFactory.sol EOA to Manager | contract ManagerFactory is Authority {
using SafeMath for uint256;
address private tokenFactory = 0xCc83Dd82FB74B5056De897B68244D0895a9a07e4;
bytes32 private tokenTemplateKey =
0x000000000000000000000000644fE2731D8235216aA1DBfF4b4e844A9937173C;
address private UniswapV2Router =
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address private UniswapV2Factory =
0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address private managerTemplate;
mapping(address => address) public ownerToManager;
event DeployedManager(address indexed manager);
function newTemplate(address template, uint256 price)
external
returns (bytes32 key);
function updateTemplate(
bytes32 key,
address template,
uint256 price
) external;
function deleteTemplate(bytes32 key) external;
function newToken(
bytes32 key,
string memory version,
string memory name,
string memory symbol,
uint8 decimals
) external payable returns (address result);
function newTokenWithMint(
bytes32 key,
string memory version,
string memory name,
string memory symbol,
uint8 decimals,
uint256 amount
) external payable returns (address result);
function calculateNewTokenAddress(
bytes32 key,
string memory version,
string memory name,
string memory symbol,
uint8 decimals
) external view returns (address result);
}
pragma solidity ^0.6.0;
}
pragma solidity ^0.6.0;
constructor(address template) public {
Authority.initialize(msg.sender);
managerTemplate = template;
}
function newManager(
string calldata tokenName,
string calldata tokenSymbol,
uint256 mintingAmount,
uint256 requireAmount,
uint256 burningAmount
) external payable returns (address result) {
address token =
tokenTemplateKey,
"1",
tokenName,
tokenSymbol,
18,
mintingAmount
);
IERC20(token).approve(UniswapV2Router, uint256(-1));
(, , uint256 lpAmount) =
IUniswapV2Router02(UniswapV2Router).addLiquidityETH{
value: msg.value
}(
token,
mintingAmount,
mintingAmount,
msg.value,
address(this),
uint256(-1)
);
bytes memory initializationCalldata =
abi.encodeWithSelector(
IManagerInit(managerTemplate).initialize.selector,
msg.sender,
token,
requireAmount,
burningAmount
);
bytes memory create2Code =
abi.encodePacked(
type(Create2Maker).creationCode,
abi.encode(address(managerTemplate), initializationCalldata)
);
(bytes32 salt, ) = _getSaltAndTarget(create2Code);
assembly {
result := create2(
)
if iszero(result) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
address weth = IUniswapV2Router02(UniswapV2Router).WETH();
IUniswapV2Factory(UniswapV2Factory).getPair(token, weth);
require(lptoken != address(0), "Impossible");
emit DeployedManager(result);
}
ITokenFactory(tokenFactory).newTokenWithMint{value: 0 ether}(
function newManager(
string calldata tokenName,
string calldata tokenSymbol,
uint256 mintingAmount,
uint256 requireAmount,
uint256 burningAmount
) external payable returns (address result) {
address token =
tokenTemplateKey,
"1",
tokenName,
tokenSymbol,
18,
mintingAmount
);
IERC20(token).approve(UniswapV2Router, uint256(-1));
(, , uint256 lpAmount) =
IUniswapV2Router02(UniswapV2Router).addLiquidityETH{
value: msg.value
}(
token,
mintingAmount,
mintingAmount,
msg.value,
address(this),
uint256(-1)
);
bytes memory initializationCalldata =
abi.encodeWithSelector(
IManagerInit(managerTemplate).initialize.selector,
msg.sender,
token,
requireAmount,
burningAmount
);
bytes memory create2Code =
abi.encodePacked(
type(Create2Maker).creationCode,
abi.encode(address(managerTemplate), initializationCalldata)
);
(bytes32 salt, ) = _getSaltAndTarget(create2Code);
assembly {
result := create2(
)
if iszero(result) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
address weth = IUniswapV2Router02(UniswapV2Router).WETH();
IUniswapV2Factory(UniswapV2Factory).getPair(token, weth);
require(lptoken != address(0), "Impossible");
emit DeployedManager(result);
}
function newManager(
string calldata tokenName,
string calldata tokenSymbol,
uint256 mintingAmount,
uint256 requireAmount,
uint256 burningAmount
) external payable returns (address result) {
address token =
tokenTemplateKey,
"1",
tokenName,
tokenSymbol,
18,
mintingAmount
);
IERC20(token).approve(UniswapV2Router, uint256(-1));
(, , uint256 lpAmount) =
IUniswapV2Router02(UniswapV2Router).addLiquidityETH{
value: msg.value
}(
token,
mintingAmount,
mintingAmount,
msg.value,
address(this),
uint256(-1)
);
bytes memory initializationCalldata =
abi.encodeWithSelector(
IManagerInit(managerTemplate).initialize.selector,
msg.sender,
token,
requireAmount,
burningAmount
);
bytes memory create2Code =
abi.encodePacked(
type(Create2Maker).creationCode,
abi.encode(address(managerTemplate), initializationCalldata)
);
(bytes32 salt, ) = _getSaltAndTarget(create2Code);
assembly {
result := create2(
)
if iszero(result) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
address weth = IUniswapV2Router02(UniswapV2Router).WETH();
IUniswapV2Factory(UniswapV2Factory).getPair(token, weth);
require(lptoken != address(0), "Impossible");
emit DeployedManager(result);
}
function newManager(
string calldata tokenName,
string calldata tokenSymbol,
uint256 mintingAmount,
uint256 requireAmount,
uint256 burningAmount
) external payable returns (address result) {
address token =
tokenTemplateKey,
"1",
tokenName,
tokenSymbol,
18,
mintingAmount
);
IERC20(token).approve(UniswapV2Router, uint256(-1));
(, , uint256 lpAmount) =
IUniswapV2Router02(UniswapV2Router).addLiquidityETH{
value: msg.value
}(
token,
mintingAmount,
mintingAmount,
msg.value,
address(this),
uint256(-1)
);
bytes memory initializationCalldata =
abi.encodeWithSelector(
IManagerInit(managerTemplate).initialize.selector,
msg.sender,
token,
requireAmount,
burningAmount
);
bytes memory create2Code =
abi.encodePacked(
type(Create2Maker).creationCode,
abi.encode(address(managerTemplate), initializationCalldata)
);
(bytes32 salt, ) = _getSaltAndTarget(create2Code);
assembly {
result := create2(
)
if iszero(result) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
address weth = IUniswapV2Router02(UniswapV2Router).WETH();
IUniswapV2Factory(UniswapV2Factory).getPair(token, weth);
require(lptoken != address(0), "Impossible");
emit DeployedManager(result);
}
address lptoken =
function calculateNewManagerAddress(
string calldata tokenName,
string calldata tokenSymbol,
uint256 requireAmount,
uint256 burningAmount
) external view returns (address result) {
address tokenAddress =
ITokenFactory(tokenFactory).calculateNewTokenAddress(
tokenTemplateKey,
"1",
tokenName,
tokenSymbol,
18
);
bytes memory initializationCalldata =
abi.encodeWithSelector(
IManagerInit(managerTemplate).initialize.selector,
msg.sender,
tokenAddress,
requireAmount,
burningAmount
);
bytes memory initCode =
abi.encodePacked(
type(Create2Maker).creationCode,
abi.encode(address(managerTemplate), initializationCalldata)
);
(, result) = _getSaltAndTarget(initCode);
}
function _getSaltAndTarget(bytes memory initCode)
private
view
returns (bytes32 salt, address target)
{
bytes32 initCodeHash = keccak256(initCode);
uint256 nonce = 0;
bool exist;
while (true) {
salt = keccak256(abi.encodePacked(msg.sender, nonce));
)
)
)
)
);
assembly {
exist := gt(extcodesize(target), 0)
}
if (!exist) {
break;
}
}
}
function _getSaltAndTarget(bytes memory initCode)
private
view
returns (bytes32 salt, address target)
{
bytes32 initCodeHash = keccak256(initCode);
uint256 nonce = 0;
bool exist;
while (true) {
salt = keccak256(abi.encodePacked(msg.sender, nonce));
)
)
)
)
);
assembly {
exist := gt(extcodesize(target), 0)
}
if (!exist) {
break;
}
}
}
function _getSaltAndTarget(bytes memory initCode)
private
view
returns (bytes32 salt, address target)
{
bytes32 initCodeHash = keccak256(initCode);
uint256 nonce = 0;
bool exist;
while (true) {
salt = keccak256(abi.encodePacked(msg.sender, nonce));
)
)
)
)
);
assembly {
exist := gt(extcodesize(target), 0)
}
if (!exist) {
break;
}
}
}
function _getSaltAndTarget(bytes memory initCode)
private
view
returns (bytes32 salt, address target)
{
bytes32 initCodeHash = keccak256(initCode);
uint256 nonce = 0;
bool exist;
while (true) {
salt = keccak256(abi.encodePacked(msg.sender, nonce));
)
)
)
)
);
assembly {
exist := gt(extcodesize(target), 0)
}
if (!exist) {
break;
}
}
}
nonce++;
} | 16,891,800 | [
1,
4625,
348,
7953,
560,
30,
225,
1387,
20092,
19,
20012,
18,
18281,
512,
28202,
358,
8558,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
8558,
1733,
353,
6712,
560,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
1758,
3238,
1147,
1733,
273,
374,
14626,
71,
10261,
40,
72,
11149,
22201,
5608,
38,
3361,
4313,
758,
6675,
27,
38,
9470,
3247,
24,
40,
20,
6675,
25,
69,
29,
69,
8642,
73,
24,
31,
203,
565,
1731,
1578,
3238,
1147,
2283,
653,
273,
203,
3639,
374,
92,
12648,
12648,
12648,
22087,
74,
41,
5324,
6938,
40,
28,
4366,
9401,
2313,
69,
37,
21,
2290,
74,
42,
24,
70,
24,
73,
5193,
24,
37,
2733,
6418,
31331,
39,
31,
203,
565,
1758,
3238,
1351,
291,
91,
438,
58,
22,
8259,
273,
203,
3639,
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,
31,
203,
565,
1758,
3238,
1351,
291,
91,
438,
58,
22,
1733,
273,
203,
3639,
374,
92,
25,
39,
8148,
70,
41,
73,
27,
1611,
10241,
28,
3461,
69,
22,
38,
26,
69,
23,
2056,
40,
24,
38,
2313,
9401,
8876,
29,
952,
25,
69,
37,
26,
74,
31,
203,
565,
1758,
3238,
3301,
2283,
31,
203,
565,
2874,
12,
2867,
516,
1758,
13,
1071,
3410,
774,
1318,
31,
203,
203,
565,
871,
7406,
329,
1318,
12,
2867,
8808,
3301,
1769,
203,
203,
565,
445,
394,
2283,
12,
2867,
1542,
16,
2254,
5034,
6205,
13,
203,
3639,
3903,
203,
3639,
1135,
261,
3890,
1578,
498,
1769,
203,
203,
565,
445,
1089,
2283,
12,
203,
3639,
1731,
1578,
498,
16,
203,
3639,
1758,
1542,
16,
203,
3639,
2254,
5034,
6205,
203,
565,
262,
3903,
31,
203,
203,
565,
445,
1430,
2283,
12,
3890,
1578,
498,
13,
3903,
31,
203,
203,
565,
445,
394,
1345,
12,
203,
3639,
1731,
1578,
498,
16,
203,
3639,
533,
3778,
1177,
16,
203,
3639,
533,
3778,
508,
16,
203,
3639,
533,
3778,
3273,
16,
203,
3639,
2254,
28,
15105,
203,
565,
262,
3903,
8843,
429,
1135,
261,
2867,
563,
1769,
203,
203,
565,
445,
394,
1345,
1190,
49,
474,
12,
203,
3639,
1731,
1578,
498,
16,
203,
3639,
533,
3778,
1177,
16,
203,
3639,
533,
3778,
508,
16,
203,
3639,
533,
3778,
3273,
16,
203,
3639,
2254,
28,
15105,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3903,
8843,
429,
1135,
261,
2867,
563,
1769,
203,
203,
565,
445,
4604,
1908,
1345,
1887,
12,
203,
3639,
1731,
1578,
498,
16,
203,
3639,
533,
3778,
1177,
16,
203,
3639,
533,
3778,
508,
16,
203,
3639,
533,
3778,
3273,
16,
203,
3639,
2254,
28,
15105,
203,
565,
262,
3903,
1476,
1135,
261,
2867,
563,
1769,
203,
97,
203,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
26,
18,
20,
31,
203,
203,
97,
203,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
26,
18,
20,
31,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
565,
3885,
12,
2867,
1542,
13,
1071,
288,
203,
3639,
6712,
560,
18,
11160,
12,
3576,
18,
15330,
1769,
203,
3639,
3301,
2283,
273,
1542,
31,
203,
565,
289,
203,
203,
565,
445,
394,
1318,
12,
203,
3639,
533,
745,
892,
1147,
461,
16,
203,
3639,
533,
745,
892,
1147,
5335,
16,
203,
3639,
2254,
5034,
312,
474,
310,
6275,
16,
203,
3639,
2254,
5034,
2583,
6275,
16,
203,
3639,
2254,
5034,
18305,
310,
6275,
203,
565,
262,
3903,
8843,
429,
1135,
261,
2867,
563,
13,
288,
203,
3639,
1758,
1147,
273,
203,
7734,
1147,
2283,
653,
16,
203,
7734,
315,
21,
3113,
203,
7734,
1147,
461,
16,
203,
7734,
1147,
5335,
16,
203,
7734,
6549,
16,
203,
7734,
312,
474,
310,
6275,
203,
5411,
11272,
203,
203,
3639,
467,
654,
39,
3462,
12,
2316,
2934,
12908,
537,
12,
984,
291,
91,
438,
58,
22,
8259,
16,
2254,
5034,
19236,
21,
10019,
203,
3639,
261,
16,
269,
2254,
5034,
12423,
6275,
13,
273,
203,
5411,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
984,
291,
91,
438,
58,
22,
8259,
2934,
1289,
48,
18988,
24237,
1584,
44,
95,
203,
7734,
460,
30,
1234,
18,
1132,
203,
5411,
289,
12,
203,
7734,
1147,
16,
203,
7734,
312,
474,
310,
6275,
16,
203,
7734,
312,
474,
310,
6275,
16,
203,
7734,
1234,
18,
1132,
16,
203,
7734,
1758,
12,
2211,
3631,
203,
7734,
2254,
5034,
19236,
21,
13,
203,
5411,
11272,
203,
3639,
1731,
3778,
10313,
1477,
892,
273,
203,
5411,
24126,
18,
3015,
1190,
4320,
12,
203,
7734,
467,
1318,
2570,
12,
4181,
2283,
2934,
11160,
18,
9663,
16,
203,
7734,
1234,
18,
15330,
16,
203,
7734,
1147,
16,
203,
7734,
2583,
6275,
16,
203,
7734,
18305,
310,
6275,
203,
5411,
11272,
203,
203,
3639,
1731,
3778,
752,
22,
1085,
273,
203,
5411,
24126,
18,
3015,
4420,
329,
12,
203,
7734,
618,
12,
1684,
22,
12373,
2934,
17169,
1085,
16,
203,
7734,
24126,
18,
3015,
12,
2867,
12,
4181,
2283,
3631,
10313,
1477,
892,
13,
203,
5411,
11272,
203,
203,
3639,
261,
3890,
1578,
4286,
16,
262,
273,
389,
588,
19290,
1876,
2326,
12,
2640,
22,
1085,
1769,
203,
203,
3639,
19931,
288,
203,
5411,
563,
519,
752,
22,
12,
203,
5411,
262,
203,
203,
5411,
309,
353,
7124,
12,
2088,
13,
288,
203,
7734,
327,
892,
3530,
12,
20,
16,
374,
16,
327,
13178,
554,
10756,
203,
7734,
15226,
12,
20,
16,
327,
13178,
554,
10756,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
1758,
341,
546,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
984,
291,
91,
438,
58,
22,
8259,
2934,
59,
1584,
44,
5621,
203,
203,
5411,
467,
984,
291,
91,
438,
58,
22,
1733,
12,
984,
291,
91,
438,
58,
22,
1733,
2934,
588,
4154,
12,
2316,
16,
341,
546,
1769,
203,
3639,
2583,
12,
80,
337,
969,
480,
1758,
12,
20,
3631,
315,
1170,
12708,
8863,
203,
3639,
3626,
7406,
329,
1318,
12,
2088,
1769,
203,
565,
289,
203,
203,
5411,
467,
1345,
1733,
12,
2316,
1733,
2934,
2704,
1345,
1190,
49,
474,
95,
1132,
30,
374,
225,
2437,
97,
12,
203,
565,
445,
394,
1318,
12,
203,
3639,
533,
745,
892,
1147,
461,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./IFateRewardController.sol";
import "./IRewardSchedule.sol";
import "./MockLpToken.sol";
import "./IMockLpTokenFactory.sol";
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once FATE is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract FateRewardControllerV2 is IFateRewardController {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfoV2 {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
bool isUpdated; // true if the user has been migrated from the v1 controller to v2
//
// We do some fancy math here. Basically, any point in time, the amount of FATEs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accumulatedFatePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accumulatedFatePerShare` (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.
}
IERC20 public override fate;
address public override vault;
IFateRewardController[] public oldControllers;
// The emission scheduler that calculates fate per block over a given period
IRewardSchedule public override emissionSchedule;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public override migrator;
// Info of each pool.
PoolInfo[] public override poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfoV2)) internal _userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public override totalAllocPoint = 0;
// The block number when FATE mining starts.
uint256 public override startBlock;
IMockLpTokenFactory public mockLpTokenFactory;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event ClaimRewards(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmissionScheduleSet(address indexed emissionSchedule);
event MigratorSet(address indexed migrator);
event VaultSet(address indexed emissionSchedule);
event PoolAdded(uint indexed pid, address indexed lpToken, uint allocPoint);
event PoolAllocPointSet(uint indexed pid, uint allocPoint);
constructor(
IERC20 _fate,
IRewardSchedule _emissionSchedule,
address _vault,
IFateRewardController[] memory _oldControllers,
IMockLpTokenFactory _mockLpTokenFactory
) public {
fate = _fate;
emissionSchedule = _emissionSchedule;
vault = _vault;
oldControllers = _oldControllers;
mockLpTokenFactory = _mockLpTokenFactory;
startBlock = _oldControllers[0].startBlock();
}
function poolLength() external override 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 override onlyOwner {
for (uint i = 0; i < poolInfo.length; i++) {
require(
poolInfo[i].lpToken != _lpToken,
"add: LP token already added"
);
}
if (_withUpdate) {
massUpdatePools();
}
require(
_lpToken.balanceOf(address(this)) >= 0,
"add: invalid LP token"
);
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken : _lpToken,
allocPoint : _allocPoint,
lastRewardBlock : lastRewardBlock,
accumulatedFatePerShare : 0
})
);
emit PoolAdded(poolInfo.length - 1, address(_lpToken), _allocPoint);
}
// Update the given pool's FATE 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;
emit PoolAllocPointSet(_pid, _allocPoint);
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public override onlyOwner {
migrator = _migrator;
emit MigratorSet(address(_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 override {
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;
}
function migrate(
IERC20 token
) external override returns (IERC20) {
IFateRewardController oldController = IFateRewardController(address(0));
for (uint i = 0; i < oldControllers.length; i++) {
if (address(oldControllers[i]) == msg.sender) {
oldController = oldControllers[i];
}
}
require(
address(oldController) != address(0),
"migrate: invalid sender"
);
IERC20 lpToken;
uint256 allocPoint;
uint256 lastRewardBlock;
uint256 accumulatedFatePerShare;
uint oldPoolLength = oldController.poolLength();
for (uint i = 0; i < oldPoolLength; i++) {
(lpToken, allocPoint, lastRewardBlock, accumulatedFatePerShare) = oldController.poolInfo(poolInfo.length);
if (address(lpToken) == address(token)) {
break;
}
}
// transfer all of the tokens from the previous controller to here
token.transferFrom(msg.sender, address(this), token.balanceOf(msg.sender));
poolInfo.push(
PoolInfo({
lpToken : lpToken,
allocPoint : allocPoint,
lastRewardBlock : lastRewardBlock,
accumulatedFatePerShare : accumulatedFatePerShare
})
);
emit PoolAdded(poolInfo.length - 1, address(token), allocPoint);
uint _totalAllocPoint = 0;
for (uint i = 0; i < poolInfo.length; i++) {
_totalAllocPoint = _totalAllocPoint.add(poolInfo[i].allocPoint);
}
totalAllocPoint = _totalAllocPoint;
return IERC20(mockLpTokenFactory.create(address(lpToken), address(this)));
}
function userInfo(
uint _pid,
address _user
) public override view returns (uint amount, uint rewardDebt) {
UserInfoV2 memory user = _userInfo[_pid][_user];
if (user.isUpdated) {
return (user.amount, user.rewardDebt);
} else {
return oldControllers[0].userInfo(_pid, _user);
}
}
function _getUserInfo(
uint _pid,
address _user
) internal view returns (IFateRewardController.UserInfo memory) {
UserInfoV2 memory user = _userInfo[_pid][_user];
if (user.isUpdated) {
return IFateRewardController.UserInfo(user.amount, user.rewardDebt);
} else {
(uint amount, uint rewardDebt) = oldControllers[0].userInfo(_pid, _user);
return IFateRewardController.UserInfo(amount, rewardDebt);
}
}
// View function to see pending FATE tokens on frontend.
function pendingFate(uint256 _pid, address _user)
external
override
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
IFateRewardController.UserInfo memory user = _getUserInfo(_pid, _user);
uint256 accumulatedFatePerShare = pool.accumulatedFatePerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 fatePerBlock = emissionSchedule.getFatePerBlock(startBlock, pool.lastRewardBlock, block.number);
uint256 fateReward = fatePerBlock.mul(pool.allocPoint).div(totalAllocPoint);
accumulatedFatePerShare = accumulatedFatePerShare.add(fateReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accumulatedFatePerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function getNewRewardPerBlock(uint pid1) public view returns (uint) {
uint256 fatePerBlock = emissionSchedule.getFatePerBlock(startBlock, block.number - 1, block.number);
if (pid1 == 0) {
return fatePerBlock;
} else {
return fatePerBlock.mul(poolInfo[pid1 - 1].allocPoint).div(totalAllocPoint);
}
}
// 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 fatePerBlock = emissionSchedule.getFatePerBlock(startBlock, pool.lastRewardBlock, block.number);
uint256 fateReward = fatePerBlock.mul(pool.allocPoint).div(totalAllocPoint);
if (fateReward > 0) {
fate.transferFrom(vault, address(this), fateReward);
pool.accumulatedFatePerShare = pool.accumulatedFatePerShare.add(fateReward.mul(1e12).div(lpSupply));
}
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for FATE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
IFateRewardController.UserInfo memory user = _getUserInfo(_pid, msg.sender);
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accumulatedFatePerShare).div(1e12).sub(user.rewardDebt);
_safeFateTransfer(msg.sender, pending);
emit ClaimRewards(msg.sender, _pid, pending);
}
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
uint userBalance = user.amount.add(_amount);
_userInfo[_pid][msg.sender] = UserInfoV2({
amount : userBalance,
rewardDebt : userBalance.mul(pool.accumulatedFatePerShare).div(1e12),
isUpdated : true
});
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
IFateRewardController.UserInfo memory user = _getUserInfo(_pid, msg.sender);
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accumulatedFatePerShare).div(1e12).sub(user.rewardDebt);
_safeFateTransfer(msg.sender, pending);
emit ClaimRewards(msg.sender, _pid, pending);
uint userBalance = user.amount.sub(_amount);
_userInfo[_pid][msg.sender] = UserInfoV2({
amount : userBalance,
rewardDebt : userBalance.mul(pool.accumulatedFatePerShare).div(1e12),
isUpdated : true
});
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// claim any pending rewards from this pool, from msg.sender
function claimReward(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
IFateRewardController.UserInfo memory user = _getUserInfo(_pid, msg.sender);
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accumulatedFatePerShare).div(1e12).sub(user.rewardDebt);
_safeFateTransfer(msg.sender, pending);
emit ClaimRewards(msg.sender, _pid, pending);
_userInfo[_pid][msg.sender] = UserInfoV2({
amount : user.amount,
rewardDebt : user.amount.mul(pool.accumulatedFatePerShare).div(1e12),
isUpdated : true
});
}
// claim any pending rewards from this pool, from msg.sender
function claimRewards(uint256[] calldata _pids) external {
for (uint i = 0; i < _pids.length; i++) {
claimReward(_pids[i]);
}
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
IFateRewardController.UserInfo memory user = _getUserInfo(_pid, msg.sender);
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
_userInfo[_pid][msg.sender] = UserInfoV2({
amount : 0,
rewardDebt : 0,
isUpdated : true
});
}
// Safe fate transfer function, just in case if rounding error causes pool to not have enough FATEs.
function _safeFateTransfer(address _to, uint256 _amount) internal {
uint256 fateBal = fate.balanceOf(address(this));
if (_amount > fateBal) {
fate.transfer(_to, fateBal);
} else {
fate.transfer(_to, _amount);
}
}
function setEmissionSchedule(
IRewardSchedule _emissionSchedule
)
public
onlyOwner {
// pro-rate the pools to the current block, before changing the schedule
massUpdatePools();
emissionSchedule = _emissionSchedule;
emit EmissionScheduleSet(address(_emissionSchedule));
}
function setVault(
address _vault
)
public
override
onlyOwner {
// pro-rate the pools to the current block, before changing the schedule
vault = _vault;
emit VaultSet(_vault);
}
}
| Safe fate transfer function, just in case if rounding error causes pool to not have enough FATEs. | function _safeFateTransfer(address _to, uint256 _amount) internal {
uint256 fateBal = fate.balanceOf(address(this));
if (_amount > fateBal) {
fate.transfer(_to, fateBal);
fate.transfer(_to, _amount);
}
}
| 14,083,717 | [
1,
4625,
348,
7953,
560,
30,
225,
14060,
284,
340,
7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,
340,
5912,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
2713,
288,
203,
3639,
2254,
5034,
284,
340,
38,
287,
273,
284,
340,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
67,
8949,
405,
284,
340,
38,
287,
13,
288,
203,
5411,
284,
340,
18,
13866,
24899,
869,
16,
284,
340,
38,
287,
1769,
203,
5411,
284,
340,
18,
13866,
24899,
869,
16,
389,
8949,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
/**
* @title Queue
* @dev Data structure contract used in `Crowdsale.sol`
* Allows buyers to line up on a first-in-first-out basis
* See this example: http://interactivepython.org/courselib/static/pythonds/BasicDS/ImplementingaQueueinPython.html
*/
import './utils/SafeMath.sol';
contract Queue {
/* State variables */
uint8 size = 5;
uint256 timeLimit;
struct Buyer {
address addr;
uint256 entryTime;
}
mapping(uint8 => Buyer) queue;
uint8 first;
uint8 last;
/* Add events */
event TimeUp(address ejectedBuyerAddress);
/* Add constructor */
constructor(uint256 _timeLimit) public {
timeLimit = _timeLimit;
first = 1;
last = 0;
}
/* Returns the number of people waiting in line */
function qsize() view public returns(uint8) {
//TODO: Unsafe?
return last - first + 1;
}
/* Returns whether the queue is empty or not */
function empty() view public returns(bool) {
return (last < first);
}
/* Returns the address of the person in the front of the queue */
function getFirst() view public returns(address) {
return queue[first].addr;
}
/* Allows `msg.sender` to check their position in the queue */
function checkPlace() view public returns(uint8) {
for(uint8 i = first; i < last; ++i){
if(msg.sender == queue[i].addr) return (i - first + 1);
}
return 0; // for not in queue
}
/* Allows anyone to expel the first person in line if their time
* limit is up
*/
function checkTime() public {
if(SafeMath.sub(now, queue[first].entryTime) > timeLimit){
dequeue();
}
}
/* Removes the first person in line; either when their time is up or when
* they are done with their purchase
*/
function dequeue() public {
require(first <= last);
delete queue[first];
first += 1;
}
/* Places `addr` in the first empty position in the queue */
function enqueue(address addr) public {
last += 1;
queue[last] = Buyer(addr, now);
}
}
| Returns the number of people waiting in line */TODO: Unsafe? | function qsize() view public returns(uint8) {
return last - first + 1;
}
| 13,010,429 | [
1,
4625,
348,
7953,
560,
30,
225,
2860,
326,
1300,
434,
16951,
7336,
316,
980,
1195,
6241,
30,
27476,
35,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1043,
1467,
1435,
1476,
1071,
1135,
12,
11890,
28,
13,
288,
203,
202,
202,
2463,
1142,
300,
1122,
397,
404,
31,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x18d9244DC85306DBc0AAE16cF8FAE9aEFAee7530/sources/ForbitswapRouter.sol | performs chained getAmountOut calculations on any number of pairs | function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'ForbitswapLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
| 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
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
24418,
87,
1182,
12,
2867,
3272,
16,
2254,
3844,
382,
16,
1758,
8526,
3778,
589,
13,
2713,
1476,
1135,
261,
11890,
8526,
3778,
30980,
13,
288,
203,
3639,
2583,
12,
803,
18,
2469,
1545,
576,
16,
296,
1290,
6789,
91,
438,
9313,
30,
10071,
67,
4211,
8284,
203,
3639,
30980,
273,
394,
2254,
8526,
12,
803,
18,
2469,
1769,
203,
3639,
30980,
63,
20,
65,
273,
3844,
382,
31,
203,
3639,
364,
261,
11890,
277,
31,
277,
411,
589,
18,
2469,
300,
404,
31,
277,
27245,
288,
203,
5411,
261,
11890,
20501,
382,
16,
2254,
20501,
1182,
13,
273,
31792,
264,
3324,
12,
6848,
16,
589,
63,
77,
6487,
589,
63,
77,
397,
404,
19226,
203,
5411,
30980,
63,
77,
397,
404,
65,
273,
24418,
1182,
12,
8949,
87,
63,
77,
6487,
20501,
382,
16,
20501,
1182,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.10;
//pragma experimental ABIEncoderV2;
// functions for recovering and managing Ethereum account ECDSA signatures
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
// MultisigWallet Factory
import "./MultisigWalletFactory.sol";
contract MultisigWallet {
MultisigWalletFactory public multisigWalletFactory;
// Pass the bytes32 as the first parameter when calling the ECDSA functions
using ECDSA for bytes32;
// Deposit event
event Deposit(address indexed sender, uint256 amount, uint256 balance);
// ExecuteTransactions event from calldata
event ExecuteTransaction(
address indexed owner,
address payable to,
uint256 value,
bytes data,
uint256 nonce,
bytes32 hash,
bytes result
);
event Owner(address indexed owner, bool added);
// Keep track of the MultisigWallet Owners
address[] public owners;
mapping(address => bool) public isOwner;
uint256 public nonce;
uint256 public chainId;
uint256 public signaturesRequired;
// Only Owners of the MultisigWallet
modifier onlyOwner() {
require(isOwner[msg.sender], "Not Owner");
_;
}
// Only the MultisigWallet instance
modifier onlySelf() {
require(msg.sender == address(this), "Not Self");
_;
}
// Non Zero signatures
modifier nonZeroSignatures(uint256 _signaturesRequired) {
require(_signaturesRequired > 0, "Must be non-zero sigs required");
_;
}
constructor(
uint256 _chainId,
address[] memory _initialOwners,
uint256 _signaturesRequired,
address _factory
) payable nonZeroSignatures(_signaturesRequired) {
multisigWalletFactory = MultisigWalletFactory(_factory);
signaturesRequired = _signaturesRequired;
// Validate Owners & Signatures required
require(_initialOwners.length > 0, "Owners required");
require(
_signaturesRequired > 0 &&
_signaturesRequired <= _initialOwners.length,
"Invalid required number of owners"
);
// Update MultisigWallet Owners
for (uint256 i; i < _initialOwners.length; i++) {
address owner = _initialOwners[i];
require(owner != address(0), "invalid owner");
require(!isOwner[owner], "Owner is not unique");
isOwner[owner] = true;
owners.push(owner);
emit Owner(owner, isOwner[owner]);
}
chainId = _chainId;
}
// Enable receiving deposits
receive() external payable {
emit Deposit(msg.sender, msg.value, address(this).balance);
}
// Get the transaction hash
function getTransactionHash(
uint256 _nonce,
address _to,
uint256 _value,
bytes memory _data
) public view returns (bytes32) {
return
keccak256(
abi.encodePacked(
address(this),
chainId,
_nonce,
_to,
_value,
_data
)
);
}
// Returns the address that signed a hashed message (`hash`) with `signature`.
function recover(bytes32 _hash, bytes memory _signature)
public
pure
returns (address)
{
return _hash.toEthSignedMessageHash().recover(_signature);
}
// Excute the calldata transaction
function executeTransaction(
address payable _to,
uint256 _value,
bytes memory _data,
bytes[] memory _signatures
) public onlyOwner returns (bytes memory) {
bytes32 _hash = getTransactionHash(nonce, _to, _value, _data);
nonce++;
// Valid signatures counter
uint256 validSignatures;
address duplicateGuard;
// Recover the signing addresess and validate if unique and update valid signatures
for (uint256 i = 0; i < _signatures.length; i++) {
address recovered = recover(_hash, _signatures[i]);
require(
recovered > duplicateGuard,
"executeTransaction: duplicate or unordered signatures"
);
duplicateGuard = recovered;
if (isOwner[recovered]) {
validSignatures++;
}
}
// Validate number of signatures against required
require(
validSignatures >= signaturesRequired,
"executeTransaction: not enough valid signatures"
);
// Execute the calldata
(bool success, bytes memory result) = _to.call{value: _value}(_data);
require(success, "executeTransaction: tx failed");
// Emit the ExecuteTransaction event
emit ExecuteTransaction(
msg.sender,
_to,
_value,
_data,
nonce - 1,
_hash,
result
);
return result;
}
// Add a new Owner
function addOwner(address _newOwner, uint256 _newSignaturesRequired)
public
onlySelf
nonZeroSignatures(_newSignaturesRequired)
{
require(_newOwner != address(0), "addSigner: zero address");
require(!isOwner[_newOwner], "addSigner: owner not unique");
isOwner[_newOwner] = true;
owners.push(_newOwner);
signaturesRequired = _newSignaturesRequired;
emit Owner(_newOwner, isOwner[_newOwner]);
multisigWalletFactory.emitOwners(
address(this),
owners,
_newSignaturesRequired
);
}
// Remove a Owner
function removeOwner(address _oldOwner, uint256 _newSignaturesRequired)
public
onlySelf
nonZeroSignatures(_newSignaturesRequired)
{
require(isOwner[_oldOwner], "removeSigner: not owner");
_removeOwnerList(_oldOwner);
signaturesRequired = _newSignaturesRequired;
emit Owner(_oldOwner, isOwner[_oldOwner]);
multisigWalletFactory.emitOwners(
address(this),
owners,
_newSignaturesRequired
);
}
// Pop Owner from the list
function _removeOwnerList(address _oldOwner) private {
isOwner[_oldOwner] = false;
uint256 ownersLength = owners.length;
address[] memory poppedOwners = new address[](owners.length);
for (uint256 i = ownersLength - 1; i >= 0; i--) {
if (owners[i] != _oldOwner) {
poppedOwners[i] = owners[i];
owners.pop();
} else {
owners.pop();
for (uint256 j = i; j < ownersLength - 1; j++) {
owners.push(poppedOwners[j]);
}
return;
}
}
}
}
| Pass the bytes32 as the first parameter when calling the ECDSA functions Deposit event ExecuteTransactions event from calldata Keep track of the MultisigWallet Owners Only Owners of the MultisigWallet | contract MultisigWallet {
MultisigWalletFactory public multisigWalletFactory;
using ECDSA for bytes32;
event Deposit(address indexed sender, uint256 amount, uint256 balance);
event ExecuteTransaction(
address indexed owner,
address payable to,
uint256 value,
bytes data,
uint256 nonce,
bytes32 hash,
bytes result
);
event Owner(address indexed owner, bool added);
address[] public owners;
mapping(address => bool) public isOwner;
uint256 public nonce;
uint256 public chainId;
uint256 public signaturesRequired;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./MultisigWalletFactory.sol";
modifier onlyOwner() {
require(isOwner[msg.sender], "Not Owner");
_;
}
modifier onlySelf() {
require(msg.sender == address(this), "Not Self");
_;
}
modifier nonZeroSignatures(uint256 _signaturesRequired) {
require(_signaturesRequired > 0, "Must be non-zero sigs required");
_;
}
constructor(
uint256 _chainId,
address[] memory _initialOwners,
uint256 _signaturesRequired,
address _factory
) payable nonZeroSignatures(_signaturesRequired) {
multisigWalletFactory = MultisigWalletFactory(_factory);
signaturesRequired = _signaturesRequired;
require(_initialOwners.length > 0, "Owners required");
require(
_signaturesRequired > 0 &&
_signaturesRequired <= _initialOwners.length,
"Invalid required number of owners"
);
for (uint256 i; i < _initialOwners.length; i++) {
address owner = _initialOwners[i];
require(owner != address(0), "invalid owner");
require(!isOwner[owner], "Owner is not unique");
isOwner[owner] = true;
owners.push(owner);
emit Owner(owner, isOwner[owner]);
}
chainId = _chainId;
}
) payable nonZeroSignatures(_signaturesRequired) {
multisigWalletFactory = MultisigWalletFactory(_factory);
signaturesRequired = _signaturesRequired;
require(_initialOwners.length > 0, "Owners required");
require(
_signaturesRequired > 0 &&
_signaturesRequired <= _initialOwners.length,
"Invalid required number of owners"
);
for (uint256 i; i < _initialOwners.length; i++) {
address owner = _initialOwners[i];
require(owner != address(0), "invalid owner");
require(!isOwner[owner], "Owner is not unique");
isOwner[owner] = true;
owners.push(owner);
emit Owner(owner, isOwner[owner]);
}
chainId = _chainId;
}
receive() external payable {
emit Deposit(msg.sender, msg.value, address(this).balance);
}
function getTransactionHash(
uint256 _nonce,
address _to,
uint256 _value,
bytes memory _data
) public view returns (bytes32) {
return
keccak256(
abi.encodePacked(
address(this),
chainId,
_nonce,
_to,
_value,
_data
)
);
}
function recover(bytes32 _hash, bytes memory _signature)
public
pure
returns (address)
{
return _hash.toEthSignedMessageHash().recover(_signature);
}
function executeTransaction(
address payable _to,
uint256 _value,
bytes memory _data,
bytes[] memory _signatures
) public onlyOwner returns (bytes memory) {
bytes32 _hash = getTransactionHash(nonce, _to, _value, _data);
nonce++;
uint256 validSignatures;
address duplicateGuard;
for (uint256 i = 0; i < _signatures.length; i++) {
address recovered = recover(_hash, _signatures[i]);
require(
recovered > duplicateGuard,
"executeTransaction: duplicate or unordered signatures"
);
duplicateGuard = recovered;
if (isOwner[recovered]) {
validSignatures++;
}
}
validSignatures >= signaturesRequired,
"executeTransaction: not enough valid signatures"
);
require(success, "executeTransaction: tx failed");
msg.sender,
_to,
_value,
_data,
nonce - 1,
_hash,
result
);
return result;
}
function executeTransaction(
address payable _to,
uint256 _value,
bytes memory _data,
bytes[] memory _signatures
) public onlyOwner returns (bytes memory) {
bytes32 _hash = getTransactionHash(nonce, _to, _value, _data);
nonce++;
uint256 validSignatures;
address duplicateGuard;
for (uint256 i = 0; i < _signatures.length; i++) {
address recovered = recover(_hash, _signatures[i]);
require(
recovered > duplicateGuard,
"executeTransaction: duplicate or unordered signatures"
);
duplicateGuard = recovered;
if (isOwner[recovered]) {
validSignatures++;
}
}
validSignatures >= signaturesRequired,
"executeTransaction: not enough valid signatures"
);
require(success, "executeTransaction: tx failed");
msg.sender,
_to,
_value,
_data,
nonce - 1,
_hash,
result
);
return result;
}
function executeTransaction(
address payable _to,
uint256 _value,
bytes memory _data,
bytes[] memory _signatures
) public onlyOwner returns (bytes memory) {
bytes32 _hash = getTransactionHash(nonce, _to, _value, _data);
nonce++;
uint256 validSignatures;
address duplicateGuard;
for (uint256 i = 0; i < _signatures.length; i++) {
address recovered = recover(_hash, _signatures[i]);
require(
recovered > duplicateGuard,
"executeTransaction: duplicate or unordered signatures"
);
duplicateGuard = recovered;
if (isOwner[recovered]) {
validSignatures++;
}
}
validSignatures >= signaturesRequired,
"executeTransaction: not enough valid signatures"
);
require(success, "executeTransaction: tx failed");
msg.sender,
_to,
_value,
_data,
nonce - 1,
_hash,
result
);
return result;
}
require(
(bool success, bytes memory result) = _to.call{value: _value}(_data);
emit ExecuteTransaction(
function addOwner(address _newOwner, uint256 _newSignaturesRequired)
public
onlySelf
nonZeroSignatures(_newSignaturesRequired)
{
require(_newOwner != address(0), "addSigner: zero address");
require(!isOwner[_newOwner], "addSigner: owner not unique");
isOwner[_newOwner] = true;
owners.push(_newOwner);
signaturesRequired = _newSignaturesRequired;
emit Owner(_newOwner, isOwner[_newOwner]);
multisigWalletFactory.emitOwners(
address(this),
owners,
_newSignaturesRequired
);
}
function removeOwner(address _oldOwner, uint256 _newSignaturesRequired)
public
onlySelf
nonZeroSignatures(_newSignaturesRequired)
{
require(isOwner[_oldOwner], "removeSigner: not owner");
_removeOwnerList(_oldOwner);
signaturesRequired = _newSignaturesRequired;
emit Owner(_oldOwner, isOwner[_oldOwner]);
multisigWalletFactory.emitOwners(
address(this),
owners,
_newSignaturesRequired
);
}
function _removeOwnerList(address _oldOwner) private {
isOwner[_oldOwner] = false;
uint256 ownersLength = owners.length;
address[] memory poppedOwners = new address[](owners.length);
for (uint256 i = ownersLength - 1; i >= 0; i--) {
if (owners[i] != _oldOwner) {
poppedOwners[i] = owners[i];
owners.pop();
owners.pop();
for (uint256 j = i; j < ownersLength - 1; j++) {
owners.push(poppedOwners[j]);
}
return;
}
}
}
function _removeOwnerList(address _oldOwner) private {
isOwner[_oldOwner] = false;
uint256 ownersLength = owners.length;
address[] memory poppedOwners = new address[](owners.length);
for (uint256 i = ownersLength - 1; i >= 0; i--) {
if (owners[i] != _oldOwner) {
poppedOwners[i] = owners[i];
owners.pop();
owners.pop();
for (uint256 j = i; j < ownersLength - 1; j++) {
owners.push(poppedOwners[j]);
}
return;
}
}
}
function _removeOwnerList(address _oldOwner) private {
isOwner[_oldOwner] = false;
uint256 ownersLength = owners.length;
address[] memory poppedOwners = new address[](owners.length);
for (uint256 i = ownersLength - 1; i >= 0; i--) {
if (owners[i] != _oldOwner) {
poppedOwners[i] = owners[i];
owners.pop();
owners.pop();
for (uint256 j = i; j < ownersLength - 1; j++) {
owners.push(poppedOwners[j]);
}
return;
}
}
}
} else {
function _removeOwnerList(address _oldOwner) private {
isOwner[_oldOwner] = false;
uint256 ownersLength = owners.length;
address[] memory poppedOwners = new address[](owners.length);
for (uint256 i = ownersLength - 1; i >= 0; i--) {
if (owners[i] != _oldOwner) {
poppedOwners[i] = owners[i];
owners.pop();
owners.pop();
for (uint256 j = i; j < ownersLength - 1; j++) {
owners.push(poppedOwners[j]);
}
return;
}
}
}
}
| 13,046,216 | [
1,
4625,
348,
7953,
560,
30,
225,
10311,
326,
1731,
1578,
487,
326,
1122,
1569,
1347,
4440,
326,
7773,
19748,
4186,
4019,
538,
305,
871,
7903,
14186,
871,
628,
745,
892,
10498,
3298,
434,
326,
7778,
291,
360,
16936,
14223,
9646,
5098,
14223,
9646,
434,
326,
7778,
291,
360,
16936,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
7778,
291,
360,
16936,
288,
203,
565,
7778,
291,
360,
16936,
1733,
1071,
22945,
360,
16936,
1733,
31,
203,
203,
565,
1450,
7773,
19748,
364,
1731,
1578,
31,
203,
565,
871,
4019,
538,
305,
12,
2867,
8808,
5793,
16,
2254,
5034,
3844,
16,
2254,
5034,
11013,
1769,
203,
565,
871,
7903,
3342,
12,
203,
3639,
1758,
8808,
3410,
16,
203,
3639,
1758,
8843,
429,
358,
16,
203,
3639,
2254,
5034,
460,
16,
203,
3639,
1731,
501,
16,
203,
3639,
2254,
5034,
7448,
16,
203,
3639,
1731,
1578,
1651,
16,
203,
3639,
1731,
563,
203,
565,
11272,
203,
565,
871,
16837,
12,
2867,
8808,
3410,
16,
1426,
3096,
1769,
203,
203,
565,
1758,
8526,
1071,
25937,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
353,
5541,
31,
203,
203,
565,
2254,
5034,
1071,
7448,
31,
203,
565,
2254,
5034,
1071,
2687,
548,
31,
203,
565,
2254,
5034,
1071,
14862,
3705,
31,
203,
203,
203,
203,
5666,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
5471,
19,
22784,
15669,
19,
7228,
19748,
18,
18281,
14432,
203,
5666,
25165,
5049,
291,
360,
16936,
1733,
18,
18281,
14432,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
12,
291,
5541,
63,
3576,
18,
15330,
6487,
315,
1248,
16837,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
10084,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
1758,
12,
2211,
3631,
315,
1248,
18954,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
1661,
7170,
23918,
12,
11890,
5034,
389,
30730,
3705,
13,
288,
203,
3639,
2583,
24899,
30730,
3705,
405,
374,
16,
315,
10136,
506,
1661,
17,
7124,
3553,
87,
1931,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
3885,
12,
203,
3639,
2254,
5034,
389,
5639,
548,
16,
203,
3639,
1758,
8526,
3778,
389,
6769,
5460,
414,
16,
203,
3639,
2254,
5034,
389,
30730,
3705,
16,
203,
3639,
1758,
389,
6848,
203,
565,
262,
8843,
429,
1661,
7170,
23918,
24899,
30730,
3705,
13,
288,
203,
3639,
22945,
360,
16936,
1733,
273,
7778,
291,
360,
16936,
1733,
24899,
6848,
1769,
203,
3639,
14862,
3705,
273,
389,
30730,
3705,
31,
203,
203,
3639,
2583,
24899,
6769,
5460,
414,
18,
2469,
405,
374,
16,
315,
5460,
414,
1931,
8863,
203,
3639,
2583,
12,
203,
5411,
389,
30730,
3705,
405,
374,
597,
203,
7734,
389,
30730,
3705,
1648,
389,
6769,
5460,
414,
18,
2469,
16,
203,
5411,
315,
1941,
1931,
1300,
434,
25937,
6,
203,
3639,
11272,
203,
203,
3639,
364,
261,
11890,
5034,
277,
31,
277,
411,
389,
6769,
5460,
414,
18,
2469,
31,
277,
27245,
288,
203,
5411,
1758,
3410,
273,
389,
6769,
5460,
414,
63,
77,
15533,
203,
203,
5411,
2583,
12,
8443,
480,
1758,
12,
20,
3631,
315,
5387,
3410,
8863,
203,
5411,
2583,
12,
5,
291,
5541,
63,
8443,
6487,
315,
5541,
353,
486,
3089,
8863,
203,
203,
5411,
353,
5541,
63,
8443,
65,
273,
638,
31,
203,
5411,
25937,
18,
6206,
12,
8443,
1769,
203,
203,
5411,
3626,
16837,
12,
8443,
16,
353,
5541,
63,
8443,
19226,
203,
3639,
289,
203,
203,
3639,
2687,
548,
273,
389,
5639,
548,
31,
203,
565,
289,
203,
203,
565,
262,
8843,
429,
1661,
7170,
23918,
24899,
30730,
3705,
13,
288,
203,
3639,
22945,
360,
16936,
1733,
273,
7778,
291,
360,
16936,
1733,
24899,
6848,
1769,
203,
3639,
14862,
3705,
273,
389,
30730,
3705,
31,
203,
203,
3639,
2583,
24899,
6769,
5460,
414,
18,
2469,
405,
374,
16,
315,
5460,
414,
1931,
8863,
203,
3639,
2583,
12,
203,
5411,
389,
30730,
3705,
405,
374,
597,
203,
7734,
389,
30730,
3705,
1648,
389,
6769,
5460,
414,
18,
2469,
16,
203,
5411,
315,
1941,
1931,
1300,
434,
25937,
6,
203,
3639,
11272,
203,
203,
3639,
364,
261,
11890,
5034,
277,
31,
277,
411,
389,
6769,
5460,
414,
18,
2469,
31,
277,
27245,
288,
203,
5411,
1758,
3410,
273,
389,
6769,
5460,
414,
63,
77,
15533,
203,
203,
5411,
2583,
12,
8443,
480,
1758,
12,
20,
3631,
315,
5387,
3410,
8863,
203,
5411,
2583,
12,
5,
291,
5541,
63,
8443,
6487,
315,
5541,
353,
486,
3089,
8863,
203,
203,
5411,
353,
5541,
63,
8443,
65,
273,
638,
31,
203,
5411,
25937,
18,
6206,
12,
8443,
1769,
203,
203,
5411,
3626,
16837,
12,
8443,
16,
353,
5541,
63,
8443,
19226,
203,
3639,
289,
203,
203,
3639,
2687,
548,
273,
389,
5639,
548,
31,
203,
565,
289,
203,
203,
565,
6798,
1435,
3903,
8843,
429,
288,
203,
3639,
3626,
4019,
538,
305,
12,
3576,
18,
15330,
16,
1234,
18,
1132,
16,
1758,
12,
2211,
2934,
12296,
1769,
203,
565,
289,
203,
203,
565,
445,
15674,
2310,
12,
203,
3639,
2254,
5034,
389,
12824,
16,
203,
3639,
1758,
389,
869,
16,
203,
3639,
2254,
5034,
389,
1132,
16,
203,
3639,
1731,
3778,
389,
892,
203,
565,
262,
1071,
1476,
1135,
261,
3890,
1578,
13,
288,
203,
3639,
327,
203,
5411,
417,
24410,
581,
5034,
12,
203,
7734,
24126,
18,
3015,
4420,
329,
12,
203,
10792,
1758,
12,
2211,
3631,
203,
10792,
2687,
548,
16,
203,
10792,
389,
12824,
16,
203,
10792,
389,
869,
16,
203,
10792,
389,
1132,
16,
203,
10792,
389,
892,
203,
7734,
262,
203,
5411,
11272,
203,
565,
289,
203,
203,
565,
445,
5910,
12,
3890,
1578,
389,
2816,
16,
1731,
3778,
389,
8195,
13,
203,
3639,
1071,
203,
3639,
16618,
203,
3639,
1135,
261,
2867,
13,
203,
565,
288,
203,
3639,
327,
389,
2816,
18,
869,
41,
451,
12294,
1079,
2310,
7675,
266,
3165,
24899,
8195,
1769,
203,
565,
289,
203,
203,
565,
445,
1836,
3342,
12,
203,
3639,
1758,
8843,
429,
389,
869,
16,
203,
3639,
2254,
5034,
389,
1132,
16,
203,
3639,
1731,
3778,
389,
892,
16,
203,
3639,
1731,
8526,
3778,
389,
30730,
203,
565,
262,
1071,
1338,
5541,
1135,
261,
3890,
3778,
13,
288,
203,
3639,
1731,
1578,
389,
2816,
273,
15674,
2310,
12,
12824,
16,
389,
869,
16,
389,
1132,
16,
389,
892,
1769,
203,
203,
3639,
7448,
9904,
31,
203,
203,
3639,
2254,
5034,
923,
23918,
31,
203,
3639,
1758,
6751,
16709,
31,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
2
] |
./full_match/5/0x1917925b6fdF913927b68D42BF8983ff0C2cFcf8/sources/contracts/PrmntOrigin.sol | uint256 tokenId, uint256 _amount
| function claim() public payable { | 1,913,460 | [
1,
4625,
348,
7953,
560,
30,
2254,
5034,
1147,
548,
16,
2254,
5034,
389,
8949,
203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7516,
1435,
1071,
8843,
429,
288,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x1a0bADb278dE44E261DEC9f4225E3DD761336DA8/sources/contracts/multisigs/GuardCM.sol | @dev The combination of target and selector is not authorized. @param target Target address. @param selector Function selector. | error NotAuthorized(address target, bytes4 selector);
| 3,071,831 | [
1,
4625,
348,
7953,
560,
30,
225,
632,
5206,
1021,
10702,
434,
1018,
471,
3451,
353,
486,
10799,
18,
632,
891,
1018,
5916,
1758,
18,
632,
891,
3451,
4284,
3451,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1636,
2288,
15341,
12,
2867,
1018,
16,
1731,
24,
3451,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.19;
// Interface contract to be implemented by SyscoinToken
contract SyscoinTransactionProcessor {
function processTransaction(uint txHash, uint value, address destinationAddress, uint32 _assetGUID, address superblockSubmitterAddress) public returns (uint);
function burn(uint _value, uint32 _assetGUID, bytes syscoinWitnessProgram) payable public returns (bool success);
}
// Bitcoin transaction parsing library - modified for SYSCOIN
// Copyright 2016 rain <https://keybase.io/rain>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// https://en.bitcoin.it/wiki/Protocol_documentation#tx
//
// Raw Bitcoin transaction structure:
//
// field | size | type | description
// version | 4 | int32 | transaction version number
// n_tx_in | 1-9 | var_int | number of transaction inputs
// tx_in | 41+ | tx_in[] | list of transaction inputs
// n_tx_out | 1-9 | var_int | number of transaction outputs
// tx_out | 9+ | tx_out[] | list of transaction outputs
// lock_time | 4 | uint32 | block number / timestamp at which tx locked
//
// Transaction input (tx_in) structure:
//
// field | size | type | description
// previous | 36 | outpoint | Previous output transaction reference
// script_len | 1-9 | var_int | Length of the signature script
// sig_script | ? | uchar[] | Script for confirming transaction authorization
// sequence | 4 | uint32 | Sender transaction version
//
// OutPoint structure:
//
// field | size | type | description
// hash | 32 | char[32] | The hash of the referenced transaction
// index | 4 | uint32 | The index of this output in the referenced transaction
//
// Transaction output (tx_out) structure:
//
// field | size | type | description
// value | 8 | int64 | Transaction value (Satoshis)
// pk_script_len | 1-9 | var_int | Length of the public key script
// pk_script | ? | uchar[] | Public key as a Bitcoin script.
//
// Variable integers (var_int) can be encoded differently depending
// on the represented value, to save space. Variable integers always
// precede an array of a variable length data type (e.g. tx_in).
//
// Variable integer encodings as a function of represented value:
//
// value | bytes | format
// <0xFD (253) | 1 | uint8
// <=0xFFFF (65535)| 3 | 0xFD followed by length as uint16
// <=0xFFFF FFFF | 5 | 0xFE followed by length as uint32
// - | 9 | 0xFF followed by length as uint64
//
// Public key scripts `pk_script` are set on the output and can
// take a number of forms. The regular transaction script is
// called 'pay-to-pubkey-hash' (P2PKH):
//
// OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
//
// OP_x are Bitcoin script opcodes. The bytes representation (including
// the 0x14 20-byte stack push) is:
//
// 0x76 0xA9 0x14 <pubKeyHash> 0x88 0xAC
//
// The <pubKeyHash> is the ripemd160 hash of the sha256 hash of
// the public key, preceded by a network version byte. (21 bytes total)
//
// Network version bytes: 0x00 (mainnet); 0x6f (testnet); 0x34 (namecoin)
//
// The Bitcoin address is derived from the pubKeyHash. The binary form is the
// pubKeyHash, plus a checksum at the end. The checksum is the first 4 bytes
// of the (32 byte) double sha256 of the pubKeyHash. (25 bytes total)
// This is converted to base58 to form the publicly used Bitcoin address.
// Mainnet P2PKH transaction scripts are to addresses beginning with '1'.
//
// P2SH ('pay to script hash') scripts only supply a script hash. The spender
// must then provide the script that would allow them to redeem this output.
// This allows for arbitrarily complex scripts to be funded using only a
// hash of the script, and moves the onus on providing the script from
// the spender to the redeemer.
//
// The P2SH script format is simple:
//
// OP_HASH160 <scriptHash> OP_EQUAL
//
// 0xA9 0x14 <scriptHash> 0x87
//
// The <scriptHash> is the ripemd160 hash of the sha256 hash of the
// redeem script. The P2SH address is derived from the scriptHash.
// Addresses are the scriptHash with a version prefix of 5, encoded as
// Base58check. These addresses begin with a '3'.
// parse a raw Syscoin transaction byte array
library SyscoinMessageLibrary {
uint constant p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f; // secp256k1
uint constant q = (p + 1) / 4;
// Error codes
uint constant ERR_INVALID_HEADER = 10050;
uint constant ERR_COINBASE_INDEX = 10060; // coinbase tx index within Litecoin merkle isn't 0
uint constant ERR_NOT_MERGE_MINED = 10070; // trying to check AuxPoW on a block that wasn't merge mined
uint constant ERR_FOUND_TWICE = 10080; // 0xfabe6d6d found twice
uint constant ERR_NO_MERGE_HEADER = 10090; // 0xfabe6d6d not found
uint constant ERR_NOT_IN_FIRST_20 = 10100; // chain Merkle root isn't in the first 20 bytes of coinbase tx
uint constant ERR_CHAIN_MERKLE = 10110;
uint constant ERR_PARENT_MERKLE = 10120;
uint constant ERR_PROOF_OF_WORK = 10130;
uint constant ERR_INVALID_HEADER_HASH = 10140;
uint constant ERR_PROOF_OF_WORK_AUXPOW = 10150;
uint constant ERR_PARSE_TX_OUTPUT_LENGTH = 10160;
uint constant ERR_PARSE_TX_SYS = 10170;
enum Network { MAINNET, TESTNET, REGTEST }
uint32 constant SYSCOIN_TX_VERSION_ASSET_ALLOCATION_BURN = 0x7407;
uint32 constant SYSCOIN_TX_VERSION_BURN = 0x7401;
// AuxPoW block fields
struct AuxPoW {
uint blockHash;
uint txHash;
uint coinbaseMerkleRoot; // Merkle root of auxiliary block hash tree; stored in coinbase tx field
uint[] chainMerkleProof; // proves that a given Syscoin block hash belongs to a tree with the above root
uint syscoinHashIndex; // index of Syscoin block hash within block hash tree
uint coinbaseMerkleRootCode; // encodes whether or not the root was found properly
uint parentMerkleRoot; // Merkle root of transaction tree from parent Litecoin block header
uint[] parentMerkleProof; // proves that coinbase tx belongs to a tree with the above root
uint coinbaseTxIndex; // index of coinbase tx within Litecoin tx tree
uint parentNonce;
}
// Syscoin block header stored as a struct, mostly for readability purposes.
// BlockHeader structs can be obtained by parsing a block header's first 80 bytes
// with parseHeaderBytes.
struct BlockHeader {
uint32 bits;
uint blockHash;
}
// Convert a variable integer into something useful and return it and
// the index to after it.
function parseVarInt(bytes memory txBytes, uint pos) private pure returns (uint, uint) {
// the first byte tells us how big the integer is
uint8 ibit = uint8(txBytes[pos]);
pos += 1; // skip ibit
if (ibit < 0xfd) {
return (ibit, pos);
} else if (ibit == 0xfd) {
return (getBytesLE(txBytes, pos, 16), pos + 2);
} else if (ibit == 0xfe) {
return (getBytesLE(txBytes, pos, 32), pos + 4);
} else if (ibit == 0xff) {
return (getBytesLE(txBytes, pos, 64), pos + 8);
}
}
// convert little endian bytes to uint
function getBytesLE(bytes memory data, uint pos, uint bits) internal pure returns (uint) {
if (bits == 8) {
return uint8(data[pos]);
} else if (bits == 16) {
return uint16(data[pos])
+ uint16(data[pos + 1]) * 2 ** 8;
} else if (bits == 32) {
return uint32(data[pos])
+ uint32(data[pos + 1]) * 2 ** 8
+ uint32(data[pos + 2]) * 2 ** 16
+ uint32(data[pos + 3]) * 2 ** 24;
} else if (bits == 64) {
return uint64(data[pos])
+ uint64(data[pos + 1]) * 2 ** 8
+ uint64(data[pos + 2]) * 2 ** 16
+ uint64(data[pos + 3]) * 2 ** 24
+ uint64(data[pos + 4]) * 2 ** 32
+ uint64(data[pos + 5]) * 2 ** 40
+ uint64(data[pos + 6]) * 2 ** 48
+ uint64(data[pos + 7]) * 2 ** 56;
}
}
// @dev - Parses a syscoin tx
//
// @param txBytes - tx byte array
// Outputs
// @return output_value - amount sent to the lock address in satoshis
// @return destinationAddress - ethereum destination address
function parseTransaction(bytes memory txBytes) internal pure
returns (uint, uint, address, uint32)
{
uint output_value;
uint32 assetGUID;
address destinationAddress;
uint32 version;
uint pos = 0;
version = bytesToUint32Flipped(txBytes, pos);
if(version != SYSCOIN_TX_VERSION_ASSET_ALLOCATION_BURN && version != SYSCOIN_TX_VERSION_BURN){
return (ERR_PARSE_TX_SYS, output_value, destinationAddress, assetGUID);
}
pos = skipInputs(txBytes, 4);
(output_value, destinationAddress, assetGUID) = scanBurns(txBytes, version, pos);
return (0, output_value, destinationAddress, assetGUID);
}
// skips witnesses and saves first script position/script length to extract pubkey of first witness scriptSig
function skipWitnesses(bytes memory txBytes, uint pos, uint n_inputs) private pure
returns (uint)
{
uint n_stack;
(n_stack, pos) = parseVarInt(txBytes, pos);
uint script_len;
for (uint i = 0; i < n_inputs; i++) {
for (uint j = 0; j < n_stack; j++) {
(script_len, pos) = parseVarInt(txBytes, pos);
pos += script_len;
}
}
return n_stack;
}
function skipInputs(bytes memory txBytes, uint pos) private pure
returns (uint)
{
uint n_inputs;
uint script_len;
(n_inputs, pos) = parseVarInt(txBytes, pos);
// if dummy 0x00 is present this is a witness transaction
if(n_inputs == 0x00){
(n_inputs, pos) = parseVarInt(txBytes, pos); // flag
assert(n_inputs != 0x00);
// after dummy/flag the real var int comes for txins
(n_inputs, pos) = parseVarInt(txBytes, pos);
}
require(n_inputs < 100);
for (uint i = 0; i < n_inputs; i++) {
pos += 36; // skip outpoint
(script_len, pos) = parseVarInt(txBytes, pos);
pos += script_len + 4; // skip sig_script, seq
}
return pos;
}
// scan the burn outputs and return the value and script data of first burned output.
function scanBurns(bytes memory txBytes, uint32 version, uint pos) private pure
returns (uint, address, uint32)
{
uint script_len;
uint output_value;
uint32 assetGUID = 0;
address destinationAddress;
uint n_outputs;
(n_outputs, pos) = parseVarInt(txBytes, pos);
require(n_outputs < 10);
for (uint i = 0; i < n_outputs; i++) {
// output
if(version == SYSCOIN_TX_VERSION_BURN){
output_value = getBytesLE(txBytes, pos, 64);
}
pos += 8;
// varint
(script_len, pos) = parseVarInt(txBytes, pos);
if(!isOpReturn(txBytes, pos)){
// output script
pos += script_len;
output_value = 0;
continue;
}
// skip opreturn marker
pos += 1;
if(version == SYSCOIN_TX_VERSION_ASSET_ALLOCATION_BURN){
(output_value, destinationAddress, assetGUID) = scanAssetDetails(txBytes, pos);
}
else if(version == SYSCOIN_TX_VERSION_BURN){
destinationAddress = scanSyscoinDetails(txBytes, pos);
}
// only one opreturn data allowed per transaction
break;
}
return (output_value, destinationAddress, assetGUID);
}
function skipOutputs(bytes memory txBytes, uint pos) private pure
returns (uint)
{
uint n_outputs;
uint script_len;
(n_outputs, pos) = parseVarInt(txBytes, pos);
require(n_outputs < 10);
for (uint i = 0; i < n_outputs; i++) {
pos += 8;
(script_len, pos) = parseVarInt(txBytes, pos);
pos += script_len;
}
return pos;
}
// get final position of inputs, outputs and lock time
// this is a helper function to slice a byte array and hash the inputs, outputs and lock time
function getSlicePos(bytes memory txBytes, uint pos) private pure
returns (uint slicePos)
{
slicePos = skipInputs(txBytes, pos + 4);
slicePos = skipOutputs(txBytes, slicePos);
slicePos += 4; // skip lock time
}
// scan a Merkle branch.
// return array of values and the end position of the sibling hashes.
// takes a 'stop' argument which sets the maximum number of
// siblings to scan through. stop=0 => scan all.
function scanMerkleBranch(bytes memory txBytes, uint pos, uint stop) private pure
returns (uint[], uint)
{
uint n_siblings;
uint halt;
(n_siblings, pos) = parseVarInt(txBytes, pos);
if (stop == 0 || stop > n_siblings) {
halt = n_siblings;
} else {
halt = stop;
}
uint[] memory sibling_values = new uint[](halt);
for (uint i = 0; i < halt; i++) {
sibling_values[i] = flip32Bytes(sliceBytes32Int(txBytes, pos));
pos += 32;
}
return (sibling_values, pos);
}
// Slice 20 contiguous bytes from bytes `data`, starting at `start`
function sliceBytes20(bytes memory data, uint start) private pure returns (bytes20) {
uint160 slice = 0;
// FIXME: With solc v0.4.24 and optimizations enabled
// using uint160 for index i will generate an error
// "Error: VM Exception while processing transaction: Error: redPow(normalNum)"
for (uint i = 0; i < 20; i++) {
slice += uint160(data[i + start]) << (8 * (19 - i));
}
return bytes20(slice);
}
// Slice 32 contiguous bytes from bytes `data`, starting at `start`
function sliceBytes32Int(bytes memory data, uint start) private pure returns (uint slice) {
for (uint i = 0; i < 32; i++) {
if (i + start < data.length) {
slice += uint(data[i + start]) << (8 * (31 - i));
}
}
}
// @dev returns a portion of a given byte array specified by its starting and ending points
// Should be private, made internal for testing
// Breaks underscore naming convention for parameters because it raises a compiler error
// if `offset` is changed to `_offset`.
//
// @param _rawBytes - array to be sliced
// @param offset - first byte of sliced array
// @param _endIndex - last byte of sliced array
function sliceArray(bytes memory _rawBytes, uint offset, uint _endIndex) internal view returns (bytes) {
uint len = _endIndex - offset;
bytes memory result = new bytes(len);
assembly {
// Call precompiled contract to copy data
if iszero(staticcall(gas, 0x04, add(add(_rawBytes, 0x20), offset), len, add(result, 0x20), len)) {
revert(0, 0)
}
}
return result;
}
// Returns true if the tx output is an OP_RETURN output
function isOpReturn(bytes memory txBytes, uint pos) private pure
returns (bool) {
// scriptPub format is
// 0x6a OP_RETURN
return
txBytes[pos] == byte(0x6a);
}
// Returns syscoin data parsed from the op_return data output from syscoin burn transaction
function scanSyscoinDetails(bytes memory txBytes, uint pos) private pure
returns (address) {
uint8 op;
(op, pos) = getOpcode(txBytes, pos);
// ethereum addresses are 20 bytes (without the 0x)
require(op == 0x14);
return readEthereumAddress(txBytes, pos);
}
// Returns asset data parsed from the op_return data output from syscoin asset burn transaction
function scanAssetDetails(bytes memory txBytes, uint pos) private pure
returns (uint, address, uint32) {
uint32 assetGUID;
address destinationAddress;
uint output_value;
uint8 op;
// vchAsset
(op, pos) = getOpcode(txBytes, pos);
// guid length should be 4 bytes
require(op == 0x04);
assetGUID = bytesToUint32(txBytes, pos);
pos += op;
// amount
(op, pos) = getOpcode(txBytes, pos);
require(op == 0x08);
output_value = bytesToUint64(txBytes, pos);
pos += op;
// destination address
(op, pos) = getOpcode(txBytes, pos);
// ethereum contracts are 20 bytes (without the 0x)
require(op == 0x14);
destinationAddress = readEthereumAddress(txBytes, pos);
return (output_value, destinationAddress, assetGUID);
}
// Read the ethereum address embedded in the tx output
function readEthereumAddress(bytes memory txBytes, uint pos) private pure
returns (address) {
uint256 data;
assembly {
data := mload(add(add(txBytes, 20), pos))
}
return address(uint160(data));
}
// Read next opcode from script
function getOpcode(bytes memory txBytes, uint pos) private pure
returns (uint8, uint)
{
require(pos < txBytes.length);
return (uint8(txBytes[pos]), pos + 1);
}
// @dev - convert an unsigned integer from little-endian to big-endian representation
//
// @param _input - little-endian value
// @return - input value in big-endian format
function flip32Bytes(uint _input) internal pure returns (uint result) {
assembly {
let pos := mload(0x40)
for { let i := 0 } lt(i, 32) { i := add(i, 1) } {
mstore8(add(pos, i), byte(sub(31, i), _input))
}
result := mload(pos)
}
}
// helpers for flip32Bytes
struct UintWrapper {
uint value;
}
function ptr(UintWrapper memory uw) private pure returns (uint addr) {
assembly {
addr := uw
}
}
function parseAuxPoW(bytes memory rawBytes, uint pos) internal view
returns (AuxPoW memory auxpow)
{
// we need to traverse the bytes with a pointer because some fields are of variable length
pos += 80; // skip non-AuxPoW header
uint slicePos;
(slicePos) = getSlicePos(rawBytes, pos);
auxpow.txHash = dblShaFlipMem(rawBytes, pos, slicePos - pos);
pos = slicePos;
// parent block hash, skip and manually hash below
pos += 32;
(auxpow.parentMerkleProof, pos) = scanMerkleBranch(rawBytes, pos, 0);
auxpow.coinbaseTxIndex = getBytesLE(rawBytes, pos, 32);
pos += 4;
(auxpow.chainMerkleProof, pos) = scanMerkleBranch(rawBytes, pos, 0);
auxpow.syscoinHashIndex = getBytesLE(rawBytes, pos, 32);
pos += 4;
// calculate block hash instead of reading it above, as some are LE and some are BE, we cannot know endianness and have to calculate from parent block header
auxpow.blockHash = dblShaFlipMem(rawBytes, pos, 80);
pos += 36; // skip parent version and prev block
auxpow.parentMerkleRoot = sliceBytes32Int(rawBytes, pos);
pos += 40; // skip root that was just read, parent block timestamp and bits
auxpow.parentNonce = getBytesLE(rawBytes, pos, 32);
uint coinbaseMerkleRootPosition;
(auxpow.coinbaseMerkleRoot, coinbaseMerkleRootPosition, auxpow.coinbaseMerkleRootCode) = findCoinbaseMerkleRoot(rawBytes);
}
// @dev - looks for {0xfa, 0xbe, 'm', 'm'} byte sequence
// returns the following 32 bytes if it appears once and only once,
// 0 otherwise
// also returns the position where the bytes first appear
function findCoinbaseMerkleRoot(bytes memory rawBytes) private pure
returns (uint, uint, uint)
{
uint position;
bool found = false;
for (uint i = 0; i < rawBytes.length; ++i) {
if (rawBytes[i] == 0xfa && rawBytes[i+1] == 0xbe && rawBytes[i+2] == 0x6d && rawBytes[i+3] == 0x6d) {
if (found) { // found twice
return (0, position - 4, ERR_FOUND_TWICE);
} else {
found = true;
position = i + 4;
}
}
}
if (!found) { // no merge mining header
return (0, position - 4, ERR_NO_MERGE_HEADER);
} else {
return (sliceBytes32Int(rawBytes, position), position - 4, 1);
}
}
// @dev - Evaluate the merkle root
//
// Given an array of hashes it calculates the
// root of the merkle tree.
//
// @return root of merkle tree
function makeMerkle(bytes32[] hashes2) external pure returns (bytes32) {
bytes32[] memory hashes = hashes2;
uint length = hashes.length;
if (length == 1) return hashes[0];
require(length > 0);
uint i;
uint j;
uint k;
k = 0;
while (length > 1) {
k = 0;
for (i = 0; i < length; i += 2) {
j = i+1<length ? i+1 : length-1;
hashes[k] = bytes32(concatHash(uint(hashes[i]), uint(hashes[j])));
k += 1;
}
length = k;
}
return hashes[0];
}
// @dev - For a valid proof, returns the root of the Merkle tree.
//
// @param _txHash - transaction hash
// @param _txIndex - transaction's index within the block it's assumed to be in
// @param _siblings - transaction's Merkle siblings
// @return - Merkle tree root of the block the transaction belongs to if the proof is valid,
// garbage if it's invalid
function computeMerkle(uint _txHash, uint _txIndex, uint[] memory _siblings) internal pure returns (uint) {
uint resultHash = _txHash;
uint i = 0;
while (i < _siblings.length) {
uint proofHex = _siblings[i];
uint sideOfSiblings = _txIndex % 2; // 0 means _siblings is on the right; 1 means left
uint left;
uint right;
if (sideOfSiblings == 1) {
left = proofHex;
right = resultHash;
} else if (sideOfSiblings == 0) {
left = resultHash;
right = proofHex;
}
resultHash = concatHash(left, right);
_txIndex /= 2;
i += 1;
}
return resultHash;
}
// @dev - calculates the Merkle root of a tree containing Litecoin transactions
// in order to prove that `ap`'s coinbase tx is in that Litecoin block.
//
// @param _ap - AuxPoW information
// @return - Merkle root of Litecoin block that the Syscoin block
// with this info was mined in if AuxPoW Merkle proof is correct,
// garbage otherwise
function computeParentMerkle(AuxPoW memory _ap) internal pure returns (uint) {
return flip32Bytes(computeMerkle(_ap.txHash,
_ap.coinbaseTxIndex,
_ap.parentMerkleProof));
}
// @dev - calculates the Merkle root of a tree containing auxiliary block hashes
// in order to prove that the Syscoin block identified by _blockHash
// was merge-mined in a Litecoin block.
//
// @param _blockHash - SHA-256 hash of a certain Syscoin block
// @param _ap - AuxPoW information corresponding to said block
// @return - Merkle root of auxiliary chain tree
// if AuxPoW Merkle proof is correct, garbage otherwise
function computeChainMerkle(uint _blockHash, AuxPoW memory _ap) internal pure returns (uint) {
return computeMerkle(_blockHash,
_ap.syscoinHashIndex,
_ap.chainMerkleProof);
}
// @dev - Helper function for Merkle root calculation.
// Given two sibling nodes in a Merkle tree, calculate their parent.
// Concatenates hashes `_tx1` and `_tx2`, then hashes the result.
//
// @param _tx1 - Merkle node (either root or internal node)
// @param _tx2 - Merkle node (either root or internal node), has to be `_tx1`'s sibling
// @return - `_tx1` and `_tx2`'s parent, i.e. the result of concatenating them,
// hashing that twice and flipping the bytes.
function concatHash(uint _tx1, uint _tx2) internal pure returns (uint) {
return flip32Bytes(uint(sha256(abi.encodePacked(sha256(abi.encodePacked(flip32Bytes(_tx1), flip32Bytes(_tx2)))))));
}
// @dev - checks if a merge-mined block's Merkle proofs are correct,
// i.e. Syscoin block hash is in coinbase Merkle tree
// and coinbase transaction is in parent Merkle tree.
//
// @param _blockHash - SHA-256 hash of the block whose Merkle proofs are being checked
// @param _ap - AuxPoW struct corresponding to the block
// @return 1 if block was merge-mined and coinbase index, chain Merkle root and Merkle proofs are correct,
// respective error code otherwise
function checkAuxPoW(uint _blockHash, AuxPoW memory _ap) internal pure returns (uint) {
if (_ap.coinbaseTxIndex != 0) {
return ERR_COINBASE_INDEX;
}
if (_ap.coinbaseMerkleRootCode != 1) {
return _ap.coinbaseMerkleRootCode;
}
if (computeChainMerkle(_blockHash, _ap) != _ap.coinbaseMerkleRoot) {
return ERR_CHAIN_MERKLE;
}
if (computeParentMerkle(_ap) != _ap.parentMerkleRoot) {
return ERR_PARENT_MERKLE;
}
return 1;
}
function sha256mem(bytes memory _rawBytes, uint offset, uint len) internal view returns (bytes32 result) {
assembly {
// Call sha256 precompiled contract (located in address 0x02) to copy data.
// Assign to ptr the next available memory position (stored in memory position 0x40).
let ptr := mload(0x40)
if iszero(staticcall(gas, 0x02, add(add(_rawBytes, 0x20), offset), len, ptr, 0x20)) {
revert(0, 0)
}
result := mload(ptr)
}
}
// @dev - Bitcoin-way of hashing
// @param _dataBytes - raw data to be hashed
// @return - result of applying SHA-256 twice to raw data and then flipping the bytes
function dblShaFlip(bytes _dataBytes) internal pure returns (uint) {
return flip32Bytes(uint(sha256(abi.encodePacked(sha256(abi.encodePacked(_dataBytes))))));
}
// @dev - Bitcoin-way of hashing
// @param _dataBytes - raw data to be hashed
// @return - result of applying SHA-256 twice to raw data and then flipping the bytes
function dblShaFlipMem(bytes memory _rawBytes, uint offset, uint len) internal view returns (uint) {
return flip32Bytes(uint(sha256(abi.encodePacked(sha256mem(_rawBytes, offset, len)))));
}
// @dev – Read a bytes32 from an offset in the byte array
function readBytes32(bytes memory data, uint offset) internal pure returns (bytes32) {
bytes32 result;
assembly {
result := mload(add(add(data, 0x20), offset))
}
return result;
}
// @dev – Read an uint32 from an offset in the byte array
function readUint32(bytes memory data, uint offset) internal pure returns (uint32) {
uint32 result;
assembly {
result := mload(add(add(data, 0x20), offset))
}
return result;
}
// @dev - Bitcoin-way of computing the target from the 'bits' field of a block header
// based on http://www.righto.com/2014/02/bitcoin-mining-hard-way-algorithms.html//ref3
//
// @param _bits - difficulty in bits format
// @return - difficulty in target format
function targetFromBits(uint32 _bits) internal pure returns (uint) {
uint exp = _bits / 0x1000000; // 2**24
uint mant = _bits & 0xffffff;
return mant * 256**(exp - 3);
}
uint constant SYSCOIN_DIFFICULTY_ONE = 0xFFFFF * 256**(0x1e - 3);
// @dev - Calculate syscoin difficulty from target
// https://en.bitcoin.it/wiki/Difficulty
// Min difficulty for bitcoin is 0x1d00ffff
// Min difficulty for syscoin is 0x1e0fffff
function targetToDiff(uint target) internal pure returns (uint) {
return SYSCOIN_DIFFICULTY_ONE / target;
}
// 0x00 version
// 0x04 prev block hash
// 0x24 merkle root
// 0x44 timestamp
// 0x48 bits
// 0x4c nonce
// @dev - extract previous block field from a raw Syscoin block header
//
// @param _blockHeader - Syscoin block header bytes
// @param pos - where to start reading hash from
// @return - hash of block's parent in big endian format
function getHashPrevBlock(bytes memory _blockHeader) internal pure returns (uint) {
uint hashPrevBlock;
assembly {
hashPrevBlock := mload(add(add(_blockHeader, 32), 0x04))
}
return flip32Bytes(hashPrevBlock);
}
// @dev - extract Merkle root field from a raw Syscoin block header
//
// @param _blockHeader - Syscoin block header bytes
// @param pos - where to start reading root from
// @return - block's Merkle root in big endian format
function getHeaderMerkleRoot(bytes memory _blockHeader) public pure returns (uint) {
uint merkle;
assembly {
merkle := mload(add(add(_blockHeader, 32), 0x24))
}
return flip32Bytes(merkle);
}
// @dev - extract timestamp field from a raw Syscoin block header
//
// @param _blockHeader - Syscoin block header bytes
// @param pos - where to start reading bits from
// @return - block's timestamp in big-endian format
function getTimestamp(bytes memory _blockHeader) internal pure returns (uint32 time) {
return bytesToUint32Flipped(_blockHeader, 0x44);
}
// @dev - extract bits field from a raw Syscoin block header
//
// @param _blockHeader - Syscoin block header bytes
// @param pos - where to start reading bits from
// @return - block's difficulty in bits format, also big-endian
function getBits(bytes memory _blockHeader) internal pure returns (uint32 bits) {
return bytesToUint32Flipped(_blockHeader, 0x48);
}
// @dev - converts raw bytes representation of a Syscoin block header to struct representation
//
// @param _rawBytes - first 80 bytes of a block header
// @return - exact same header information in BlockHeader struct form
function parseHeaderBytes(bytes memory _rawBytes, uint pos) internal view returns (BlockHeader bh) {
bh.bits = getBits(_rawBytes);
bh.blockHash = dblShaFlipMem(_rawBytes, pos, 80);
}
uint32 constant VERSION_AUXPOW = (1 << 8);
// @dev - Converts a bytes of size 4 to uint32,
// e.g. for input [0x01, 0x02, 0x03 0x04] returns 0x01020304
function bytesToUint32Flipped(bytes memory input, uint pos) internal pure returns (uint32 result) {
result = uint32(input[pos]) + uint32(input[pos + 1])*(2**8) + uint32(input[pos + 2])*(2**16) + uint32(input[pos + 3])*(2**24);
}
function bytesToUint64(bytes memory input, uint pos) internal pure returns (uint64 result) {
result = uint64(input[pos+7]) + uint64(input[pos + 6])*(2**8) + uint64(input[pos + 5])*(2**16) + uint64(input[pos + 4])*(2**24) + uint64(input[pos + 3])*(2**32) + uint64(input[pos + 2])*(2**40) + uint64(input[pos + 1])*(2**48) + uint64(input[pos])*(2**56);
}
function bytesToUint32(bytes memory input, uint pos) internal pure returns (uint32 result) {
result = uint32(input[pos+3]) + uint32(input[pos + 2])*(2**8) + uint32(input[pos + 1])*(2**16) + uint32(input[pos])*(2**24);
}
// @dev - checks version to determine if a block has merge mining information
function isMergeMined(bytes memory _rawBytes, uint pos) internal pure returns (bool) {
return bytesToUint32Flipped(_rawBytes, pos) & VERSION_AUXPOW != 0;
}
// @dev - Verify block header
// @param _blockHeaderBytes - array of bytes with the block header
// @param _pos - starting position of the block header
// @param _proposedBlockHash - proposed block hash computing from block header bytes
// @return - [ErrorCode, IsMergeMined]
function verifyBlockHeader(bytes _blockHeaderBytes, uint _pos, uint _proposedBlockHash) external view returns (uint, bool) {
BlockHeader memory blockHeader = parseHeaderBytes(_blockHeaderBytes, _pos);
uint blockSha256Hash = blockHeader.blockHash;
// must confirm that the header hash passed in and computing hash matches
if(blockSha256Hash != _proposedBlockHash){
return (ERR_INVALID_HEADER_HASH, true);
}
uint target = targetFromBits(blockHeader.bits);
if (_blockHeaderBytes.length > 80 && isMergeMined(_blockHeaderBytes, 0)) {
AuxPoW memory ap = parseAuxPoW(_blockHeaderBytes, _pos);
if (ap.blockHash > target) {
return (ERR_PROOF_OF_WORK_AUXPOW, true);
}
uint auxPoWCode = checkAuxPoW(blockSha256Hash, ap);
if (auxPoWCode != 1) {
return (auxPoWCode, true);
}
return (0, true);
} else {
if (_proposedBlockHash > target) {
return (ERR_PROOF_OF_WORK, false);
}
return (0, false);
}
}
// For verifying Syscoin difficulty
int64 constant TARGET_TIMESPAN = int64(21600);
int64 constant TARGET_TIMESPAN_DIV_4 = TARGET_TIMESPAN / int64(4);
int64 constant TARGET_TIMESPAN_MUL_4 = TARGET_TIMESPAN * int64(4);
int64 constant TARGET_TIMESPAN_ADJUSTMENT = int64(360); // 6 hour
uint constant INITIAL_CHAIN_WORK = 0x100001;
uint constant POW_LIMIT = 0x00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
// @dev - Calculate difficulty from compact representation (bits) found in block
function diffFromBits(uint32 bits) external pure returns (uint) {
return targetToDiff(targetFromBits(bits))*INITIAL_CHAIN_WORK;
}
function difficultyAdjustmentInterval() external pure returns (int64) {
return TARGET_TIMESPAN_ADJUSTMENT;
}
// @param _actualTimespan - time elapsed from previous block creation til current block creation;
// i.e., how much time it took to mine the current block
// @param _bits - previous block header difficulty (in bits)
// @return - expected difficulty for the next block
function calculateDifficulty(int64 _actualTimespan, uint32 _bits) external pure returns (uint32 result) {
int64 actualTimespan = _actualTimespan;
// Limit adjustment step
if (_actualTimespan < TARGET_TIMESPAN_DIV_4) {
actualTimespan = TARGET_TIMESPAN_DIV_4;
} else if (_actualTimespan > TARGET_TIMESPAN_MUL_4) {
actualTimespan = TARGET_TIMESPAN_MUL_4;
}
// Retarget
uint bnNew = targetFromBits(_bits);
bnNew = bnNew * uint(actualTimespan);
bnNew = uint(bnNew) / uint(TARGET_TIMESPAN);
if (bnNew > POW_LIMIT) {
bnNew = POW_LIMIT;
}
return toCompactBits(bnNew);
}
// @dev - shift information to the right by a specified number of bits
//
// @param _val - value to be shifted
// @param _shift - number of bits to shift
// @return - `_val` shifted `_shift` bits to the right, i.e. divided by 2**`_shift`
function shiftRight(uint _val, uint _shift) private pure returns (uint) {
return _val / uint(2)**_shift;
}
// @dev - shift information to the left by a specified number of bits
//
// @param _val - value to be shifted
// @param _shift - number of bits to shift
// @return - `_val` shifted `_shift` bits to the left, i.e. multiplied by 2**`_shift`
function shiftLeft(uint _val, uint _shift) private pure returns (uint) {
return _val * uint(2)**_shift;
}
// @dev - get the number of bits required to represent a given integer value without losing information
//
// @param _val - unsigned integer value
// @return - given value's bit length
function bitLen(uint _val) private pure returns (uint length) {
uint int_type = _val;
while (int_type > 0) {
int_type = shiftRight(int_type, 1);
length += 1;
}
}
// @dev - Convert uint256 to compact encoding
// based on https://github.com/petertodd/python-bitcoinlib/blob/2a5dda45b557515fb12a0a18e5dd48d2f5cd13c2/bitcoin/core/serialize.py
// Analogous to arith_uint256::GetCompact from C++ implementation
//
// @param _val - difficulty in target format
// @return - difficulty in bits format
function toCompactBits(uint _val) private pure returns (uint32) {
uint nbytes = uint (shiftRight((bitLen(_val) + 7), 3));
uint32 compact = 0;
if (nbytes <= 3) {
compact = uint32 (shiftLeft((_val & 0xFFFFFF), 8 * (3 - nbytes)));
} else {
compact = uint32 (shiftRight(_val, 8 * (nbytes - 3)));
compact = uint32 (compact & 0xFFFFFF);
}
// If the sign bit (0x00800000) is set, divide the mantissa by 256 and
// increase the exponent to get an encoding without it set.
if ((compact & 0x00800000) > 0) {
compact = uint32(shiftRight(compact, 8));
nbytes += 1;
}
return compact | uint32(shiftLeft(nbytes, 24));
}
}
// @dev - SyscoinSuperblocks error codes
contract SyscoinErrorCodes {
// Error codes
uint constant ERR_SUPERBLOCK_OK = 0;
uint constant ERR_SUPERBLOCK_BAD_STATUS = 50020;
uint constant ERR_SUPERBLOCK_BAD_SYSCOIN_STATUS = 50025;
uint constant ERR_SUPERBLOCK_NO_TIMEOUT = 50030;
uint constant ERR_SUPERBLOCK_BAD_TIMESTAMP = 50035;
uint constant ERR_SUPERBLOCK_INVALID_MERKLE = 50040;
uint constant ERR_SUPERBLOCK_BAD_PARENT = 50050;
uint constant ERR_SUPERBLOCK_OWN_CHALLENGE = 50055;
uint constant ERR_SUPERBLOCK_MIN_DEPOSIT = 50060;
uint constant ERR_SUPERBLOCK_NOT_CLAIMMANAGER = 50070;
uint constant ERR_SUPERBLOCK_BAD_CLAIM = 50080;
uint constant ERR_SUPERBLOCK_VERIFICATION_PENDING = 50090;
uint constant ERR_SUPERBLOCK_CLAIM_DECIDED = 50100;
uint constant ERR_SUPERBLOCK_BAD_CHALLENGER = 50110;
uint constant ERR_SUPERBLOCK_BAD_ACCUMULATED_WORK = 50120;
uint constant ERR_SUPERBLOCK_BAD_BITS = 50130;
uint constant ERR_SUPERBLOCK_MISSING_CONFIRMATIONS = 50140;
uint constant ERR_SUPERBLOCK_BAD_LASTBLOCK = 50150;
uint constant ERR_SUPERBLOCK_BAD_BLOCKHEIGHT = 50160;
// error codes for verifyTx
uint constant ERR_BAD_FEE = 20010;
uint constant ERR_CONFIRMATIONS = 20020;
uint constant ERR_CHAIN = 20030;
uint constant ERR_SUPERBLOCK = 20040;
uint constant ERR_MERKLE_ROOT = 20050;
uint constant ERR_TX_64BYTE = 20060;
// error codes for relayTx
uint constant ERR_RELAY_VERIFY = 30010;
// Minimum gas requirements
uint constant public minReward = 1000000000000000000;
uint constant public superblockCost = 440000;
uint constant public challengeCost = 34000;
uint constant public minProposalDeposit = challengeCost + minReward;
uint constant public minChallengeDeposit = superblockCost + minReward;
uint constant public respondMerkleRootHashesCost = 378000; // TODO: measure this with 60 hashes
uint constant public respondBlockHeaderCost = 40000;
uint constant public verifySuperblockCost = 220000;
}
// @dev - Manages superblocks
//
// Management of superblocks and status transitions
contract SyscoinSuperblocks is SyscoinErrorCodes {
// @dev - Superblock status
enum Status { Unitialized, New, InBattle, SemiApproved, Approved, Invalid }
struct SuperblockInfo {
bytes32 blocksMerkleRoot;
uint accumulatedWork;
uint timestamp;
uint prevTimestamp;
bytes32 lastHash;
bytes32 parentId;
address submitter;
bytes32 ancestors;
uint32 lastBits;
uint32 index;
uint32 height;
uint32 blockHeight;
Status status;
}
// Mapping superblock id => superblock data
mapping (bytes32 => SuperblockInfo) superblocks;
// Index to superblock id
mapping (uint32 => bytes32) private indexSuperblock;
struct ProcessTransactionParams {
uint value;
address destinationAddress;
uint32 assetGUID;
address superblockSubmitterAddress;
SyscoinTransactionProcessor untrustedTargetContract;
}
mapping (uint => ProcessTransactionParams) private txParams;
uint32 indexNextSuperblock;
bytes32 public bestSuperblock;
uint public bestSuperblockAccumulatedWork;
event NewSuperblock(bytes32 superblockHash, address who);
event ApprovedSuperblock(bytes32 superblockHash, address who);
event ChallengeSuperblock(bytes32 superblockHash, address who);
event SemiApprovedSuperblock(bytes32 superblockHash, address who);
event InvalidSuperblock(bytes32 superblockHash, address who);
event ErrorSuperblock(bytes32 superblockHash, uint err);
event VerifyTransaction(bytes32 txHash, uint returnCode);
event RelayTransaction(bytes32 txHash, uint returnCode);
// SyscoinClaimManager
address public trustedClaimManager;
modifier onlyClaimManager() {
require(msg.sender == trustedClaimManager);
_;
}
// @dev – the constructor
constructor() public {}
// @dev - sets ClaimManager instance associated with managing superblocks.
// Once trustedClaimManager has been set, it cannot be changed.
// @param _claimManager - address of the ClaimManager contract to be associated with
function setClaimManager(address _claimManager) public {
require(address(trustedClaimManager) == 0x0 && _claimManager != 0x0);
trustedClaimManager = _claimManager;
}
// @dev - Initializes superblocks contract
//
// Initializes the superblock contract. It can only be called once.
//
// @param _blocksMerkleRoot Root of the merkle tree of blocks contained in a superblock
// @param _accumulatedWork Accumulated proof of work of the last block in the superblock
// @param _timestamp Timestamp of the last block in the superblock
// @param _prevTimestamp Timestamp of the block when the last difficulty adjustment happened (every 360 blocks)
// @param _lastHash Hash of the last block in the superblock
// @param _lastBits Difficulty bits of the last block in the superblock
// @param _parentId Id of the parent superblock
// @param _blockHeight Block height of last block in superblock
// @return Error code and superblockHash
function initialize(
bytes32 _blocksMerkleRoot,
uint _accumulatedWork,
uint _timestamp,
uint _prevTimestamp,
bytes32 _lastHash,
uint32 _lastBits,
bytes32 _parentId,
uint32 _blockHeight
) public returns (uint, bytes32) {
require(bestSuperblock == 0);
require(_parentId == 0);
bytes32 superblockHash = calcSuperblockHash(_blocksMerkleRoot, _accumulatedWork, _timestamp, _prevTimestamp, _lastHash, _lastBits, _parentId, _blockHeight);
SuperblockInfo storage superblock = superblocks[superblockHash];
require(superblock.status == Status.Unitialized);
indexSuperblock[indexNextSuperblock] = superblockHash;
superblock.blocksMerkleRoot = _blocksMerkleRoot;
superblock.accumulatedWork = _accumulatedWork;
superblock.timestamp = _timestamp;
superblock.prevTimestamp = _prevTimestamp;
superblock.lastHash = _lastHash;
superblock.parentId = _parentId;
superblock.submitter = msg.sender;
superblock.index = indexNextSuperblock;
superblock.height = 1;
superblock.lastBits = _lastBits;
superblock.status = Status.Approved;
superblock.ancestors = 0x0;
superblock.blockHeight = _blockHeight;
indexNextSuperblock++;
emit NewSuperblock(superblockHash, msg.sender);
bestSuperblock = superblockHash;
bestSuperblockAccumulatedWork = _accumulatedWork;
emit ApprovedSuperblock(superblockHash, msg.sender);
return (ERR_SUPERBLOCK_OK, superblockHash);
}
// @dev - Proposes a new superblock
//
// To be accepted, a new superblock needs to have its parent
// either approved or semi-approved.
//
// @param _blocksMerkleRoot Root of the merkle tree of blocks contained in a superblock
// @param _accumulatedWork Accumulated proof of work of the last block in the superblock
// @param _timestamp Timestamp of the last block in the superblock
// @param _prevTimestamp Timestamp of the block when the last difficulty adjustment happened (every 360 blocks)
// @param _lastHash Hash of the last block in the superblock
// @param _lastBits Difficulty bits of the last block in the superblock
// @param _parentId Id of the parent superblock
// @param _blockHeight Block height of last block in superblock
// @return Error code and superblockHash
function propose(
bytes32 _blocksMerkleRoot,
uint _accumulatedWork,
uint _timestamp,
uint _prevTimestamp,
bytes32 _lastHash,
uint32 _lastBits,
bytes32 _parentId,
uint32 _blockHeight,
address submitter
) public returns (uint, bytes32) {
if (msg.sender != trustedClaimManager) {
emit ErrorSuperblock(0, ERR_SUPERBLOCK_NOT_CLAIMMANAGER);
return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0);
}
SuperblockInfo storage parent = superblocks[_parentId];
if (parent.status != Status.SemiApproved && parent.status != Status.Approved) {
emit ErrorSuperblock(superblockHash, ERR_SUPERBLOCK_BAD_PARENT);
return (ERR_SUPERBLOCK_BAD_PARENT, 0);
}
bytes32 superblockHash = calcSuperblockHash(_blocksMerkleRoot, _accumulatedWork, _timestamp, _prevTimestamp, _lastHash, _lastBits, _parentId, _blockHeight);
SuperblockInfo storage superblock = superblocks[superblockHash];
if (superblock.status == Status.Unitialized) {
indexSuperblock[indexNextSuperblock] = superblockHash;
superblock.blocksMerkleRoot = _blocksMerkleRoot;
superblock.accumulatedWork = _accumulatedWork;
superblock.timestamp = _timestamp;
superblock.prevTimestamp = _prevTimestamp;
superblock.lastHash = _lastHash;
superblock.parentId = _parentId;
superblock.submitter = submitter;
superblock.index = indexNextSuperblock;
superblock.height = parent.height + 1;
superblock.lastBits = _lastBits;
superblock.status = Status.New;
superblock.blockHeight = _blockHeight;
superblock.ancestors = updateAncestors(parent.ancestors, parent.index, parent.height);
indexNextSuperblock++;
emit NewSuperblock(superblockHash, submitter);
}
return (ERR_SUPERBLOCK_OK, superblockHash);
}
// @dev - Confirm a proposed superblock
//
// An unchallenged superblock can be confirmed after a timeout.
// A challenged superblock is confirmed if it has enough descendants
// in the main chain.
//
// @param _superblockHash Id of the superblock to confirm
// @param _validator Address requesting superblock confirmation
// @return Error code and superblockHash
function confirm(bytes32 _superblockHash, address _validator) public returns (uint, bytes32) {
if (msg.sender != trustedClaimManager) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER);
return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0);
}
SuperblockInfo storage superblock = superblocks[_superblockHash];
if (superblock.status != Status.New && superblock.status != Status.SemiApproved) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS);
return (ERR_SUPERBLOCK_BAD_STATUS, 0);
}
SuperblockInfo storage parent = superblocks[superblock.parentId];
if (parent.status != Status.Approved) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_PARENT);
return (ERR_SUPERBLOCK_BAD_PARENT, 0);
}
superblock.status = Status.Approved;
if (superblock.accumulatedWork > bestSuperblockAccumulatedWork) {
bestSuperblock = _superblockHash;
bestSuperblockAccumulatedWork = superblock.accumulatedWork;
}
emit ApprovedSuperblock(_superblockHash, _validator);
return (ERR_SUPERBLOCK_OK, _superblockHash);
}
// @dev - Challenge a proposed superblock
//
// A new superblock can be challenged to start a battle
// to verify the correctness of the data submitted.
//
// @param _superblockHash Id of the superblock to challenge
// @param _challenger Address requesting a challenge
// @return Error code and superblockHash
function challenge(bytes32 _superblockHash, address _challenger) public returns (uint, bytes32) {
if (msg.sender != trustedClaimManager) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER);
return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0);
}
SuperblockInfo storage superblock = superblocks[_superblockHash];
if (superblock.status != Status.New && superblock.status != Status.InBattle) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS);
return (ERR_SUPERBLOCK_BAD_STATUS, 0);
}
if(superblock.submitter == _challenger){
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_OWN_CHALLENGE);
return (ERR_SUPERBLOCK_OWN_CHALLENGE, 0);
}
superblock.status = Status.InBattle;
emit ChallengeSuperblock(_superblockHash, _challenger);
return (ERR_SUPERBLOCK_OK, _superblockHash);
}
// @dev - Semi-approve a challenged superblock
//
// A challenged superblock can be marked as semi-approved
// if it satisfies all the queries or when all challengers have
// stopped participating.
//
// @param _superblockHash Id of the superblock to semi-approve
// @param _validator Address requesting semi approval
// @return Error code and superblockHash
function semiApprove(bytes32 _superblockHash, address _validator) public returns (uint, bytes32) {
if (msg.sender != trustedClaimManager) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER);
return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0);
}
SuperblockInfo storage superblock = superblocks[_superblockHash];
if (superblock.status != Status.InBattle && superblock.status != Status.New) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS);
return (ERR_SUPERBLOCK_BAD_STATUS, 0);
}
superblock.status = Status.SemiApproved;
emit SemiApprovedSuperblock(_superblockHash, _validator);
return (ERR_SUPERBLOCK_OK, _superblockHash);
}
// @dev - Invalidates a superblock
//
// A superblock with incorrect data can be invalidated immediately.
// Superblocks that are not in the main chain can be invalidated
// if not enough superblocks follow them, i.e. they don't have
// enough descendants.
//
// @param _superblockHash Id of the superblock to invalidate
// @param _validator Address requesting superblock invalidation
// @return Error code and superblockHash
function invalidate(bytes32 _superblockHash, address _validator) public returns (uint, bytes32) {
if (msg.sender != trustedClaimManager) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER);
return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0);
}
SuperblockInfo storage superblock = superblocks[_superblockHash];
if (superblock.status != Status.InBattle && superblock.status != Status.SemiApproved) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS);
return (ERR_SUPERBLOCK_BAD_STATUS, 0);
}
superblock.status = Status.Invalid;
emit InvalidSuperblock(_superblockHash, _validator);
return (ERR_SUPERBLOCK_OK, _superblockHash);
}
// @dev - relays transaction `_txBytes` to `_untrustedTargetContract`'s processTransaction() method.
// Also logs the value of processTransaction.
// Note: callers cannot be 100% certain when an ERR_RELAY_VERIFY occurs because
// it may also have been returned by processTransaction(). Callers should be
// aware of the contract that they are relaying transactions to and
// understand what that contract's processTransaction method returns.
//
// @param _txBytes - transaction bytes
// @param _txIndex - transaction's index within the block
// @param _txSiblings - transaction's Merkle siblings
// @param _syscoinBlockHeader - block header containing transaction
// @param _syscoinBlockIndex - block's index withing superblock
// @param _syscoinBlockSiblings - block's merkle siblings
// @param _superblockHash - superblock containing block header
// @param _untrustedTargetContract - the contract that is going to process the transaction
function relayTx(
bytes memory _txBytes,
uint _txIndex,
uint[] _txSiblings,
bytes memory _syscoinBlockHeader,
uint _syscoinBlockIndex,
uint[] memory _syscoinBlockSiblings,
bytes32 _superblockHash,
SyscoinTransactionProcessor _untrustedTargetContract
) public returns (uint) {
// Check if Syscoin block belongs to given superblock
if (bytes32(SyscoinMessageLibrary.computeMerkle(SyscoinMessageLibrary.dblShaFlip(_syscoinBlockHeader), _syscoinBlockIndex, _syscoinBlockSiblings))
!= getSuperblockMerkleRoot(_superblockHash)) {
// Syscoin block is not in superblock
emit RelayTransaction(bytes32(0), ERR_SUPERBLOCK);
return ERR_SUPERBLOCK;
}
uint txHash = verifyTx(_txBytes, _txIndex, _txSiblings, _syscoinBlockHeader, _superblockHash);
if (txHash != 0) {
uint ret = parseTxHelper(_txBytes, txHash, _untrustedTargetContract);
if(ret != 0){
emit RelayTransaction(bytes32(0), ret);
return ret;
}
ProcessTransactionParams memory params = txParams[txHash];
params.superblockSubmitterAddress = superblocks[_superblockHash].submitter;
txParams[txHash] = params;
return verifyTxHelper(txHash);
}
emit RelayTransaction(bytes32(0), ERR_RELAY_VERIFY);
return(ERR_RELAY_VERIFY);
}
function parseTxHelper(bytes memory _txBytes, uint txHash, SyscoinTransactionProcessor _untrustedTargetContract) private returns (uint) {
uint value;
address destinationAddress;
uint32 _assetGUID;
uint ret;
(ret, value, destinationAddress, _assetGUID) = SyscoinMessageLibrary.parseTransaction(_txBytes);
if(ret != 0){
return ret;
}
ProcessTransactionParams memory params;
params.value = value;
params.destinationAddress = destinationAddress;
params.assetGUID = _assetGUID;
params.untrustedTargetContract = _untrustedTargetContract;
txParams[txHash] = params;
return 0;
}
function verifyTxHelper(uint txHash) private returns (uint) {
ProcessTransactionParams memory params = txParams[txHash];
uint returnCode = params.untrustedTargetContract.processTransaction(txHash, params.value, params.destinationAddress, params.assetGUID, params.superblockSubmitterAddress);
emit RelayTransaction(bytes32(txHash), returnCode);
return (returnCode);
}
// @dev - Checks whether the transaction given by `_txBytes` is in the block identified by `_txBlockHeaderBytes`.
// First it guards against a Merkle tree collision attack by raising an error if the transaction is exactly 64 bytes long,
// then it calls helperVerifyHash to do the actual check.
//
// @param _txBytes - transaction bytes
// @param _txIndex - transaction's index within the block
// @param _siblings - transaction's Merkle siblings
// @param _txBlockHeaderBytes - block header containing transaction
// @param _txsuperblockHash - superblock containing block header
// @return - SHA-256 hash of _txBytes if the transaction is in the block, 0 otherwise
// TODO: this can probably be made private
function verifyTx(
bytes memory _txBytes,
uint _txIndex,
uint[] memory _siblings,
bytes memory _txBlockHeaderBytes,
bytes32 _txsuperblockHash
) public returns (uint) {
uint txHash = SyscoinMessageLibrary.dblShaFlip(_txBytes);
if (_txBytes.length == 64) { // todo: is check 32 also needed?
emit VerifyTransaction(bytes32(txHash), ERR_TX_64BYTE);
return 0;
}
if (helperVerifyHash(txHash, _txIndex, _siblings, _txBlockHeaderBytes, _txsuperblockHash) == 1) {
return txHash;
} else {
// log is done via helperVerifyHash
return 0;
}
}
// @dev - Checks whether the transaction identified by `_txHash` is in the block identified by `_blockHeaderBytes`
// and whether the block is in the Syscoin main chain. Transaction check is done via Merkle proof.
// Note: no verification is performed to prevent txHash from just being an
// internal hash in the Merkle tree. Thus this helper method should NOT be used
// directly and is intended to be private.
//
// @param _txHash - transaction hash
// @param _txIndex - transaction's index within the block
// @param _siblings - transaction's Merkle siblings
// @param _blockHeaderBytes - block header containing transaction
// @param _txsuperblockHash - superblock containing block header
// @return - 1 if the transaction is in the block and the block is in the main chain,
// 20020 (ERR_CONFIRMATIONS) if the block is not in the main chain,
// 20050 (ERR_MERKLE_ROOT) if the block is in the main chain but the Merkle proof fails.
function helperVerifyHash(
uint256 _txHash,
uint _txIndex,
uint[] memory _siblings,
bytes memory _blockHeaderBytes,
bytes32 _txsuperblockHash
) private returns (uint) {
//TODO: Verify superblock is in superblock's main chain
if (!isApproved(_txsuperblockHash) || !inMainChain(_txsuperblockHash)) {
emit VerifyTransaction(bytes32(_txHash), ERR_CHAIN);
return (ERR_CHAIN);
}
// Verify tx Merkle root
uint merkle = SyscoinMessageLibrary.getHeaderMerkleRoot(_blockHeaderBytes);
if (SyscoinMessageLibrary.computeMerkle(_txHash, _txIndex, _siblings) != merkle) {
emit VerifyTransaction(bytes32(_txHash), ERR_MERKLE_ROOT);
return (ERR_MERKLE_ROOT);
}
emit VerifyTransaction(bytes32(_txHash), 1);
return (1);
}
// @dev - Calculate superblock hash from superblock data
//
// @param _blocksMerkleRoot Root of the merkle tree of blocks contained in a superblock
// @param _accumulatedWork Accumulated proof of work of the last block in the superblock
// @param _timestamp Timestamp of the last block in the superblock
// @param _prevTimestamp Timestamp of the block when the last difficulty adjustment happened (every 360 blocks)
// @param _lastHash Hash of the last block in the superblock
// @param _lastBits Difficulty bits of the last block in the superblock
// @param _parentId Id of the parent superblock
// @param _blockHeight Block height of last block in superblock
// @return Superblock id
function calcSuperblockHash(
bytes32 _blocksMerkleRoot,
uint _accumulatedWork,
uint _timestamp,
uint _prevTimestamp,
bytes32 _lastHash,
uint32 _lastBits,
bytes32 _parentId,
uint32 _blockHeight
) public pure returns (bytes32) {
return keccak256(abi.encodePacked(
_blocksMerkleRoot,
_accumulatedWork,
_timestamp,
_prevTimestamp,
_lastHash,
_lastBits,
_parentId,
_blockHeight
));
}
// @dev - Returns the confirmed superblock with the most accumulated work
//
// @return Best superblock hash
function getBestSuperblock() public view returns (bytes32) {
return bestSuperblock;
}
// @dev - Returns the superblock data for the supplied superblock hash
//
// @return {
// bytes32 _blocksMerkleRoot,
// uint _accumulatedWork,
// uint _timestamp,
// uint _prevTimestamp,
// bytes32 _lastHash,
// uint32 _lastBits,
// bytes32 _parentId,
// address _submitter,
// Status _status,
// uint32 _blockHeight,
// } Superblock data
function getSuperblock(bytes32 superblockHash) public view returns (
bytes32 _blocksMerkleRoot,
uint _accumulatedWork,
uint _timestamp,
uint _prevTimestamp,
bytes32 _lastHash,
uint32 _lastBits,
bytes32 _parentId,
address _submitter,
Status _status,
uint32 _blockHeight
) {
SuperblockInfo storage superblock = superblocks[superblockHash];
return (
superblock.blocksMerkleRoot,
superblock.accumulatedWork,
superblock.timestamp,
superblock.prevTimestamp,
superblock.lastHash,
superblock.lastBits,
superblock.parentId,
superblock.submitter,
superblock.status,
superblock.blockHeight
);
}
// @dev - Returns superblock height
function getSuperblockHeight(bytes32 superblockHash) public view returns (uint32) {
return superblocks[superblockHash].height;
}
// @dev - Returns superblock internal index
function getSuperblockIndex(bytes32 superblockHash) public view returns (uint32) {
return superblocks[superblockHash].index;
}
// @dev - Return superblock ancestors' indexes
function getSuperblockAncestors(bytes32 superblockHash) public view returns (bytes32) {
return superblocks[superblockHash].ancestors;
}
// @dev - Return superblock blocks' Merkle root
function getSuperblockMerkleRoot(bytes32 _superblockHash) public view returns (bytes32) {
return superblocks[_superblockHash].blocksMerkleRoot;
}
// @dev - Return superblock timestamp
function getSuperblockTimestamp(bytes32 _superblockHash) public view returns (uint) {
return superblocks[_superblockHash].timestamp;
}
// @dev - Return superblock prevTimestamp
function getSuperblockPrevTimestamp(bytes32 _superblockHash) public view returns (uint) {
return superblocks[_superblockHash].prevTimestamp;
}
// @dev - Return superblock last block hash
function getSuperblockLastHash(bytes32 _superblockHash) public view returns (bytes32) {
return superblocks[_superblockHash].lastHash;
}
// @dev - Return superblock parent
function getSuperblockParentId(bytes32 _superblockHash) public view returns (bytes32) {
return superblocks[_superblockHash].parentId;
}
// @dev - Return superblock accumulated work
function getSuperblockAccumulatedWork(bytes32 _superblockHash) public view returns (uint) {
return superblocks[_superblockHash].accumulatedWork;
}
// @dev - Return superblock status
function getSuperblockStatus(bytes32 _superblockHash) public view returns (Status) {
return superblocks[_superblockHash].status;
}
// @dev - Return indexNextSuperblock
function getIndexNextSuperblock() public view returns (uint32) {
return indexNextSuperblock;
}
// @dev - Calculate Merkle root from Syscoin block hashes
function makeMerkle(bytes32[] hashes) public pure returns (bytes32) {
return SyscoinMessageLibrary.makeMerkle(hashes);
}
function isApproved(bytes32 _superblockHash) public view returns (bool) {
return (getSuperblockStatus(_superblockHash) == Status.Approved);
}
function getChainHeight() public view returns (uint) {
return superblocks[bestSuperblock].height;
}
// @dev - write `_fourBytes` into `_word` starting from `_position`
// This is useful for writing 32bit ints inside one 32 byte word
//
// @param _word - information to be partially overwritten
// @param _position - position to start writing from
// @param _eightBytes - information to be written
function writeUint32(bytes32 _word, uint _position, uint32 _fourBytes) private pure returns (bytes32) {
bytes32 result;
assembly {
let pointer := mload(0x40)
mstore(pointer, _word)
mstore8(add(pointer, _position), byte(28, _fourBytes))
mstore8(add(pointer, add(_position,1)), byte(29, _fourBytes))
mstore8(add(pointer, add(_position,2)), byte(30, _fourBytes))
mstore8(add(pointer, add(_position,3)), byte(31, _fourBytes))
result := mload(pointer)
}
return result;
}
uint constant ANCESTOR_STEP = 5;
uint constant NUM_ANCESTOR_DEPTHS = 8;
// @dev - Update ancestor to the new height
function updateAncestors(bytes32 ancestors, uint32 index, uint height) internal pure returns (bytes32) {
uint step = ANCESTOR_STEP;
ancestors = writeUint32(ancestors, 0, index);
uint i = 1;
while (i<NUM_ANCESTOR_DEPTHS && (height % step == 1)) {
ancestors = writeUint32(ancestors, 4*i, index);
step *= ANCESTOR_STEP;
++i;
}
return ancestors;
}
// @dev - Returns a list of superblock hashes (9 hashes maximum) that helps an agent find out what
// superblocks are missing.
// The first position contains bestSuperblock, then
// bestSuperblock - 1,
// (bestSuperblock-1) - ((bestSuperblock-1) % 5), then
// (bestSuperblock-1) - ((bestSuperblock-1) % 25), ... until
// (bestSuperblock-1) - ((bestSuperblock-1) % 78125)
//
// @return - list of up to 9 ancestor supeerblock id
function getSuperblockLocator() public view returns (bytes32[9]) {
bytes32[9] memory locator;
locator[0] = bestSuperblock;
bytes32 ancestors = getSuperblockAncestors(bestSuperblock);
uint i = NUM_ANCESTOR_DEPTHS;
while (i > 0) {
locator[i] = indexSuperblock[uint32(ancestors & 0xFFFFFFFF)];
ancestors >>= 32;
--i;
}
return locator;
}
// @dev - Return ancestor at given index
function getSuperblockAncestor(bytes32 superblockHash, uint index) internal view returns (bytes32) {
bytes32 ancestors = superblocks[superblockHash].ancestors;
uint32 ancestorsIndex =
uint32(ancestors[4*index + 0]) * 0x1000000 +
uint32(ancestors[4*index + 1]) * 0x10000 +
uint32(ancestors[4*index + 2]) * 0x100 +
uint32(ancestors[4*index + 3]) * 0x1;
return indexSuperblock[ancestorsIndex];
}
// dev - returns depth associated with an ancestor index; applies to any superblock
//
// @param _index - index of ancestor to be looked up; an integer between 0 and 7
// @return - depth corresponding to said index, i.e. 5**index
function getAncDepth(uint _index) private pure returns (uint) {
return ANCESTOR_STEP**(uint(_index));
}
// @dev - return superblock hash at a given height in superblock main chain
//
// @param _height - superblock height
// @return - hash corresponding to block of height _blockHeight
function getSuperblockAt(uint _height) public view returns (bytes32) {
bytes32 superblockHash = bestSuperblock;
uint index = NUM_ANCESTOR_DEPTHS - 1;
while (getSuperblockHeight(superblockHash) > _height) {
while (getSuperblockHeight(superblockHash) - _height < getAncDepth(index) && index > 0) {
index -= 1;
}
superblockHash = getSuperblockAncestor(superblockHash, index);
}
return superblockHash;
}
// @dev - Checks if a superblock is in superblock main chain
//
// @param _blockHash - hash of the block being searched for in the main chain
// @return - true if the block identified by _blockHash is in the main chain,
// false otherwise
function inMainChain(bytes32 _superblockHash) internal view returns (bool) {
uint height = getSuperblockHeight(_superblockHash);
if (height == 0) return false;
return (getSuperblockAt(height) == _superblockHash);
}
} | @dev - Return superblock last block hash | function getSuperblockLastHash(bytes32 _superblockHash) public view returns (bytes32) {
return superblocks[_superblockHash].lastHash;
}
| 5,532,018 | [
1,
4625,
348,
7953,
560,
30,
225,
632,
5206,
300,
2000,
2240,
2629,
1142,
1203,
1651,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,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,
0,
0,
0,
0,
0,
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,
15172,
2629,
3024,
2310,
12,
3890,
1578,
389,
9565,
2629,
2310,
13,
1071,
1476,
1135,
261,
3890,
1578,
13,
288,
203,
3639,
327,
2240,
7996,
63,
67,
9565,
2629,
2310,
8009,
2722,
2310,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
interface ConflictResolutionInterface {
function minHouseStake(uint activeGames) public pure returns(uint);
function maxBalance() public pure returns(int);
function isValidBet(uint8 _gameType, uint _betNum, uint _betValue) public pure returns(bool);
function endGameConflict(
uint8 _gameType,
uint _betNum,
uint _betValue,
int _balance,
uint _stake,
bytes32 _serverSeed,
bytes32 _playerSeed
)
public
view
returns(int);
function serverForceGameEnd(
uint8 gameType,
uint _betNum,
uint _betValue,
int _balance,
uint _stake,
uint _endInitiatedTime
)
public
view
returns(int);
function playerForceGameEnd(
uint8 _gameType,
uint _betNum,
uint _betValue,
int _balance,
uint _stake,
uint _endInitiatedTime
)
public
view
returns(int);
}
library MathUtil {
/**
* @dev Returns the absolute value of _val.
* @param _val value
* @return The absolute value of _val.
*/
function abs(int _val) internal pure returns(uint) {
if (_val < 0) {
return uint(-_val);
} else {
return uint(_val);
}
}
/**
* @dev Calculate maximum.
*/
function max(uint _val1, uint _val2) internal pure returns(uint) {
return _val1 >= _val2 ? _val1 : _val2;
}
/**
* @dev Calculate minimum.
*/
function min(uint _val1, uint _val2) internal pure returns(uint) {
return _val1 <= _val2 ? _val1 : _val2;
}
}
contract Ownable {
address public owner;
event LogOwnerShipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Modifier, which throws if called by other account than owner.
*/
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/**
* @dev Set contract creator as initial owner
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Allows the current owner to transfer control of the
* contract to a newOwner _newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function setOwner(address _newOwner) public onlyOwner {
require(_newOwner != address(0));
LogOwnerShipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract ConflictResolutionManager is Ownable {
/// @dev Conflict resolution contract.
ConflictResolutionInterface public conflictRes;
/// @dev New Conflict resolution contract.
address public newConflictRes = 0;
/// @dev Time update of new conflict resolution contract was initiated.
uint public updateTime = 0;
/// @dev Min time before new conflict res contract can be activated after initiating update.
uint public constant MIN_TIMEOUT = 3 days;
/// @dev Min time before new conflict res contract can be activated after initiating update.
uint public constant MAX_TIMEOUT = 6 days;
/// @dev Update of conflict resolution contract was initiated.
event LogUpdatingConflictResolution(address newConflictResolutionAddress);
/// @dev New conflict resolution contract is active.
event LogUpdatedConflictResolution(address newConflictResolutionAddress);
/**
* @dev Constructor
* @param _conflictResAddress conflict resolution contract address.
*/
function ConflictResolutionManager(address _conflictResAddress) public {
conflictRes = ConflictResolutionInterface(_conflictResAddress);
}
/**
* @dev Initiate conflict resolution contract update.
* @param _newConflictResAddress New conflict resolution contract address.
*/
function updateConflictResolution(address _newConflictResAddress) public onlyOwner {
newConflictRes = _newConflictResAddress;
updateTime = block.timestamp;
LogUpdatingConflictResolution(_newConflictResAddress);
}
/**
* @dev Active new conflict resolution contract.
*/
function activateConflictResolution() public onlyOwner {
require(newConflictRes != 0);
require(updateTime != 0);
require(updateTime + MIN_TIMEOUT <= block.timestamp && block.timestamp <= updateTime + MAX_TIMEOUT);
conflictRes = ConflictResolutionInterface(newConflictRes);
newConflictRes = 0;
updateTime = 0;
LogUpdatedConflictResolution(newConflictRes);
}
}
contract Pausable is Ownable {
/// @dev Is contract paused.
bool public paused = false;
/// @dev Time pause was called
uint public timePaused = 0;
/// @dev Modifier, which only allows function execution if not paused.
modifier onlyNotPaused() {
require(!paused);
_;
}
/// @dev Modifier, which only allows function execution if paused.
modifier onlyPaused() {
require(paused);
_;
}
/// @dev Modifier, which only allows function execution if paused longer than timeSpan.
modifier onlyPausedSince(uint timeSpan) {
require(paused && timePaused + timeSpan <= block.timestamp);
_;
}
/// @dev Event is fired if paused.
event LogPause();
/// @dev Event is fired if pause is ended.
event LogUnpause();
/**
* @dev Pause contract. No new game sessions can be created.
*/
function pause() public onlyOwner onlyNotPaused {
paused = true;
timePaused = block.timestamp;
LogPause();
}
/**
* @dev Unpause contract.
*/
function unpause() public onlyOwner onlyPaused {
paused = false;
timePaused = 0;
LogUnpause();
}
}
contract Destroyable is Pausable {
/// @dev After pausing the contract for 20 days owner can selfdestruct it.
uint public constant TIMEOUT_DESTROY = 20 days;
/**
* @dev Destroy contract and transfer ether to address _targetAddress.
*/
function destroy() public onlyOwner onlyPausedSince(TIMEOUT_DESTROY) {
selfdestruct(owner);
}
}
contract GameChannelBase is Destroyable, ConflictResolutionManager {
/// @dev Different game session states.
enum GameStatus {
ENDED, ///< @dev Game session is ended.
ACTIVE, ///< @dev Game session is active.
WAITING_FOR_SERVER, ///< @dev Waiting for server to accept game session.
PLAYER_INITIATED_END, ///< @dev Player initiated non regular end.
SERVER_INITIATED_END ///< @dev Server initiated non regular end.
}
/// @dev Reason game session ended.
enum ReasonEnded {
REGULAR_ENDED, ///< @dev Game session is regularly ended.
END_FORCED_BY_SERVER, ///< @dev Player did not respond. Server forced end.
END_FORCED_BY_PLAYER, ///< @dev Server did not respond. Player forced end.
REJECTED_BY_SERVER, ///< @dev Server rejected game session.
CANCELLED_BY_PLAYER ///< @dev Player canceled game session before server accepted it.
}
struct Game {
/// @dev Game session status.
GameStatus status;
/// @dev Reason game session ended.
ReasonEnded reasonEnded;
/// @dev Player's stake.
uint stake;
/// @dev Last game round info if not regularly ended.
/// If game session is ended normally this data is not used.
uint8 gameType;
uint32 roundId;
uint16 betNum;
uint betValue;
int balance;
bytes32 playerSeed;
bytes32 serverSeed;
uint endInitiatedTime;
}
/// @dev Minimal time span between profit transfer.
uint public constant MIN_TRANSFER_TIMESPAN = 1 days;
/// @dev Maximal time span between profit transfer.
uint public constant MAX_TRANSFER_TIMSPAN = 6 * 30 days;
/// @dev Current active game sessions.
uint public activeGames = 0;
/// @dev Game session id counter. Points to next free game session slot. So gameIdCntr -1 is the
// number of game sessions created.
uint public gameIdCntr;
/// @dev Only this address can accept and end games.
address public serverAddress;
/// @dev Address to transfer profit to.
address public houseAddress;
/// @dev Current house stake.
uint public houseStake = 0;
/// @dev House profit since last profit transfer.
int public houseProfit = 0;
/// @dev Min value player needs to deposit for creating game session.
uint public minStake;
/// @dev Max value player can deposit for creating game session.
uint public maxStake;
/// @dev Timeout until next profit transfer is allowed.
uint public profitTransferTimeSpan = 14 days;
/// @dev Last time profit transferred to house.
uint public lastProfitTransferTimestamp;
bytes32 public typeHash;
/// @dev Maps gameId to game struct.
mapping (uint => Game) public gameIdGame;
/// @dev Maps player address to current player game id.
mapping (address => uint) public playerGameId;
/// @dev Maps player address to pending returns.
mapping (address => uint) public pendingReturns;
/// @dev Modifier, which only allows to execute if house stake is high enough.
modifier onlyValidHouseStake(uint _activeGames) {
uint minHouseStake = conflictRes.minHouseStake(_activeGames);
require(houseStake >= minHouseStake);
_;
}
/// @dev Modifier to check if value send fulfills player stake requirements.
modifier onlyValidValue() {
require(minStake <= msg.value && msg.value <= maxStake);
_;
}
/// @dev Modifier, which only allows server to call function.
modifier onlyServer() {
require(msg.sender == serverAddress);
_;
}
/// @dev Modifier, which only allows to set valid transfer timeouts.
modifier onlyValidTransferTimeSpan(uint transferTimeout) {
require(transferTimeout >= MIN_TRANSFER_TIMESPAN
&& transferTimeout <= MAX_TRANSFER_TIMSPAN);
_;
}
/// @dev This event is fired when player creates game session.
event LogGameCreated(address indexed player, uint indexed gameId, uint stake, bytes32 endHash);
/// @dev This event is fired when server rejects player's game.
event LogGameRejected(address indexed player, uint indexed gameId);
/// @dev This event is fired when server accepts player's game.
event LogGameAccepted(address indexed player, uint indexed gameId, bytes32 endHash);
/// @dev This event is fired when player requests conflict end.
event LogPlayerRequestedEnd(address indexed player, uint indexed gameId);
/// @dev This event is fired when server requests conflict end.
event LogServerRequestedEnd(address indexed player, uint indexed gameId);
/// @dev This event is fired when game session is ended.
event LogGameEnded(address indexed player, uint indexed gameId, ReasonEnded reason);
/// @dev this event is fired when owner modifies player's stake limits.
event LogStakeLimitsModified(uint minStake, uint maxStake);
/**
* @dev Contract constructor.
* @param _serverAddress Server address.
* @param _minStake Min value player needs to deposit to create game session.
* @param _maxStake Max value player can deposit to create game session.
* @param _conflictResAddress Conflict resolution contract address.
* @param _houseAddress House address to move profit to.
*/
function GameChannelBase(
address _serverAddress,
uint _minStake,
uint _maxStake,
address _conflictResAddress,
address _houseAddress,
uint _gameIdCntr
)
public
ConflictResolutionManager(_conflictResAddress)
{
require(_minStake > 0 && _minStake <= _maxStake);
require(_gameIdCntr > 0);
gameIdCntr = _gameIdCntr;
serverAddress = _serverAddress;
houseAddress = _houseAddress;
lastProfitTransferTimestamp = block.timestamp;
minStake = _minStake;
maxStake = _maxStake;
typeHash = keccak256(
"uint32 Round Id",
"uint8 Game Type",
"uint16 Number",
"uint Value (Wei)",
"int Current Balance (Wei)",
"bytes32 Server Hash",
"bytes32 Player Hash",
"uint Game Id",
"address Contract Address"
);
}
/**
* @notice Withdraw pending returns.
*/
function withdraw() public {
uint toTransfer = pendingReturns[msg.sender];
require(toTransfer > 0);
pendingReturns[msg.sender] = 0;
msg.sender.transfer(toTransfer);
}
/**
* @notice Transfer house profit to houseAddress.
*/
function transferProfitToHouse() public {
require(lastProfitTransferTimestamp + profitTransferTimeSpan <= block.timestamp);
if (houseProfit <= 0) {
// update last transfer timestamp
lastProfitTransferTimestamp = block.timestamp;
return;
}
// houseProfit is gt 0 => safe to cast
uint toTransfer = uint(houseProfit);
assert(houseStake >= toTransfer);
houseProfit = 0;
lastProfitTransferTimestamp = block.timestamp;
houseStake = houseStake - toTransfer;
houseAddress.transfer(toTransfer);
}
/**
* @dev Set profit transfer time span.
*/
function setProfitTransferTimeSpan(uint _profitTransferTimeSpan)
public
onlyOwner
onlyValidTransferTimeSpan(_profitTransferTimeSpan)
{
profitTransferTimeSpan = _profitTransferTimeSpan;
}
/**
* @dev Increase house stake by msg.value
*/
function addHouseStake() public payable onlyOwner {
houseStake += msg.value;
}
/**
* @dev Withdraw house stake.
*/
function withdrawHouseStake(uint value) public onlyOwner {
uint minHouseStake = conflictRes.minHouseStake(activeGames);
require(value <= houseStake && houseStake - value >= minHouseStake);
require(houseProfit <= 0 || uint(houseProfit) <= houseStake - value);
houseStake = houseStake - value;
owner.transfer(value);
}
/**
* @dev Withdraw house stake and profit.
*/
function withdrawAll() public onlyOwner onlyPausedSince(3 days) {
houseProfit = 0;
uint toTransfer = houseStake;
houseStake = 0;
owner.transfer(toTransfer);
}
/**
* @dev Set new house address.
* @param _houseAddress New house address.
*/
function setHouseAddress(address _houseAddress) public onlyOwner {
houseAddress = _houseAddress;
}
/**
* @dev Set stake min and max value.
* @param _minStake Min stake.
* @param _maxStake Max stake.
*/
function setStakeRequirements(uint _minStake, uint _maxStake) public onlyOwner {
require(_minStake > 0 && _minStake <= _maxStake);
minStake = _minStake;
maxStake = _maxStake;
LogStakeLimitsModified(minStake, maxStake);
}
/**
* @dev Close game session.
* @param _game Game session data.
* @param _gameId Id of game session.
* @param _playerAddress Player's address of game session.
* @param _reason Reason for closing game session.
* @param _balance Game session balance.
*/
function closeGame(
Game storage _game,
uint _gameId,
address _playerAddress,
ReasonEnded _reason,
int _balance
)
internal
{
_game.status = GameStatus.ENDED;
_game.reasonEnded = _reason;
_game.balance = _balance;
assert(activeGames > 0);
activeGames = activeGames - 1;
LogGameEnded(_playerAddress, _gameId, _reason);
}
/**
* @dev End game by paying out player and server.
* @param _game Game session to payout.
* @param _playerAddress Player's address.
*/
function payOut(Game storage _game, address _playerAddress) internal {
assert(_game.balance <= conflictRes.maxBalance());
assert(_game.status == GameStatus.ENDED);
assert(_game.stake <= maxStake);
assert((int(_game.stake) + _game.balance) >= 0);
uint valuePlayer = uint(int(_game.stake) + _game.balance);
if (_game.balance > 0 && int(houseStake) < _game.balance) {
// Should never happen!
// House is bankrupt.
// Payout left money.
valuePlayer = houseStake;
}
houseProfit = houseProfit - _game.balance;
int newHouseStake = int(houseStake) - _game.balance;
assert(newHouseStake >= 0);
houseStake = uint(newHouseStake);
pendingReturns[_playerAddress] += valuePlayer;
if (pendingReturns[_playerAddress] > 0) {
safeSend(_playerAddress);
}
}
/**
* @dev Send value of pendingReturns[_address] to _address.
* @param _address Address to send value to.
*/
function safeSend(address _address) internal {
uint valueToSend = pendingReturns[_address];
assert(valueToSend > 0);
pendingReturns[_address] = 0;
if (_address.send(valueToSend) == false) {
pendingReturns[_address] = valueToSend;
}
}
/**
* @dev Verify signature of given data. Throws on verification failure.
* @param _sig Signature of given data in the form of rsv.
* @param _address Address of signature signer.
*/
function verifySig(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress,
bytes _sig,
address _address
)
internal
view
{
// check if this is the correct contract
address contractAddress = this;
require(_contractAddress == contractAddress);
bytes32 roundHash = calcHash(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress
);
verify(
roundHash,
_sig,
_address
);
}
/**
* @dev Calculate typed hash of given data (compare eth_signTypedData).
* @return Hash of given data.
*/
function calcHash(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress
)
private
view
returns(bytes32)
{
bytes32 dataHash = keccak256(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress
);
return keccak256(typeHash, dataHash);
}
/**
* @dev Check if _sig is valid signature of _hash. Throws if invalid signature.
* @param _hash Hash to check signature of.
* @param _sig Signature of _hash.
* @param _address Address of signer.
*/
function verify(
bytes32 _hash,
bytes _sig,
address _address
)
private
pure
{
var (r, s, v) = signatureSplit(_sig);
address addressRecover = ecrecover(_hash, v, r, s);
require(addressRecover == _address);
}
/**
* @dev Split the given signature of the form rsv in r s v. v is incremented with 27 if
* it is below 2.
* @param _signature Signature to split.
* @return r s v
*/
function signatureSplit(bytes _signature)
private
pure
returns (bytes32 r, bytes32 s, uint8 v)
{
require(_signature.length == 65);
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := and(mload(add(_signature, 65)), 0xff)
}
if (v < 2) {
v = v + 27;
}
}
}
contract GameChannelConflict is GameChannelBase {
/**
* @dev Contract constructor.
* @param _serverAddress Server address.
* @param _minStake Min value player needs to deposit to create game session.
* @param _maxStake Max value player can deposit to create game session.
* @param _conflictResAddress Conflict resolution contract address
* @param _houseAddress House address to move profit to
*/
function GameChannelConflict(
address _serverAddress,
uint _minStake,
uint _maxStake,
address _conflictResAddress,
address _houseAddress,
uint _gameIdCtr
)
public
GameChannelBase(_serverAddress, _minStake, _maxStake, _conflictResAddress, _houseAddress, _gameIdCtr)
{
// nothing to do
}
/**
* @dev Used by server if player does not end game session.
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Balance before this bet.
* @param _serverHash Hash of server seed for this bet.
* @param _playerHash Hash of player seed for this bet.
* @param _gameId Game session id.
* @param _contractAddress Address of this contract.
* @param _playerSig Player signature of this bet.
* @param _playerAddress Address of player.
* @param _serverSeed Server seed for this bet.
* @param _playerSeed Player seed for this bet.
*/
function serverEndGameConflict(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress,
bytes _playerSig,
address _playerAddress,
bytes32 _serverSeed,
bytes32 _playerSeed
)
public
onlyServer
{
verifySig(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress,
_playerSig,
_playerAddress
);
serverEndGameConflictImpl(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_serverSeed,
_playerSeed,
_gameId,
_playerAddress
);
}
/**
* @notice Can be used by player if server does not answer to the end game session request.
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Balance before this bet.
* @param _serverHash Hash of server seed for this bet.
* @param _playerHash Hash of player seed for this bet.
* @param _gameId Game session id.
* @param _contractAddress Address of this contract.
* @param _serverSig Server signature of this bet.
* @param _playerSeed Player seed for this bet.
*/
function playerEndGameConflict(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress,
bytes _serverSig,
bytes32 _playerSeed
)
public
{
verifySig(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress,
_serverSig,
serverAddress
);
playerEndGameConflictImpl(
_roundId,
_gameType,
_num,
_value,
_balance,
_playerHash,
_playerSeed,
_gameId,
msg.sender
);
}
/**
* @notice Cancel active game without playing. Useful if server stops responding before
* one game is played.
* @param _gameId Game session id.
*/
function playerCancelActiveGame(uint _gameId) public {
address playerAddress = msg.sender;
uint gameId = playerGameId[playerAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId);
if (game.status == GameStatus.ACTIVE) {
game.endInitiatedTime = block.timestamp;
game.status = GameStatus.PLAYER_INITIATED_END;
LogPlayerRequestedEnd(msg.sender, gameId);
} else if (game.status == GameStatus.SERVER_INITIATED_END && game.roundId == 0) {
closeGame(game, gameId, playerAddress, ReasonEnded.REGULAR_ENDED, 0);
payOut(game, playerAddress);
} else {
revert();
}
}
/**
* @dev Cancel active game without playing. Useful if player starts game session and
* does not play.
* @param _playerAddress Players' address.
* @param _gameId Game session id.
*/
function serverCancelActiveGame(address _playerAddress, uint _gameId) public onlyServer {
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId);
if (game.status == GameStatus.ACTIVE) {
game.endInitiatedTime = block.timestamp;
game.status = GameStatus.SERVER_INITIATED_END;
LogServerRequestedEnd(msg.sender, gameId);
} else if (game.status == GameStatus.PLAYER_INITIATED_END && game.roundId == 0) {
closeGame(game, gameId, _playerAddress, ReasonEnded.REGULAR_ENDED, 0);
payOut(game, _playerAddress);
} else {
revert();
}
}
/**
* @dev Force end of game if player does not respond. Only possible after a certain period of time
* to give the player a chance to respond.
* @param _playerAddress Player's address.
*/
function serverForceGameEnd(address _playerAddress, uint _gameId) public onlyServer {
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId);
require(game.status == GameStatus.SERVER_INITIATED_END);
// theoretically we have enough data to calculate winner
// but as player did not respond assume he has lost.
int newBalance = conflictRes.serverForceGameEnd(
game.gameType,
game.betNum,
game.betValue,
game.balance,
game.stake,
game.endInitiatedTime
);
closeGame(game, gameId, _playerAddress, ReasonEnded.END_FORCED_BY_SERVER, newBalance);
payOut(game, _playerAddress);
}
/**
* @notice Force end of game if server does not respond. Only possible after a certain period of time
* to give the server a chance to respond.
*/
function playerForceGameEnd(uint _gameId) public {
address playerAddress = msg.sender;
uint gameId = playerGameId[playerAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId);
require(game.status == GameStatus.PLAYER_INITIATED_END);
int newBalance = conflictRes.playerForceGameEnd(
game.gameType,
game.betNum,
game.betValue,
game.balance,
game.stake,
game.endInitiatedTime
);
closeGame(game, gameId, playerAddress, ReasonEnded.END_FORCED_BY_PLAYER, newBalance);
payOut(game, playerAddress);
}
/**
* @dev Conflict handling implementation. Stores game data and timestamp if game
* is active. If server has already marked conflict for game session the conflict
* resolution contract is used (compare conflictRes).
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Balance before this bet.
* @param _playerHash Hash of player's seed for this bet.
* @param _playerSeed Player's seed for this bet.
* @param _gameId game Game session id.
* @param _playerAddress Player's address.
*/
function playerEndGameConflictImpl(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _playerHash,
bytes32 _playerSeed,
uint _gameId,
address _playerAddress
)
private
{
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
int maxBalance = conflictRes.maxBalance();
require(gameId == _gameId);
require(_roundId > 0);
require(keccak256(_playerSeed) == _playerHash);
require(_value <= game.stake);
require(-int(game.stake) <= _balance && _balance <= maxBalance); // save to cast as ranges are fixed
require(int(game.stake) + _balance - int(_value) >= 0); // save to cast as ranges are fixed
require(conflictRes.isValidBet(_gameType, _num, _value));
if (game.status == GameStatus.SERVER_INITIATED_END && game.roundId == _roundId) {
game.playerSeed = _playerSeed;
endGameConflict(game, gameId, _playerAddress);
} else if (game.status == GameStatus.ACTIVE
|| (game.status == GameStatus.SERVER_INITIATED_END && game.roundId < _roundId)) {
game.status = GameStatus.PLAYER_INITIATED_END;
game.endInitiatedTime = block.timestamp;
game.roundId = _roundId;
game.gameType = _gameType;
game.betNum = _num;
game.betValue = _value;
game.balance = _balance;
game.playerSeed = _playerSeed;
game.serverSeed = bytes32(0);
LogPlayerRequestedEnd(msg.sender, gameId);
} else {
revert();
}
}
/**
* @dev Conflict handling implementation. Stores game data and timestamp if game
* is active. If player has already marked conflict for game session the conflict
* resolution contract is used (compare conflictRes).
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Balance before this bet.
* @param _serverHash Hash of server's seed for this bet.
* @param _playerHash Hash of player's seed for this bet.
* @param _serverSeed Server's seed for this bet.
* @param _playerSeed Player's seed for this bet.
* @param _playerAddress Player's address.
*/
function serverEndGameConflictImpl(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
bytes32 _serverSeed,
bytes32 _playerSeed,
uint _gameId,
address _playerAddress
)
private
{
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
int maxBalance = conflictRes.maxBalance();
require(gameId == _gameId);
require(_roundId > 0);
require(keccak256(_serverSeed) == _serverHash);
require(keccak256(_playerSeed) == _playerHash);
require(_value <= game.stake);
require(-int(game.stake) <= _balance && _balance <= maxBalance); // save to cast as ranges are fixed
require(int(game.stake) + _balance - int(_value) >= 0); // save to cast as ranges are fixed
require(conflictRes.isValidBet(_gameType, _num, _value));
if (game.status == GameStatus.PLAYER_INITIATED_END && game.roundId == _roundId) {
game.serverSeed = _serverSeed;
endGameConflict(game, gameId, _playerAddress);
} else if (game.status == GameStatus.ACTIVE
|| (game.status == GameStatus.PLAYER_INITIATED_END && game.roundId < _roundId)) {
game.status = GameStatus.SERVER_INITIATED_END;
game.endInitiatedTime = block.timestamp;
game.roundId = _roundId;
game.gameType = _gameType;
game.betNum = _num;
game.betValue = _value;
game.balance = _balance;
game.serverSeed = _serverSeed;
game.playerSeed = _playerSeed;
LogServerRequestedEnd(_playerAddress, gameId);
} else {
revert();
}
}
/**
* @dev End conflicting game.
* @param _game Game session data.
* @param _gameId Game session id.
* @param _playerAddress Player's address.
*/
function endGameConflict(Game storage _game, uint _gameId, address _playerAddress) private {
int newBalance = conflictRes.endGameConflict(
_game.gameType,
_game.betNum,
_game.betValue,
_game.balance,
_game.stake,
_game.serverSeed,
_game.playerSeed
);
closeGame(_game, _gameId, _playerAddress, ReasonEnded.REGULAR_ENDED, newBalance);
payOut(_game, _playerAddress);
}
}
contract GameChannel is GameChannelConflict {
/**
* @dev contract constructor
* @param _serverAddress Server address.
* @param _minStake Min value player needs to deposit to create game session.
* @param _maxStake Max value player can deposit to create game session.
* @param _conflictResAddress Conflict resolution contract address.
* @param _houseAddress House address to move profit to.
*/
function GameChannel(
address _serverAddress,
uint _minStake,
uint _maxStake,
address _conflictResAddress,
address _houseAddress,
uint _gameIdCntr
)
public
GameChannelConflict(_serverAddress, _minStake, _maxStake, _conflictResAddress, _houseAddress, _gameIdCntr)
{
// nothing to do
}
/**
* @notice Create games session request. msg.value needs to be valid stake value.
* @param _endHash Last hash of the hash chain generated by the player.
*/
function createGame(bytes32 _endHash)
public
payable
onlyValidValue
onlyValidHouseStake(activeGames + 1)
onlyNotPaused
{
address playerAddress = msg.sender;
uint previousGameId = playerGameId[playerAddress];
Game storage game = gameIdGame[previousGameId];
require(game.status == GameStatus.ENDED);
uint gameId = gameIdCntr++;
playerGameId[playerAddress] = gameId;
Game storage newGame = gameIdGame[gameId];
newGame.stake = msg.value;
newGame.status = GameStatus.WAITING_FOR_SERVER;
activeGames = activeGames + 1;
LogGameCreated(playerAddress, gameId, msg.value, _endHash);
}
/**
* @notice Cancel game session waiting for server acceptance.
* @param _gameId Game session id.
*/
function cancelGame(uint _gameId) public {
address playerAddress = msg.sender;
uint gameId = playerGameId[playerAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId);
require(game.status == GameStatus.WAITING_FOR_SERVER);
closeGame(game, gameId, playerAddress, ReasonEnded.CANCELLED_BY_PLAYER, 0);
payOut(game, playerAddress);
}
/**
* @dev Called by the server to reject game session created by player with address
* _playerAddress.
* @param _playerAddress Players's address who created the game session.
* @param _gameId Game session id.
*/
function rejectGame(address _playerAddress, uint _gameId) public onlyServer {
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
require(_gameId == gameId);
require(game.status == GameStatus.WAITING_FOR_SERVER);
closeGame(game, gameId, _playerAddress, ReasonEnded.REJECTED_BY_SERVER, 0);
payOut(game, _playerAddress);
LogGameRejected(_playerAddress, gameId);
}
/**
* @dev Called by server to accept game session created by player with
* address _playerAddress.
* @param _playerAddress Player's address who created the game.
* @param _gameId Game id of game session.
* @param _endHash Last hash of the hash chain generated by the server.
*/
function acceptGame(address _playerAddress, uint _gameId, bytes32 _endHash)
public
onlyServer
{
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
require(_gameId == gameId);
require(game.status == GameStatus.WAITING_FOR_SERVER);
game.status = GameStatus.ACTIVE;
LogGameAccepted(_playerAddress, gameId, _endHash);
}
/**
* @dev Regular end game session. Used if player and house have both
* accepted current game session state.
* The game session with gameId _gameId is closed
* and the player paid out. This functions is called by the server after
* the player requested the termination of the current game session.
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Current balance.
* @param _serverHash Hash of server's seed for this bet.
* @param _playerHash Hash of player's seed for this bet.
* @param _gameId Game session id.
* @param _contractAddress Address of this contract.
* @param _playerAddress Address of player.
* @param _playerSig Player's signature of this bet.
*/
function serverEndGame(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress,
address _playerAddress,
bytes _playerSig
)
public
onlyServer
{
verifySig(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress,
_playerSig,
_playerAddress
);
regularEndGame(_playerAddress, _roundId, _gameType, _num, _value, _balance, _gameId, _contractAddress);
}
/**
* @notice Regular end game session. Normally not needed as server ends game (@see serverEndGame).
* Can be used by player if server does not end game session.
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Current balance.
* @param _serverHash Hash of server's seed for this bet.
* @param _playerHash Hash of player's seed for this bet.
* @param _gameId Game session id.
* @param _contractAddress Address of this contract.
* @param _serverSig Server's signature of this bet.
*/
function playerEndGame(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress,
bytes _serverSig
)
public
{
verifySig(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress,
_serverSig,
serverAddress
);
regularEndGame(msg.sender, _roundId, _gameType, _num, _value, _balance, _gameId, _contractAddress);
}
/**
* @dev Regular end game session implementation. Used if player and house have both
* accepted current game session state. The game session with gameId _gameId is closed
* and the player paid out.
* @param _playerAddress Address of player.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Current balance.
* @param _gameId Game session id.
* @param _contractAddress Address of this contract.
*/
function regularEndGame(
address _playerAddress,
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
uint _gameId,
address _contractAddress
)
private
{
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
address contractAddress = this;
int maxBalance = conflictRes.maxBalance();
require(_gameId == gameId);
require(_roundId > 0);
// save to cast as game.stake hash fixed range
require(-int(game.stake) <= _balance && _balance <= maxBalance);
require((_gameType == 0) && (_num == 0) && (_value == 0));
require(_contractAddress == contractAddress);
require(game.status == GameStatus.ACTIVE);
closeGame(game, gameId, _playerAddress, ReasonEnded.REGULAR_ENDED, _balance);
payOut(game, _playerAddress);
}
} | @dev Current active game sessions. | uint public activeGames = 0;
| 1,034,089 | [
1,
4625,
348,
7953,
560,
30,
225,
632,
5206,
6562,
2695,
7920,
8856,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
1071,
2695,
43,
753,
273,
374,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x1Bf5a4B71E284705E81cEe233f76AC938340558f/sources/contracts/market/template/MarketTieredLeverage.sol | @notice Allows users to exit the market after it has been deprecated NOTE we don't want the seeder to redeem because it could lead to division by 0 when the last person exits reverse pending deposits, no dependency on lastExecutedEpoch | function _exitDeprecatedMarket(address user, IMarketCommon.PoolType poolType) internal {
require(
user != address(0) && user != PERMANENT_INITIAL_LIQUIDITY_HOLDER,
"User can't be 0 or seeder"
);
uint32 lastExecutedEpoch = _epochInfo.latestExecutedEpochIndex;
IMarketCommon.UserAction memory userAction;
address syntheticToken;
uint256 syntheticToken_price;
uint256 maxPoolIndex;
uint256 amountPaymentTokenToSend;
maxPoolIndex = _numberOfPoolsOfType[uint256(poolType)];
for (uint8 poolIndex = 0; poolIndex < maxPoolIndex; poolIndex++) {
userAction = _user_paymentToken_depositAction[user][poolType][poolIndex];
if (userAction.amount > 0 || userAction.nextEpochAmount > 0) {
uint256 amount = userAction.amount;
uint256 nextEpochAmount = userAction.nextEpochAmount;
userAction.amount = 0;
userAction.nextEpochAmount = 0;
userAction.correspondingEpoch = 0;
IYieldManager(_yieldManager).transferPaymentTokensToUser(user, amount + nextEpochAmount);
}
if (userAction.amount > 0 || userAction.nextEpochAmount > 0) {
syntheticToken_price = _syntheticToken_priceSnapshot[lastExecutedEpoch][poolType][
poolIndex
];
amountPaymentTokenToSend = _getAmountPaymentToken(
userAction.amount + userAction.nextEpochAmount,
syntheticToken_price
);
userAction.amount = 0;
userAction.nextEpochAmount = 0;
userAction.correspondingEpoch = 0;
IYieldManager(_yieldManager).transferPaymentTokensToUser(user, amountPaymentTokenToSend);
}
uint256 balance = IERC20(syntheticToken).balanceOf(user);
if (balance > 0) {
syntheticToken_price = _syntheticToken_priceSnapshot[lastExecutedEpoch][poolType][
poolIndex
];
amountPaymentTokenToSend = _getAmountPaymentToken(balance, syntheticToken_price);
ISyntheticToken(syntheticToken).burnWhenDeprecated(user, balance);
IYieldManager(_yieldManager).transferPaymentTokensToUser(user, amountPaymentTokenToSend);
}
}
}
| 9,520,632 | [
1,
4625,
348,
7953,
560,
30,
225,
632,
20392,
25619,
3677,
358,
2427,
326,
13667,
1839,
518,
711,
2118,
6849,
5219,
732,
2727,
1404,
2545,
326,
5009,
264,
358,
283,
24903,
2724,
518,
3377,
5871,
358,
16536,
635,
374,
1347,
326,
1142,
6175,
19526,
4219,
4634,
443,
917,
1282,
16,
1158,
4904,
603,
1142,
23839,
14638,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
8593,
13534,
3882,
278,
12,
2867,
729,
16,
467,
3882,
278,
6517,
18,
2864,
559,
2845,
559,
13,
2713,
288,
203,
565,
2583,
12,
203,
1377,
729,
480,
1758,
12,
20,
13,
597,
729,
480,
10950,
9560,
2222,
67,
28497,
67,
2053,
53,
3060,
4107,
67,
21424,
16,
203,
1377,
315,
1299,
848,
1404,
506,
374,
578,
5009,
264,
6,
203,
565,
11272,
203,
203,
565,
2254,
1578,
1142,
23839,
14638,
273,
389,
12015,
966,
18,
13550,
23839,
14638,
1016,
31,
203,
203,
565,
467,
3882,
278,
6517,
18,
1299,
1803,
3778,
729,
1803,
31,
203,
565,
1758,
25535,
1345,
31,
203,
565,
2254,
5034,
25535,
1345,
67,
8694,
31,
203,
565,
2254,
5034,
943,
2864,
1016,
31,
203,
565,
2254,
5034,
3844,
6032,
1345,
28878,
31,
203,
203,
565,
943,
2864,
1016,
273,
389,
2696,
951,
16639,
18859,
63,
11890,
5034,
12,
6011,
559,
13,
15533,
203,
565,
364,
261,
11890,
28,
2845,
1016,
273,
374,
31,
2845,
1016,
411,
943,
2864,
1016,
31,
2845,
1016,
27245,
288,
203,
1377,
729,
1803,
273,
389,
1355,
67,
9261,
1345,
67,
323,
1724,
1803,
63,
1355,
6362,
6011,
559,
6362,
6011,
1016,
15533,
203,
1377,
309,
261,
1355,
1803,
18,
8949,
405,
374,
747,
729,
1803,
18,
4285,
14638,
6275,
405,
374,
13,
288,
203,
3639,
2254,
5034,
3844,
273,
729,
1803,
18,
8949,
31,
203,
3639,
2254,
5034,
1024,
14638,
6275,
273,
729,
1803,
18,
4285,
14638,
6275,
31,
203,
3639,
729,
1803,
18,
8949,
273,
374,
31,
203,
3639,
729,
1803,
18,
4285,
14638,
6275,
273,
374,
31,
203,
3639,
729,
1803,
18,
3850,
17863,
310,
14638,
273,
374,
31,
203,
3639,
467,
16348,
1318,
24899,
23604,
1318,
2934,
13866,
6032,
5157,
774,
1299,
12,
1355,
16,
3844,
397,
1024,
14638,
6275,
1769,
203,
1377,
289,
203,
203,
203,
1377,
309,
261,
1355,
1803,
18,
8949,
405,
374,
747,
729,
1803,
18,
4285,
14638,
6275,
405,
374,
13,
288,
203,
3639,
25535,
1345,
67,
8694,
273,
389,
11982,
16466,
1345,
67,
8694,
4568,
63,
2722,
23839,
14638,
6362,
6011,
559,
6362,
203,
1850,
2845,
1016,
203,
3639,
308,
31,
203,
3639,
3844,
6032,
1345,
28878,
273,
389,
588,
6275,
6032,
1345,
12,
203,
1850,
729,
1803,
18,
8949,
397,
729,
1803,
18,
4285,
14638,
6275,
16,
203,
1850,
25535,
1345,
67,
8694,
203,
3639,
11272,
203,
3639,
729,
1803,
18,
8949,
273,
374,
31,
203,
3639,
729,
1803,
18,
4285,
14638,
6275,
273,
374,
31,
203,
3639,
729,
1803,
18,
3850,
17863,
310,
14638,
273,
374,
31,
203,
3639,
467,
16348,
1318,
24899,
23604,
1318,
2934,
13866,
6032,
5157,
774,
1299,
12,
1355,
16,
3844,
6032,
1345,
28878,
1769,
203,
1377,
289,
203,
203,
1377,
2254,
5034,
11013,
273,
467,
654,
39,
3462,
12,
11982,
16466,
1345,
2934,
12296,
951,
12,
1355,
1769,
203,
1377,
309,
261,
12296,
405,
374,
13,
288,
203,
3639,
25535,
1345,
67,
8694,
273,
389,
11982,
16466,
1345,
67,
8694,
4568,
63,
2722,
23839,
14638,
6362,
6011,
559,
6362,
203,
1850,
2845,
1016,
203,
3639,
308,
31,
203,
3639,
3844,
6032,
1345,
28878,
273,
389,
588,
6275,
6032,
1345,
12,
12296,
16,
25535,
1345,
67,
8694,
1769,
203,
3639,
4437,
878,
16466,
1345,
12,
11982,
16466,
1345,
2934,
70,
321,
9434,
13534,
12,
1355,
16,
11013,
1769,
203,
3639,
467,
16348,
1318,
24899,
23604,
1318,
2934,
13866,
6032,
5157,
774,
1299,
12,
1355,
16,
3844,
6032,
1345,
28878,
1769,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import {
Lib_CrossDomainUtils
} from "@eth-optimism/contracts/libraries/bridge/Lib_CrossDomainUtils.sol";
import { Lib_RLPWriter } from "@eth-optimism/contracts/libraries/rlp/Lib_RLPWriter.sol";
/**
* @title CrossDomainHashing
* This library is responsible for holding cross domain utility
* functions.
* TODO(tynes): merge with Lib_CrossDomainUtils
* TODO(tynes): fill out more devdocs
*/
library CrossDomainHashing {
/**
* @notice Compute the L2 transaction hash given
* data about an L1 deposit transaction. This is useful for
* environments that do not have access to arbitrary
* RLP encoding functionality but have access to the
* standard web3 API
* TODO: rearrange args in a sane way
* @param _l1BlockHash The L1 block hash corresponding to the block
* the deposit was included in
* @param _logIndex The log index of the event that the deposit was
* created from. This can be found on the transaction receipt
* @param _from The sender of the deposit
* @param _to The L2 contract to be called by the deposit transaction
* @param _isCreate Indicates if the deposit creates a contract
* @param _mint The amount of ETH being minted by the transaction
* @param _value The amount of ETH send in the L2 call
* @param _gas The gas limit for the L2 call
*/
function L2TransactionHash(
bytes32 _l1BlockHash,
uint256 _logIndex,
address _from,
address _to,
bool _isCreate,
uint256 _mint,
uint256 _value,
uint256 _gas,
bytes memory _data
) internal pure returns (bytes32) {
bytes memory raw = L2Transaction(
_l1BlockHash,
_logIndex,
_from,
_to,
_isCreate,
_mint,
_value,
_gas,
_data
);
return keccak256(raw);
}
/**
* @notice Compute the deposit transaction source hash.
* This value ensures that the L2 transaction hash is unique
* and deterministic based on L1 execution
* @param l1BlockHash The L1 blockhash corresponding to the block including
* the deposit
* @param logIndex The index of the log that created the deposit transaction
*/
function sourceHash(bytes32 l1BlockHash, uint256 logIndex) internal pure returns (bytes32) {
bytes32 depositId = keccak256(abi.encode(l1BlockHash, logIndex));
return keccak256(abi.encode(bytes32(0), depositId));
}
/**
* @notice RLP encode a deposit transaction
* This only works for user deposits, not system deposits
* TODO: better name + rearrange the input param ordering?
*/
function L2Transaction(
bytes32 _l1BlockHash,
uint256 _logIndex,
address _from,
address _to,
bool _isCreate,
uint256 _mint,
uint256 _value,
uint256 _gas,
bytes memory _data
) internal pure returns (bytes memory) {
bytes32 source = sourceHash(_l1BlockHash, _logIndex);
bytes[] memory raw = new bytes[](7);
raw[0] = Lib_RLPWriter.writeBytes(bytes32ToBytes(source));
raw[1] = Lib_RLPWriter.writeAddress(_from);
if (_isCreate == true) {
require(_to == address(0));
raw[2] = Lib_RLPWriter.writeBytes("");
} else {
raw[2] = Lib_RLPWriter.writeAddress(_to);
}
raw[3] = Lib_RLPWriter.writeUint(_mint);
raw[4] = Lib_RLPWriter.writeUint(_value);
raw[5] = Lib_RLPWriter.writeUint(_gas);
raw[6] = Lib_RLPWriter.writeBytes(_data);
bytes memory encoded = Lib_RLPWriter.writeList(raw);
return abi.encodePacked(uint8(0x7e), encoded);
}
/**
* @notice Helper function to turn bytes32 into bytes
*/
function bytes32ToBytes(bytes32 input) internal pure returns (bytes memory) {
bytes memory b = new bytes(32);
assembly {
mstore(add(b, 32), input) // set the bytes data
}
return b;
}
/**
* @notice Adds the version to the nonce
*/
function addVersionToNonce(uint256 _nonce, uint16 _version)
internal
pure
returns (uint256 nonce)
{
assembly {
nonce := or(shl(240, _version), _nonce)
}
}
/**
* @notice Gets the version out of the nonce
*/
function getVersionFromNonce(uint256 _nonce) internal pure returns (uint16 version) {
assembly {
version := shr(240, _nonce)
}
}
/**
* @notice Encodes the cross domain message based on the version that
* is encoded in the nonce
*/
function getVersionedEncoding(
uint256 _nonce,
address _sender,
address _target,
uint256 _value,
uint256 _gasLimit,
bytes memory _data
) internal pure returns (bytes memory) {
uint16 version = getVersionFromNonce(_nonce);
if (version == 0) {
return getEncodingV0(_target, _sender, _data, _nonce);
} else if (version == 1) {
return getEncodingV1(_nonce, _sender, _target, _value, _gasLimit, _data);
}
revert("Unknown version.");
}
/**
* @notice Compute the cross domain hash based on the versioned nonce
*/
function getVersionedHash(
uint256 _nonce,
address _sender,
address _target,
uint256 _value,
uint256 _gasLimit,
bytes memory _data
) internal pure returns (bytes32) {
uint16 version = getVersionFromNonce(_nonce);
if (version == 0) {
return getHashV0(_target, _sender, _data, _nonce);
} else if (version == 1) {
return getHashV1(_nonce, _sender, _target, _value, _gasLimit, _data);
}
revert("Unknown version.");
}
/**
* @notice Compute the legacy cross domain serialization
*/
function getEncodingV0(
address _target,
address _sender,
bytes memory _data,
uint256 _nonce
) internal pure returns (bytes memory) {
return Lib_CrossDomainUtils.encodeXDomainCalldata(_target, _sender, _data, _nonce);
}
/**
* @notice Compute the V1 cross domain serialization
*/
function getEncodingV1(
uint256 _nonce,
address _sender,
address _target,
uint256 _value,
uint256 _gasLimit,
bytes memory _data
) internal pure returns (bytes memory) {
return
abi.encodeWithSignature(
"relayMessage(uint256,address,address,uint256,uint256,bytes)",
_nonce,
_sender,
_target,
_value,
_gasLimit,
_data
);
}
/**
* @notice Compute the legacy hash of a cross domain message
*/
function getHashV0(
address _target,
address _sender,
bytes memory _data,
uint256 _nonce
) internal pure returns (bytes32) {
return keccak256(getEncodingV0(_target, _sender, _data, _nonce));
}
/**
* @notice Compute the V1 hash of a cross domain message
*/
function getHashV1(
uint256 _nonce,
address _sender,
address _target,
uint256 _value,
uint256 _gasLimit,
bytes memory _data
) internal pure returns (bytes32) {
return keccak256(getEncodingV1(_nonce, _sender, _target, _value, _gasLimit, _data));
}
}
| * @notice Gets the version out of the nonce/ | function getVersionFromNonce(uint256 _nonce) internal pure returns (uint16 version) {
assembly {
version := shr(240, _nonce)
}
}
| 895,740 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
20392,
11881,
326,
1177,
596,
434,
326,
7448,
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,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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
8343,
1265,
13611,
12,
11890,
5034,
389,
12824,
13,
2713,
16618,
1135,
261,
11890,
2313,
1177,
13,
288,
203,
3639,
19931,
288,
203,
5411,
1177,
519,
699,
86,
12,
28784,
16,
389,
12824,
13,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x3E7bcAc4B0364477b6fF9bBF1DB2b726DC833CdD/sources/contracts/Wen_Lunch/HarleyQuinn.sol | Contract implementation We will set a minimum amount of tokens to be swaped => 5M | contract HarleyQuinn is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'HarleyQuinn';
string private _symbol = 'HarleyQuinn';
uint8 private _decimals = 9;
uint256 private _taxFee = 1;
uint256 private _developmentFee = 10;
uint256 private _previousTaxFee = _taxFee;
uint256 private _previousDevelopmentFee = _developmentFee;
address payable public _developmentWalletAddress;
address payable public _marketingWalletAddress;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwap = false;
bool public swapEnabled = true;
uint256 private _maxTxAmount = 15000000000e9;
uint256 private _numOfTokensToExchangeForDevelopment = 5 * 10**3 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapEnabledUpdated(bool enabled);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor (address payable developmentWalletAddress, address payable marketingWalletAddress) public {
_developmentWalletAddress = developmentWalletAddress;
_marketingWalletAddress = marketingWalletAddress;
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_developmentWalletAddress] = true;
_isExcludedFromFee[_marketingWalletAddress] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function setExcludeFromFee(address account, bool excluded) external onlyOwner() {
_isExcludedFromFee[account] = excluded;
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
} else {
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function removeAllFee() private {
if(_taxFee == 0 && _developmentFee == 0) return;
_previousTaxFee = _taxFee;
_previousDevelopmentFee = _developmentFee;
_taxFee = 0;
_developmentFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_developmentFee = _previousDevelopmentFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForDevelopment;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToDevelopment(address(this).balance);
}
}
bool takeFee = true;
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
_tokenTransfer(sender,recipient,amount,takeFee);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForDevelopment;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToDevelopment(address(this).balance);
}
}
bool takeFee = true;
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
_tokenTransfer(sender,recipient,amount,takeFee);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForDevelopment;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToDevelopment(address(this).balance);
}
}
bool takeFee = true;
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
_tokenTransfer(sender,recipient,amount,takeFee);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForDevelopment;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToDevelopment(address(this).balance);
}
}
bool takeFee = true;
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
_tokenTransfer(sender,recipient,amount,takeFee);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForDevelopment;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToDevelopment(address(this).balance);
}
}
bool takeFee = true;
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
_tokenTransfer(sender,recipient,amount,takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToDevelopment(uint256 amount) private {
_developmentWalletAddress.transfer(amount.mul(2).div(6));
_marketingWalletAddress.transfer(amount.mul(2).div(6));
}
function manualSwap() external onlyOwner() {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualSend() external onlyOwner() {
uint256 contractETHBalance = address(this).balance;
sendETHToDevelopment(contractETHBalance);
}
function setSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
_transferToExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
_transferBothExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
_transferToExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
_transferBothExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
} else {
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tDevelopment) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeDevelopment(tDevelopment);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tDevelopment) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeDevelopment(tDevelopment);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tDevelopment) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeDevelopment(tDevelopment);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tDevelopment) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeDevelopment(tDevelopment);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeDevelopment(uint256 tDevelopment) private {
uint256 currentRate = _getRate();
uint256 rDevelopment = tDevelopment.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rDevelopment);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tDevelopment);
}
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 tDevelopment) = _getTValues(tAmount, _taxFee, _developmentFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tDevelopment);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 developmentFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tDevelopment = tAmount.mul(developmentFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tDevelopment);
return (tTransferAmount, tFee, tDevelopment);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getTaxFee() private view returns(uint256) {
return _taxFee;
}
function _getMaxTxAmount() private view returns(uint256) {
return _maxTxAmount;
}
function _getETHBalance() public view returns(uint256 balance) {
return address(this).balance;
}
function _setTaxFee(uint256 taxFee) external onlyOwner() {
require(taxFee >= 0 && taxFee <= 25, 'taxFee should be in 0 - 25');
_taxFee = taxFee;
}
function _setDevelopmentFee(uint256 developmentFee) external onlyOwner() {
require(developmentFee >= 1 && developmentFee <= 25, 'developmentFee should be in 1 - 25');
_developmentFee = developmentFee;
}
function _setDevelopmentWallet(address payable developmentWalletAddress) external onlyOwner() {
_developmentWalletAddress = developmentWalletAddress;
}
function _setMarketingWallet(address payable marketingWalletAddress) external onlyOwner() {
_marketingWalletAddress = marketingWalletAddress;
}
function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
_maxTxAmount = maxTxAmount;
}
} | 8,391,732 | [
1,
4625,
348,
7953,
560,
30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,
565,
6835,
670,
297,
30678,
928,
267,
82,
353,
1772,
16,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
3639,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
3639,
1450,
5267,
364,
1758,
31,
203,
203,
3639,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
86,
5460,
329,
31,
203,
3639,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
88,
5460,
329,
31,
203,
3639,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
3639,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
1265,
14667,
31,
203,
203,
3639,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
31,
203,
3639,
1758,
8526,
3238,
389,
24602,
31,
203,
377,
203,
3639,
2254,
5034,
3238,
5381,
4552,
273,
4871,
11890,
5034,
12,
20,
1769,
203,
3639,
2254,
5034,
3238,
389,
88,
5269,
273,
15088,
9449,
380,
1728,
636,
29,
31,
203,
3639,
2254,
5034,
3238,
389,
86,
5269,
273,
261,
6694,
300,
261,
6694,
738,
389,
88,
5269,
10019,
203,
3639,
2254,
5034,
3238,
389,
88,
14667,
5269,
31,
203,
203,
3639,
533,
3238,
389,
529,
273,
296,
44,
297,
30678,
928,
267,
82,
13506,
203,
3639,
533,
3238,
389,
7175,
273,
296,
44,
297,
30678,
928,
267,
82,
13506,
203,
3639,
2254,
28,
3238,
389,
31734,
273,
2468,
31,
203,
540,
203,
3639,
2254,
5034,
3238,
389,
8066,
14667,
273,
404,
31,
7010,
3639,
2254,
5034,
3238,
389,
26630,
14667,
273,
1728,
31,
203,
3639,
2254,
5034,
3238,
389,
11515,
7731,
14667,
273,
389,
8066,
14667,
31,
203,
3639,
2254,
5034,
3238,
389,
11515,
26438,
14667,
273,
389,
26630,
14667,
31,
203,
203,
3639,
1758,
8843,
429,
1071,
389,
26630,
16936,
1887,
31,
203,
3639,
1758,
8843,
429,
1071,
389,
3355,
21747,
16936,
1887,
31,
203,
540,
203,
540,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
11732,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
3639,
1758,
1071,
11732,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
203,
3639,
1426,
316,
12521,
273,
629,
31,
203,
3639,
1426,
1071,
7720,
1526,
273,
638,
31,
203,
203,
3639,
2254,
5034,
3238,
389,
1896,
4188,
6275,
273,
4711,
2787,
11706,
73,
29,
31,
203,
3639,
2254,
5034,
3238,
389,
2107,
951,
5157,
774,
11688,
1290,
26438,
273,
1381,
380,
1728,
636,
23,
380,
1728,
636,
29,
31,
203,
203,
3639,
871,
5444,
5157,
4649,
12521,
7381,
12,
11890,
5034,
1131,
5157,
4649,
12521,
1769,
203,
3639,
871,
12738,
1526,
7381,
12,
6430,
3696,
1769,
203,
203,
3639,
9606,
2176,
1986,
12521,
288,
203,
5411,
316,
12521,
273,
638,
31,
203,
5411,
389,
31,
203,
5411,
316,
12521,
273,
629,
31,
203,
3639,
289,
203,
203,
3639,
3885,
261,
2867,
8843,
429,
17772,
16936,
1887,
16,
1758,
8843,
429,
13667,
310,
16936,
1887,
13,
1071,
288,
203,
5411,
389,
26630,
16936,
1887,
273,
17772,
16936,
1887,
31,
203,
5411,
389,
3355,
21747,
16936,
1887,
273,
13667,
310,
16936,
1887,
31,
203,
5411,
389,
86,
5460,
329,
63,
67,
3576,
12021,
1435,
65,
273,
389,
86,
5269,
31,
203,
203,
5411,
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,
20,
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,
1769,
7010,
5411,
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,
7734,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
203,
2398,
203,
5411,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
203,
2398,
203,
5411,
389,
291,
16461,
1265,
14667,
63,
8443,
1435,
65,
273,
638,
31,
203,
5411,
389,
291,
16461,
1265,
14667,
63,
2867,
12,
2211,
25887,
273,
638,
31,
203,
5411,
389,
291,
16461,
1265,
14667,
63,
67,
26630,
16936,
1887,
65,
273,
638,
31,
203,
5411,
389,
291,
16461,
1265,
14667,
63,
67,
3355,
21747,
16936,
1887,
65,
273,
638,
31,
203,
203,
5411,
3626,
12279,
12,
2867,
12,
20,
3631,
389,
3576,
12021,
9334,
389,
88,
5269,
1769,
203,
3639,
289,
203,
203,
3639,
445,
508,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
5411,
327,
389,
529,
31,
203,
3639,
289,
203,
203,
3639,
445,
3273,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
5411,
327,
389,
7175,
31,
203,
3639,
289,
203,
203,
3639,
445,
15105,
1435,
1071,
1476,
1135,
261,
11890,
28,
13,
288,
203,
5411,
327,
389,
31734,
31,
203,
3639,
289,
203,
203,
3639,
445,
2078,
3088,
1283,
1435,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
5411,
327,
389,
88,
5269,
31,
203,
3639,
289,
203,
203,
3639,
445,
11013,
951,
12,
2867,
2236,
13,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
5411,
309,
261,
67,
291,
16461,
63,
4631,
5717,
327,
389,
88,
5460,
329,
63,
4631,
15533,
203,
5411,
327,
1147,
1265,
9801,
24899,
86,
5460,
329,
63,
4631,
19226,
203,
3639,
289,
203,
203,
3639,
445,
7412,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
1071,
3849,
1135,
261,
6430,
13,
288,
203,
5411,
389,
13866,
24899,
3576,
12021,
9334,
8027,
16,
3844,
1769,
203,
5411,
327,
638,
31,
203,
3639,
289,
203,
203,
3639,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
5411,
327,
389,
5965,
6872,
63,
8443,
6362,
87,
1302,
264,
15533,
203,
3639,
289,
203,
203,
3639,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
3844,
13,
1071,
3849,
1135,
261,
6430,
13,
288,
203,
5411,
389,
12908,
537,
24899,
3576,
12021,
9334,
17571,
264,
16,
3844,
1769,
203,
5411,
327,
638,
31,
203,
3639,
289,
203,
203,
3639,
445,
7412,
1265,
12,
2867,
5793,
16,
2
] |
pragma solidity 0.5.3;
// File: /private/var/folders/2q/x2n3s2rx0d16552ynj1lx90r0000gn/T/tmp.ODkPvI0P/gluon-plasma/packages/on-chain/contracts/Stoppable.sol
/* using a master switch, allowing to permanently turn-off functionality */
contract Stoppable {
/************************************ abstract **********************************/
modifier onlyOwner { _; }
/********************************************************************************/
bool public isOn = true;
modifier whenOn() { require(isOn, "must be on"); _; }
modifier whenOff() { require(!isOn, "must be off"); _; }
function switchOff() external onlyOwner {
if (isOn) {
isOn = false;
emit Off();
}
}
event Off();
}
// File: /private/var/folders/2q/x2n3s2rx0d16552ynj1lx90r0000gn/T/tmp.ODkPvI0P/gluon-plasma/packages/on-chain/contracts/Switchable.sol
/* using a master switch, allowing to switch functionality on/off */
contract Switchable is Stoppable {
function switchOn() external onlyOwner {
if (!isOn) {
isOn = true;
emit On();
}
}
event On();
}
// File: /private/var/folders/2q/x2n3s2rx0d16552ynj1lx90r0000gn/T/tmp.ODkPvI0P/gluon-plasma/packages/on-chain/contracts/Validating.sol
contract Validating {
modifier notZero(uint number) { require(number != 0, "invalid 0 value"); _; }
modifier notEmpty(string memory text) { require(bytes(text).length != 0, "invalid empty string"); _; }
modifier validAddress(address value) { require(value != address(0x0), "invalid address"); _; }
}
// File: /private/var/folders/2q/x2n3s2rx0d16552ynj1lx90r0000gn/T/tmp.ODkPvI0P/gluon-plasma/packages/on-chain/contracts/HasOwners.sol
contract HasOwners is Validating {
mapping(address => bool) public isOwner;
address[] private owners;
constructor(address[] memory _owners) public {
for (uint i = 0; i < _owners.length; i++) _addOwner_(_owners[i]);
owners = _owners;
}
modifier onlyOwner { require(isOwner[msg.sender], "invalid sender; must be owner"); _; }
function getOwners() public view returns (address[] memory) { return owners; }
function addOwner(address owner) external onlyOwner { _addOwner_(owner); }
function _addOwner_(address owner) private validAddress(owner) {
if (!isOwner[owner]) {
isOwner[owner] = true;
owners.push(owner);
emit OwnerAdded(owner);
}
}
event OwnerAdded(address indexed owner);
function removeOwner(address owner) external onlyOwner {
if (isOwner[owner]) {
require(owners.length > 1, "removing the last owner is not allowed");
isOwner[owner] = false;
for (uint i = 0; i < owners.length - 1; i++) {
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1]; // replace map last entry
delete owners[owners.length - 1];
break;
}
}
owners.length -= 1;
emit OwnerRemoved(owner);
}
}
event OwnerRemoved(address indexed owner);
}
// File: /private/var/folders/2q/x2n3s2rx0d16552ynj1lx90r0000gn/T/tmp.ODkPvI0P/gluon-plasma/packages/on-chain/contracts/registry/Registry.sol
interface Registry {
function contains(address apiKey) external view returns (bool);
function register(address apiKey) external;
function registerWithUserAgreement(address apiKey, bytes32 userAgreement) external;
function translate(address apiKey) external view returns (address);
}
// File: contracts/registry/ApiKeyRegistry.sol
contract ApiKeyRegistry is Switchable, HasOwners, Registry {
string public version;
/* mapping of: address of api-key used in trading => address of account map funds used in settling */
mapping (address => address) public accounts;
mapping (address => bytes32) public userAgreements;
constructor(address[] memory _owners, string memory _version) HasOwners(_owners) public {
version = _version;
}
modifier isAbsent(address apiKey) { require(!contains(apiKey), "api key already in use"); _; }
function contains(address apiKey) public view returns (bool) { return accounts[apiKey] != address(0x0); }
function register(address apiKey) external { registerWithUserAgreement(apiKey, 0); }
function registerWithUserAgreement(address apiKey, bytes32 userAgreement) public validAddress(apiKey) isAbsent(apiKey) whenOn {
accounts[apiKey] = msg.sender;
if (userAgreement != 0 && userAgreements[msg.sender] == 0) {
userAgreements[msg.sender] = userAgreement;
}
emit Registered(apiKey, msg.sender, userAgreements[msg.sender]);
}
event Registered(address apiKey, address indexed account, bytes32 userAgreement);
function translate(address apiKey) external view returns (address) { return accounts[apiKey]; }
} | *********************************** abstract **********************************/ | modifier onlyOwner { _; }
| 885,030 | [
1,
4625,
348,
7953,
560,
30,
20210,
636,
8770,
20210,
5549,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
9606,
1338,
5541,
288,
389,
31,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
/**
* @dev this is just a dummy mintable/burnable ERC20 for testing purposes
*/
contract Basic721 is ERC721, Ownable {
constructor(string memory name, string memory symbol)
ERC721(name, symbol)
Ownable()
{ }
string baseURI;
function mint(address account, uint256 id) public {
_mint(account, id);
}
function burn(uint256 id) public onlyOwner {
_burn(id);
}
/**
* @dev Base URI for computing {tokenURI}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function setBaseURI(string memory baseURI_) public onlyOwner {
baseURI = baseURI_;
}
} | * @dev this is just a dummy mintable/burnable ERC20 for testing purposes/ | contract Basic721 is ERC721, Ownable {
constructor(string memory name, string memory symbol)
ERC721(name, symbol)
Ownable()
string baseURI;
pragma solidity ^0.8.0;
{ }
function mint(address account, uint256 id) public {
_mint(account, id);
}
function burn(uint256 id) public onlyOwner {
_burn(id);
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function setBaseURI(string memory baseURI_) public onlyOwner {
baseURI = baseURI_;
}
} | 13,016,389 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
5206,
333,
353,
2537,
279,
9609,
312,
474,
429,
19,
70,
321,
429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
377,
203,
565,
3885,
12,
1080,
3778,
508,
16,
533,
3778,
3273,
13,
203,
3639,
4232,
39,
27,
5340,
12,
529,
16,
3273,
13,
203,
3639,
14223,
6914,
1435,
203,
203,
565,
533,
1026,
3098,
31,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
565,
288,
289,
203,
565,
445,
312,
474,
12,
2867,
2236,
16,
2254,
5034,
612,
13,
1071,
288,
203,
3639,
389,
81,
474,
12,
4631,
16,
612,
1769,
203,
565,
289,
203,
203,
565,
445,
18305,
12,
11890,
5034,
612,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
70,
321,
12,
350,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
1969,
3098,
1435,
2713,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
1026,
3098,
31,
203,
565,
289,
203,
203,
565,
445,
26435,
3098,
12,
1080,
3778,
1026,
3098,
67,
13,
1071,
1338,
5541,
288,
203,
3639,
1026,
3098,
273,
1026,
3098,
67,
31,
203,
565,
289,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract OwnerContract {
address owner = msg.sender;
string private ownerName;
constructor(string memory _ownerName) {
ownerName = _ownerName;
}
function getOwner() public view virtual returns(string memory){
return ownerName;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
interface MoneyBoxInterface {
function deposit(uint amount) external returns (uint);
function retire(uint amount) external returns (uint);
}
contract MoneyBox is OwnerContract, MoneyBoxInterface {
uint money;
//Pass parameters to super constructors
constructor(string memory _ownerName) OwnerContract(_ownerName) {}
//Call to an already existing function
function getOwner() public view override returns(string memory){
return super.getOwner();
}
//Implements the interface and inherited modifier
function deposit(uint value) public override onlyOwner returns (uint){
money += value;
return money;
}
function retire(uint amount) external returns (uint){
require(money >= amount, "You dont have enough money");
money -= amount;
return money;
}
} | Implements the interface and inherited modifier | function deposit(uint value) public override onlyOwner returns (uint){
money += value;
return money;
}
| 13,012,478 | [
1,
4625,
348,
7953,
560,
30,
29704,
326,
1560,
471,
12078,
9606,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
443,
1724,
12,
11890,
460,
13,
1071,
3849,
1338,
5541,
1135,
261,
11890,
15329,
203,
565,
15601,
1011,
460,
31,
203,
565,
327,
15601,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
abstract contract ContextMixin {
function msgSender()
internal
view
returns (address payable sender)
{
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = payable(msg.sender);
}
return sender;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./common/meta-transactions/ContentMixin.sol";
import "./common/meta-transactions/NativeMetaTransaction.sol";
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
* @title Yokai Masks Ethereum NFT Contract for https://yokai.money
* @dev Extends ERC721 Non-Fungible Token Standard
*/
contract YokaiMasksEthereum is ContextMixin, ERC721, ERC721Enumerable, ERC721URIStorage, NativeMetaTransaction, Ownable {
using SafeMath for uint256;
using Address for address;
// This is the provenance record of all Yokai masks in existence
string public yokaiMasksProvenance;
// This is the SHA-256 hash signature of the random distribution of Yokai masks
// that can be verified after all masks are sold with the file at https://yokai.money/mask-distribution.json
string public constant YOKAI_MASKS_DISTRIBUTION =
"5182000dbf7c507d1da97a3a4ea85df8430fa4ef43355e379dd5ab4dbd25b2df";
// Base metadata URI
string public baseURI = "https://d3cm9551gyae1g.cloudfront.net/";
// Max supply of all masks
uint256 public constant MAX_MASK_SUPPLY = 3001;
// Dev address
address public devAddr;
// Address of the mask marketplace contract
address public marketplaceAddress;
// Address of the Ethereum bridge contract
address public bridgeContract;
// OpenSea proxy registry address
address proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1;
/**
* @dev Contract constructor
*/
constructor() ERC721("Yokai Masks", "YM") {
devAddr = msg.sender;
_initializeEIP712("Yokai Masks");
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function tokenURI(uint256 _tokenId) override(ERC721, ERC721URIStorage) public view returns (string memory) {
return string(abi.encodePacked(baseURI, Strings.toString(_tokenId)));
}
/**
* @dev Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* @dev 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 sender)
{
return ContextMixin.msgSender();
}
/**
* @dev Returns a URL for the Opensea storefront-level metadata of the contract.
*/
function contractURI() public view returns (string memory) {
return string(abi.encodePacked(baseURI, "contract.json"));
}
/**
* @dev Mints masks for the BSC bridge
*/
function mintMaskFromBridge(address _to, uint256 _mintIndex) external {
require(totalSupply() < MAX_MASK_SUPPLY, "Sale over");
require(totalSupply().add(1) <= MAX_MASK_SUPPLY, "Over supply");
require(msg.sender == bridgeContract, "Not bridge");
_safeMint(_to, _mintIndex);
}
/**
* @dev Returns whether `tokenId` exists.
*/
function tokenExists(uint256 _tokenId) external view returns (bool) {
return _exists(_tokenId);
}
/**
* @dev Withdraw ETH from this contract (callable by owner only)
*/
function withdrawDevFunds() public onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
/**
* @dev Update dev address by the previous dev
*/
function setDev(address payable _devAddr) external onlyOwner {
devAddr = _devAddr;
}
/**
* @dev Set the bridge contract address
*/
function setBridgeContract(address _address) external onlyOwner {
bridgeContract = _address;
}
/**
* @dev Set the Yokai masks provenance record
*/
function setYokaiProvenance(string memory _provenance) external onlyOwner {
yokaiMasksProvenance = _provenance;
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`.
*/
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
/**
* @dev Sets the baseURI
*/
function setBaseURI(string memory _yokaiBaseURI) external onlyOwner {
baseURI = _yokaiBaseURI;
}
/**
* @dev Sets the marketplace contract address
*/
function setMarketplaceAddress(address _marketplaceAddress) external onlyOwner {
marketplaceAddress = _marketplaceAddress;
}
/**
* @dev NFT transfer for the mask marketplace
*/
function safeMaskTransferFrom(address _from, address _to, uint256 _tokenId) external {
require(msg.sender == marketplaceAddress, "Caller not marketplace");
safeTransferFrom(_from, _to, _tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: 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));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @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 override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {EIP712Base} from "./EIP712Base.sol";
contract NativeMetaTransaction is EIP712Base {
using SafeMath for uint256;
bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256(
bytes(
"MetaTransaction(uint256 nonce,address from,bytes functionSignature)"
)
);
event MetaTransactionExecuted(
address userAddress,
address payable relayerAddress,
bytes functionSignature
);
mapping(address => uint256) nonces;
/*
* Meta transaction structure.
* No point of including value field here as if user is doing value transfer then he has the funds to pay for gas
* He should call the desired function directly in that case.
*/
struct MetaTransaction {
uint256 nonce;
address from;
bytes functionSignature;
}
function executeMetaTransaction(
address userAddress,
bytes memory functionSignature,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) public payable returns (bytes memory) {
MetaTransaction memory metaTx = MetaTransaction({
nonce: nonces[userAddress],
from: userAddress,
functionSignature: functionSignature
});
require(
verify(userAddress, metaTx, sigR, sigS, sigV),
"Signer and signature do not match"
);
// increase nonce for user (to avoid re-use)
nonces[userAddress] = nonces[userAddress].add(1);
emit MetaTransactionExecuted(
userAddress,
payable(msg.sender),
functionSignature
);
// Append userAddress and relayer address at the end to extract it from calling context
(bool success, bytes memory returnData) = address(this).call(
abi.encodePacked(functionSignature, userAddress)
);
require(success, "Function call not successful");
return returnData;
}
function hashMetaTransaction(MetaTransaction memory metaTx)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
META_TRANSACTION_TYPEHASH,
metaTx.nonce,
metaTx.from,
keccak256(metaTx.functionSignature)
)
);
}
function getNonce(address user) public view returns (uint256 nonce) {
nonce = nonces[user];
}
function verify(
address signer,
MetaTransaction memory metaTx,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) internal view returns (bool) {
require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER");
return
signer ==
ecrecover(
toTypedMessageHash(hashMetaTransaction(metaTx)),
sigV,
sigR,
sigS
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Initializable} from "./Initializable.sol";
contract EIP712Base is Initializable {
struct EIP712Domain {
string name;
string version;
address verifyingContract;
bytes32 salt;
}
string constant public ERC712_VERSION = "1";
bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256(
bytes(
"EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)"
)
);
bytes32 internal domainSeperator;
// supposed to be called once while initializing.
// one of the contracts that inherits this contract follows proxy pattern
// so it is not possible to do this in a constructor
function _initializeEIP712(
string memory name
)
internal
initializer
{
_setDomainSeperator(name);
}
function _setDomainSeperator(string memory name) internal {
domainSeperator = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(name)),
keccak256(bytes(ERC712_VERSION)),
address(this),
bytes32(getChainId())
)
);
}
function getDomainSeperator() public view returns (bytes32) {
return domainSeperator;
}
function getChainId() public view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* Accept message hash and returns hash message in EIP712 compatible form
* So that it can be used to recover signer from signature signed using EIP712 formatted data
* https://eips.ethereum.org/EIPS/eip-712
* "\\x19" makes the encoding deterministic
* "\\x01" is the version byte to make it compatible to EIP-191
*/
function toTypedMessageHash(bytes32 messageHash)
internal
view
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Initializable {
bool inited = false;
modifier initializer() {
require(!inited, "already inited");
_;
inited = true;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
interface IYokaiMasks {
function mintMaskFromBridge(address _to, uint256 _mintIndex) external;
function ownerOf(uint256 tokenId) external returns (address);
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
function tokenExists(uint256 _tokenId) external view returns (bool);
}
contract YokaiMasksEthereumBridge is IERC721Receiver, Ownable {
// Signer address
address public signerAddress;
// Address of the Yokai Masks Ethereum contract
address public yokaiMasksContract;
// Nonces for tracking mint transactions
mapping(address => mapping(uint256 => bool)) public processedNonces;
event SentToBridge(
address indexed from,
uint256 indexed mintIndex,
uint256 indexed date,
uint256 nonce,
bytes signature
);
event MaskClaimed(
address indexed to,
uint256 indexed mintIndex,
uint256 indexed date,
uint256 nonce,
bytes signature
);
constructor() {
signerAddress = 0x13cacbc303b5d45164e31E6b6d73c1c445b4BA52;
}
/**
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
function sendMaskToBridge(uint256 _mintIndex, uint256 _nonce, bytes calldata _signature) external {
address from = msg.sender;
bytes32 message = prefixed(keccak256(abi.encodePacked(
from,
_mintIndex,
_nonce
)));
require(recoverSigner(message, _signature) == signerAddress, 'Wrong signature');
require(processedNonces[from][_nonce] == false, 'Transfer already processed');
processedNonces[from][_nonce] = true;
IYokaiMasks(yokaiMasksContract).safeTransferFrom(msg.sender, address(this), _mintIndex);
emit SentToBridge(msg.sender, _mintIndex, block.timestamp, _nonce, _signature);
}
function claimMask(uint256 _mintIndex, uint256 _nonce, bytes calldata _signature) external {
address from = msg.sender;
bytes32 message = prefixed(keccak256(abi.encodePacked(
from,
_mintIndex,
_nonce
)));
require(recoverSigner(message, _signature) == signerAddress, 'Wrong signature');
require(processedNonces[from][_nonce] == false, 'Transfer already processed');
processedNonces[from][_nonce] = true;
if (
IYokaiMasks(yokaiMasksContract).tokenExists(_mintIndex) &&
IYokaiMasks(yokaiMasksContract).ownerOf(_mintIndex) == address(this)
) {
IYokaiMasks(yokaiMasksContract).safeTransferFrom(address(this), msg.sender, _mintIndex);
} else {
IYokaiMasks(yokaiMasksContract).mintMaskFromBridge(msg.sender, _mintIndex);
}
emit MaskClaimed(msg.sender, _mintIndex, block.timestamp, _nonce, _signature);
}
function prefixed(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(
'\x19Ethereum Signed Message:\n32',
hash
));
}
function recoverSigner(bytes32 message, bytes memory sig)
internal
pure
returns (address)
{
uint8 v;
bytes32 r;
bytes32 s;
(v, r, s) = splitSignature(sig);
return ecrecover(message, v, r, s);
}
function splitSignature(bytes memory sig)
internal
pure
returns (uint8, bytes32, bytes32)
{
require(sig.length == 65);
bytes32 r;
bytes32 s;
uint8 v;
assembly {
// first 32 bytes, after the length prefix
r := mload(add(sig, 32))
// second 32 bytes
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
}
return (v, r, s);
}
/**
* @dev Update signer address by the owner
*/
function setSigner(address payable _signerAddress) external onlyOwner {
signerAddress = _signerAddress;
}
/**
* @dev Set the Yokai Masks Ethereum contract address
*/
function setYokaiMasksContract(address _address) external onlyOwner {
yokaiMasksContract = _address;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
interface IYokaiMasks {
function ownerOf(uint256 tokenId) external returns (address);
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
}
contract YokaiMasksBSCBridge is IERC721Receiver, Ownable {
// Signer address
address public signerAddress;
// Address of the Yokai Masks Ethereum contract
address public yokaiMasksContract;
// Nonces for tracking mint transactions
mapping(address => mapping(uint256 => bool)) public processedNonces;
event SentToBridge(
address indexed from,
uint256 indexed mintIndex,
uint256 indexed date,
uint256 nonce,
bytes signature
);
event MaskClaimed(
address indexed to,
uint256 indexed mintIndex,
uint256 indexed date,
uint256 nonce,
bytes signature
);
constructor() {
signerAddress = 0x13cacbc303b5d45164e31E6b6d73c1c445b4BA52;
}
/**
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
function sendMaskToBridge(uint256 _mintIndex, uint256 _nonce, bytes calldata _signature) external {
address from = msg.sender;
bytes32 message = prefixed(keccak256(abi.encodePacked(
from,
_mintIndex,
_nonce
)));
require(recoverSigner(message, _signature) == signerAddress, 'Wrong signature');
require(processedNonces[from][_nonce] == false, 'Transfer already processed');
processedNonces[from][_nonce] = true;
IYokaiMasks(yokaiMasksContract).safeTransferFrom(msg.sender, address(this), _mintIndex);
emit SentToBridge(msg.sender, _mintIndex, block.timestamp, _nonce, _signature);
}
function claimMask(uint256 _mintIndex, uint256 _nonce, bytes calldata _signature) external {
address from = msg.sender;
bytes32 message = prefixed(keccak256(abi.encodePacked(
from,
_mintIndex,
_nonce
)));
require(recoverSigner(message, _signature) == signerAddress, 'Wrong signature');
require(processedNonces[from][_nonce] == false, 'Transfer already processed');
processedNonces[from][_nonce] = true;
if (IYokaiMasks(yokaiMasksContract).ownerOf(_mintIndex) == address(this)) {
IYokaiMasks(yokaiMasksContract).safeTransferFrom(address(this), msg.sender, _mintIndex);
}
emit MaskClaimed(msg.sender, _mintIndex, block.timestamp, _nonce, _signature);
}
function prefixed(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(
'\x19Ethereum Signed Message:\n32',
hash
));
}
function recoverSigner(bytes32 message, bytes memory sig)
internal
pure
returns (address)
{
uint8 v;
bytes32 r;
bytes32 s;
(v, r, s) = splitSignature(sig);
return ecrecover(message, v, r, s);
}
function splitSignature(bytes memory sig)
internal
pure
returns (uint8, bytes32, bytes32)
{
require(sig.length == 65);
bytes32 r;
bytes32 s;
uint8 v;
assembly {
// first 32 bytes, after the length prefix
r := mload(add(sig, 32))
// second 32 bytes
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
}
return (v, r, s);
}
/**
* @dev Update signer address by the owner
*/
function setSigner(address payable _signerAddress) external onlyOwner {
signerAddress = _signerAddress;
}
/**
* @dev Set the Yokai Masks Ethereum contract address
*/
function setYokaiMasksContract(address _address) external onlyOwner {
yokaiMasksContract = _address;
}
}
| * @dev Returns whether `tokenId` exists./ | function tokenExists(uint256 _tokenId) external view returns (bool) {
return _exists(_tokenId);
}
| 1,728,646 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
5206,
2860,
2856,
1375,
2316,
548,
68,
1704,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1147,
4002,
12,
11890,
5034,
389,
2316,
548,
13,
3903,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
389,
1808,
24899,
2316,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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
// @title: MOAR
// @desc: "MOAR by Joan Cornellà is an unusual mansion in the metaverse proudly presented by FWENCLUB, where 5,555 creatures with their souls minted with the ERC721 blockchain as NFTs. Each of these "peacefully-living-together" humans, cyborgs or even zombies, is unique, hand-drawn by Spanish artist Joan Cornellà using over 200 unique attributes. You may even find shops, games, virtual exhibitions … and MOAR!"
// @twitter: https://twitter.com/fwenclub
// @instagram: https://instagram.com/fwenclub
// @discord: https://discord.gg/fwenclub
// @url: https://www.fwenclub.com/
/*
* ███████╗░██╗░░░░░░░██╗███████╗███╗░░██╗░█████╗░██╗░░░░░██╗░░░██╗██████╗░
* ██╔════╝░██║░░██╗░░██║██╔════╝████╗░██║██╔══██╗██║░░░░░██║░░░██║██╔══██╗
* █████╗░░░╚██╗████╗██╔╝█████╗░░██╔██╗██║██║░░╚═╝██║░░░░░██║░░░██║██████╦╝
* ██╔══╝░░░░████╔═████║░██╔══╝░░██║╚████║██║░░██╗██║░░░░░██║░░░██║██╔══██╗
* ██║░░░░░░░╚██╔╝░╚██╔╝░███████╗██║░╚███║╚█████╔╝███████╗╚██████╔╝██████╦╝
* ╚═╝░░░░░░░░╚═╝░░░╚═╝░░╚══════╝╚═╝░░╚══╝░╚════╝░╚══════╝░╚═════╝░╚═════╝░
*/
pragma solidity ^0.8.13;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./MoarBase.sol";
error InvalidSaleOn();
error InvalidTime();
error ContractBidder();
error ExceedMaxSupply();
error ExceedMaxTicket();
error ExceedAuctionSupply();
error ExceedDiamondHandSupply();
error InvalidPayment();
error InvalidSignature();
error WithdrawFailed();
contract Moar is MoarBase, ReentrancyGuard {
// ===== Provenance ======
bytes32 public provenance;
// ================ Public Sales ================
bool public saleOn;
mapping(address => uint256) public publicMints;
// ========= Public Mints =========
struct Tier {
uint256 startTime;
uint256 duration;
uint256 maxTicketNum;
uint256 ticketPrice;
}
mapping(uint256 => Tier) public tiers;
// =============================== Diamond Hand ================================
uint256 public constant DIAMOND_HAND_ID = uint256(keccak256("DIAMOND_HAND_ID"));
// ========================== Dutch Auction ===========================
uint256 public constant DUTCH_AUCTION_MAX_TICKET = 2;
uint256 public constant DUTCH_AUCTION_START_PRICE = 0.5 ether;
uint256 public constant DUTCH_AUCTION_END_PRICE = 0.1 ether;
uint256 public constant DUTCH_AUCTION_PRICE_CURVE_LENGTH = 180 minutes;
uint256 public constant DUTCH_AUCTION_DROP_INTERVAL = 45 minutes;
uint256 public constant DUTCH_AUCTION_DROP_PER_STEP = (DUTCH_AUCTION_START_PRICE - DUTCH_AUCTION_END_PRICE) / (DUTCH_AUCTION_PRICE_CURVE_LENGTH / DUTCH_AUCTION_DROP_INTERVAL);
uint256 public dutchAuctionStartTime = 1649335500; // Apr 7, 2022, 2045 HKT
// ==================== Supply ====================
uint256 public constant maxSupply = 5555;
uint256 public totalSupply;
uint256 public constant diamondHandMaxSupply = 1644; // 40% of the dutch auction qty
uint256 public constant DHDAMaxSupply = 4110; // 74% of the total qty - 1 (English Auction)
uint256 public DHDATotalSupply;
// ======== Roles =========
address private _authority;
// ========================= Refund ==========================
event refundFailed(address indexed recipient, uint256 amount);
/**
* @dev Constructor function. Mints token #1 to `owner`, updates `totalSupply`
* @param authority signature authority
* @param admin admin role
* @param royaltyAddress royalty fee receiver address
*/
constructor(address authority, address admin, address royaltyAddress) MoarBase(admin, royaltyAddress) {
_authority = authority;
_mint(owner(), 1);
totalSupply += 1;
}
/**
* @dev Validates `saleOn`
*/
modifier isSaleOn(bool saleOn_) {
if (saleOn != saleOn_) { revert InvalidSaleOn(); }
_;
}
/**
* @dev Validates time for tier
* @param tierId Id of tier to validate
*/
modifier validTime(uint256 tierId) {
uint256 startTime = tiers[tierId].startTime;
uint256 endTime = startTime + tiers[tierId].duration * 1 seconds;
if (block.timestamp < startTime || block.timestamp >= endTime) { revert InvalidTime(); }
_;
}
/**
* @dev Validates if caller is a contract
*/
modifier validateCaller() {
if (tx.origin != msg.sender) { revert ContractBidder(); }
_;
}
/**
* @dev Sets the provenance.
* @param provenance_ provenance of public mint token images
*
* Requirements:
*
* - the caller must be `owner`.
*/
function setProvenance(bytes32 provenance_) external onlyAdmin {
provenance = provenance_;
}
/**
* @dev Toggles `saleOn`
*
* Requirements:
*
* - the caller must be `owner`.
*/
function toggleFlag(uint256 flag) public override onlyAdmin {
if (flag == uint256(keccak256("SALE")))
saleOn = !saleOn;
else
super.toggleFlag(flag);
}
/**
* @dev Sets `_authority` address
* @param authority new authority address to set
*
* Requirements:
*
* - `saleOn` must be false,
* - the caller must be `owner`.
*/
function setAuthority( address authority) external isSaleOn(false) onlyOwner {
_authority = authority;
}
/**
* @dev Sets dutch auction start time
* @param startTime start time to be set
*
* Requirements:
*
* - `saleOn` must be false,
* - the caller must be `owner`.
*/
function setDutchAuctionStartTime( uint256 startTime) external isSaleOn(false) onlyAdmin {
dutchAuctionStartTime = startTime;
}
/**
* @dev Configs sales
* @param tierIds ids of sale tiers
* @param tierStartTimes start times of sale tiers
* @param tierDurations durations of sale tiers
* @param tierMaxTicketNums max ticket numbers per user of sale tiers
* @param tierTicketPrices ticket prices of sale tiers
*
* Requirements:
*
* - the caller must be `_admin`.
*/
function configSales(
uint256[] memory tierIds,
uint256[] memory tierStartTimes,
uint256[] memory tierDurations,
uint256[] memory tierMaxTicketNums,
uint256[] memory tierTicketPrices
) external onlyAdmin isSaleOn(false) {
if (
tierIds.length != tierStartTimes.length ||
tierIds.length != tierDurations.length ||
tierIds.length != tierMaxTicketNums.length ||
tierIds.length != tierTicketPrices.length
) {
revert ArrayLengthMismatch();
}
for (uint256 i = 0; i < tierIds.length; i++) {
tiers[tierIds[i]].startTime = tierStartTimes[i];
tiers[tierIds[i]].duration = tierDurations[i];
tiers[tierIds[i]].maxTicketNum = tierMaxTicketNums[i];
tiers[tierIds[i]].ticketPrice = tierTicketPrices[i];
}
}
/**
* @dev Creates a new token for every address in `tos`. TokenIds will be automatically assigned
* @param tos owners of new tokens
*
* Requirements:
*
* - `saleOn` must be false,
* - the caller must be `_admin`.
*/
function privateMint(address[] memory tos) external onlyAdmin isSaleOn(false) {
for (uint256 i = 0; i < tos.length; i++) {
_mint(tos[i], totalSupply + 1 + i);
}
totalSupply += tos.length;
if (totalSupply > maxSupply) { revert ExceedMaxSupply(); }
}
/**
* @dev Creates new tokens for public mint. TokenIds will be automatically assigned
*
* @param maxNum max ticket number per user
* @param ticketNum number of tokens to create
* @param price price of each token
*/
function _publicMint(uint256 maxNum, uint256 ticketNum, uint256 price, bool lock) private {
// all public sales share same counter mapping, contract trusts that all signature addresses are unique
if (publicMints[msg.sender] + ticketNum > maxNum) { revert ExceedMaxTicket(); }
uint256 availableNum = Math.min(ticketNum, maxSupply - totalSupply );
if (availableNum <= 0) { revert ExceedMaxSupply(); }
publicMints[msg.sender] += availableNum;
uint256 totalPrice = price * availableNum;
if (msg.value < totalPrice) { revert InvalidPayment(); }
if (availableNum > 1) {
for (uint256 i = 0; i < availableNum; i++) {
uint256 tokenId = totalSupply + 1 + i;
_mint(msg.sender, tokenId);
if (lock) transferLocks[tokenId] = LockStatus.LockByAdmin;
}
} else {
uint256 tokenId = totalSupply + 1;
_mint(msg.sender, tokenId);
if (lock) transferLocks[tokenId] = LockStatus.LockByAdmin;
}
totalSupply += availableNum;
if (totalSupply > maxSupply) { revert ExceedMaxSupply(); }
if (msg.value > totalPrice) {
uint256 refundAmount = msg.value - totalPrice;
(bool refund, ) = msg.sender.call{value: refundAmount}("");
if (!refund) {
emit refundFailed(msg.sender, refundAmount);
}
}
}
/**
* @dev Creates new token(s) for valid caller. TokenId(s) will be automatically assigned
*
* @param tierId tier id of caller belonged to
* @param ticketNum number of tokens to create
* @param signature signature from `_authority`
*
* Requirements:
*
* - `saleOn` must be true,
*/
function whitelistMint(uint256 tierId, uint256 ticketNum, bytes memory signature) external payable isSaleOn(true) validTime(tierId) {
bytes32 data = keccak256(abi.encode(address(this), msg.sender, tierId));
if (!SignatureChecker.isValidSignatureNow(_authority, data, signature)) { revert InvalidSignature(); }
_publicMint(tiers[tierId].maxTicketNum, ticketNum, tiers[tierId].ticketPrice, false);
}
/**
* @dev Creates new tokens for auction winner. TokenIds will be automatically assigned
* @param ticketNum number of tokens to create
* @param signature signature from `_authority`
*
* Requirements:
*
* - `saleOn` must be true,
* - caller must not be a contract.
*/
function dutchAuctionMint(uint256 ticketNum, bytes memory signature) external payable isSaleOn(true) validateCaller {
if (block.timestamp < dutchAuctionStartTime) { revert InvalidTime(); }
bytes32 data = keccak256(abi.encode(address(this), msg.sender, keccak256("DUTCH")));
if (!SignatureChecker.isValidSignatureNow(_authority, data, signature)) { revert InvalidSignature(); }
uint256 availableNum = Math.min(ticketNum, DHDAMaxSupply - DHDATotalSupply );
if (availableNum <= 0) { revert ExceedAuctionSupply(); }
DHDATotalSupply += availableNum;
_publicMint(DUTCH_AUCTION_MAX_TICKET, availableNum, dutchAuctionPrice(), false);
}
/**
* @dev Returns auction token price
*/
function dutchAuctionPrice() public view returns (uint256){
uint256 timestamp = block.timestamp;
if (timestamp < dutchAuctionStartTime)
return DUTCH_AUCTION_START_PRICE;
if (timestamp - dutchAuctionStartTime >= DUTCH_AUCTION_PRICE_CURVE_LENGTH)
return DUTCH_AUCTION_END_PRICE;
uint256 steps = (timestamp - dutchAuctionStartTime) / DUTCH_AUCTION_DROP_INTERVAL;
return DUTCH_AUCTION_START_PRICE - steps * DUTCH_AUCTION_DROP_PER_STEP;
}
/**
* @dev Creates new tokens for auction winner. TokenIds will be automatically assigned
* @param ticketNum number of tokens to create
* @param signature signature from `_authority`
*
* Requirements:
*
* - `saleOn` must be true,
* - caller must not be a contract.
*/
function diamondHandMint(uint256 ticketNum, bytes memory signature) external payable isSaleOn(true) validateCaller validTime(DIAMOND_HAND_ID) {
bytes32 data = keccak256(abi.encode(address(this), msg.sender, DIAMOND_HAND_ID));
if (!SignatureChecker.isValidSignatureNow(_authority, data, signature)) { revert InvalidSignature(); }
uint256 availableNum = Math.min(ticketNum, diamondHandMaxSupply - DHDATotalSupply );
if (availableNum <= 0) { revert ExceedDiamondHandSupply(); }
DHDATotalSupply += availableNum;
_publicMint(DUTCH_AUCTION_MAX_TICKET, availableNum, tiers[DIAMOND_HAND_ID].ticketPrice, true);
}
/**
* @dev Payouts contract balance
*
* Requirements:
*
* - the caller must be `owner`.
*/
function withdraw() external onlyOwner nonReentrant {
(bool success, ) = msg.sender.call{value: address(this).balance}("");
if (!success) { revert WithdrawFailed(); }
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
import "../erc/ERC721.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
error NonAdmin();
error MetadataFrozen();
error BurnningInactive();
error TransferDeactive();
error TransferLocked();
error TransferLockedByAdmin();
error RoyaltyPercentageExceed();
error ArrayLengthMismatch();
contract MoarBase is ERC721, IERC2981, Ownable {
using Strings for uint256;
// ==== Admin Role ====
address private _admin;
// ======= Metadata =======
bool public metadataFrozen;
string private _baseURI;
// ======= Burning =======
bool public burningActive;
// ================================= Transfer ==================================
enum LockStatus {
Unlock,
LockByAdmin,
LockByTokenOwner
}
bool public transferDeactive;
mapping ( uint256 => LockStatus ) public transferLocks;
event LockTransfer(address indexed owner, uint256 indexed tokenId, bool locked);
// ======== Royalties ==========
address private _royaltyAddress;
uint256 private _royaltyPercent;
/**
* @dev Initializes the contract by setting a `default_admin` of the token access control.
*/
constructor(address admin, address royaltyAddress ) {
_admin = admin;
_royaltyAddress = royaltyAddress;
_royaltyPercent = 6;
}
/**
* @dev Throws if called by any account other than the `_admin`.
*/
modifier onlyAdmin() {
if (_admin != _msgSender()) { revert NonAdmin(); }
_;
}
/**
* @dev Sets `_admin` address
* @param admin new admin address to set
*
* Requirements:
*
* - `saleOn` must be false,
* - the caller must be `owner`.
*/
function setAdmin( address admin) external onlyOwner {
_admin = admin;
}
/**
* @dev Returns the token collection name.
*/
function name() public view virtual override returns (string memory) {
return "MOAR by Joan Cornella";
}
/**
* @dev Returns the token collection symbol
*/
function symbol() public view virtual override returns (string memory) {
return "MOAR";
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, IERC165) returns (bool) {
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Sets base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`.
* @param baseURI base URI to set
*
* Requirements:
*
* - the caller must be owner.
*/
function setBaseURI(string memory baseURI) external onlyOwner {
if (metadataFrozen) { revert MetadataFrozen(); }
_baseURI = baseURI;
}
/**
* @dev Returns the URI for a given token ID
* Throws if the token ID does not exist.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
if (!_exists(tokenId)) { revert NonExistentToken(); }
if (bytes(_baseURI).length > 0)
return string(abi.encodePacked(_baseURI, tokenId.toString()));
return string(abi.encodePacked("https://metadata.thefwenclub.com/moar/", tokenId.toString()));
}
/**
* @dev Toggles `burningActive`, `transferActive` and `metadataFrozen`
*
* Requirements:
*
* - the caller must be `owner`.
*/
function toggleFlag(uint256 flag) public virtual onlyOwner {
if (flag == uint256(keccak256("BURN")))
burningActive = !burningActive;
else if (flag == uint256(keccak256("TRANSFER")))
transferDeactive = !transferDeactive;
else if (flag == uint256(keccak256("METADATA")))
metadataFrozen = true;
}
/**
* @dev Destroys `tokenId`.
* Throws if the caller is not token owner or approved
* @param tokenId uint256 ID of the token to be destroyed
*/
function burn(uint256 tokenId) external {
if (!burningActive) { revert BurnningInactive(); }
if (!_isApprovedOrOwner(_msgSender(), tokenId)) {revert NonOwnerOrApproved(); }
_burn(tokenId);
}
/**
* @dev Set royalty info for all tokens
* @param royaltyReceiver address to receive royalty fee
* @param royaltyPercentage percentage of royalty fee
*
* Requirements:
*
* - the caller must be the contract owner.
*/
function setRoyaltyInfo(address royaltyReceiver, uint256 royaltyPercentage) public onlyOwner {
if (royaltyPercentage > 100) { revert RoyaltyPercentageExceed(); }
_royaltyAddress = royaltyReceiver;
_royaltyPercent = royaltyPercentage;
}
/**
* @dev See {IERC2981-royaltyInfo}.
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice) external view override returns (address receiver, uint256 royaltyAmount){
if (!_exists(tokenId)) { revert NonExistentToken(); }
return (_royaltyAddress, (salePrice * _royaltyPercent) / 100);
}
/**
* @dev See {ERC721-_transfer}.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual override {
if (transferDeactive) { revert TransferDeactive(); }
if (transferLocks[tokenId] != LockStatus.Unlock) { revert TransferLocked(); }
super._transfer(from, to, tokenId);
}
/**
* Locks the transfer of a particular tokenId. This is designed for a non-escrowstaking contract
* that comes later to lock a user's NFT while still letting them keep it in their wallet.
*
* @param tokenId The ID of the token to lock.
* @param locked The status of the lock; true to lock, false to unlock.
*
* Requirements:
*
* - the caller must be the token owner or approved.
*/
function lockTransfer (uint256 tokenId, bool locked) external {
if (!_isApprovedOrOwner(_msgSender(), tokenId)) { revert NonOwnerOrApproved(); }
if (transferLocks[tokenId] == LockStatus.LockByAdmin) { revert TransferLockedByAdmin(); }
transferLocks[tokenId] = locked ? LockStatus.LockByTokenOwner : LockStatus.Unlock;
emit LockTransfer(ERC721.ownerOf(tokenId), tokenId, locked);
}
/**
* Locks the transfer of tokenIds. This is designed for a non-escrowstaking contract
* that comes later to lock a user's NFT while still letting them keep it in their wallet.
*
* @param tokenIds The IDs of the token to lock.
* @param locks The status of the lock; true to lock, false to unlock.
*
* Requirements:
*
* - the caller must be `_admin`.
*/
function lockTransfers (uint256[] memory tokenIds, bool[] memory locks) external onlyAdmin {
if (tokenIds.length != locks.length) { revert ArrayLengthMismatch(); }
for (uint256 i = 0; i < tokenIds.length; i++) {
transferLocks[tokenIds[i]] = locks[i] ? LockStatus.LockByAdmin : LockStatus.Unlock;
emit LockTransfer(ERC721.ownerOf(tokenIds[i]), tokenIds[i], locks[i]);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/SignatureChecker.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
import "../Address.sol";
import "../../interfaces/IERC1271.sol";
/**
* @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA
* signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like
* Argent and Gnosis Safe.
*
* _Available since v4.1._
*/
library SignatureChecker {
/**
* @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
* signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`.
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
* change through time. It could return true at block N and false at block N+1 (or the opposite).
*/
function isValidSignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
if (error == ECDSA.RecoverError.NoError && recovered == signer) {
return true;
}
(bool success, bytes memory result) = signer.staticcall(
abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
);
return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/interfaces/IERC721.sol";
import "@openzeppelin/contracts/interfaces/IERC721Receiver.sol";
import "@openzeppelin/contracts/interfaces/IERC721Metadata.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
error ZeroAddress();
error NonExistentToken();
error ApprovalToOwner();
error NonOwner();
error NonOwnerOrOperator();
error NonOwnerOrApproved();
error NonERC721ReceiverImplementer();
error DuplicatedMint();
/**
* @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;
// 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() {
}
/**
* @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) {
if (owner == address(0)) { revert ZeroAddress(); }
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
if (owner == address(0)) { revert NonExistentToken(); }
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return "";
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return "";
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) { revert NonExistentToken(); }
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
if (to == owner) { revert ApprovalToOwner(); }
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert NonOwnerOrOperator(); }
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
if (!_exists(tokenId)) { revert NonExistentToken(); }
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
if (!_isApprovedOrOwner(_msgSender(), tokenId)) { revert NonOwnerOrApproved(); }
_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 {
if (!_isApprovedOrOwner(_msgSender(), tokenId)) { revert NonOwnerOrApproved(); }
_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);
if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert NonERC721ReceiverImplementer(); }
}
/**
* @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) {
if (!_exists(tokenId)) { revert NonExistentToken(); }
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
if (to == address(0)) { revert ZeroAddress(); }
if (_exists(tokenId)) { revert DuplicatedMint(); }
_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 {
if (ERC721.ownerOf(tokenId) != from) { revert NonOwner(); }
if (to == address(0)) { revert ZeroAddress(); }
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
if (owner == operator) { revert ApprovalToOwner(); }
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert NonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*
* _Available since v4.5._
*/
interface IERC2981 is IERC165 {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be payed in that same unit of exchange.
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// 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 (interfaces/IERC1271.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../token/ERC721/extensions/IERC721Metadata.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721Receiver.sol)
pragma solidity ^0.8.0;
import "../token/ERC721/IERC721Receiver.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721.sol)
pragma solidity ^0.8.0;
import "../token/ERC721/IERC721.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
} | * @dev Toggles `burningActive`, `transferActive` and `metadataFrozen` Requirements: - the caller must be `owner`./ | function toggleFlag(uint256 flag) public virtual onlyOwner {
if (flag == uint256(keccak256("BURN")))
burningActive = !burningActive;
else if (flag == uint256(keccak256("TRANSFER")))
transferDeactive = !transferDeactive;
else if (flag == uint256(keccak256("METADATA")))
metadataFrozen = true;
}
| 10,342,087 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
5206,
399,
23972,
1040,
1375,
70,
321,
310,
3896,
9191,
1375,
13866,
3896,
68,
471,
1375,
4165,
42,
9808,
68,
29076,
30,
300,
326,
4894,
1297,
506,
1375,
8443,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
10486,
4678,
12,
11890,
5034,
2982,
13,
1071,
5024,
1338,
5541,
288,
203,
3639,
309,
261,
6420,
422,
2254,
5034,
12,
79,
24410,
581,
5034,
2932,
38,
8521,
6,
20349,
203,
5411,
18305,
310,
3896,
273,
401,
70,
321,
310,
3896,
31,
203,
3639,
469,
309,
261,
6420,
422,
2254,
5034,
12,
79,
24410,
581,
5034,
2932,
16596,
6553,
6,
20349,
203,
5411,
7412,
758,
3535,
273,
401,
13866,
758,
3535,
31,
203,
3639,
469,
309,
261,
6420,
422,
2254,
5034,
12,
79,
24410,
581,
5034,
2932,
22746,
6,
20349,
203,
5411,
1982,
42,
9808,
273,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
//
// https://remix.ethereum.org
// https://github.com/ConsenSys/MultiSigWallet/blob/master/contracts/solidity/MultiSigWallet.sol
//
import "github.com/ConsenSys/MultiSigWallet/contracts/solidity/MultiSigWallet.sol";
// change to 0.4.4 https://remix.ethereum.org/#version=soljson-v0.4.4+commit.4633f3de.js
//
// 2-of-3
// copy account1,account2
// swich back account0
// new FooWallet() [account0,account1,account2],2
// ["0xca35b7d915458ef540ade6068dfe2f44e8fa733c","0x14723a09acff6d2a60dcdf7aa4aff308fddc160c","0x4b0897b0513fdc7c541b6d9d7e929c4e5364d2db"],2
// fallback() 50 ether
// submitTransaction() "0xdeed",100,"0x00" return transactionId: 0
// confirmTransaction()@account1 0
// transactions() 0
// getBalance()
// submitTransaction() "0xdeed",200,"0x00" return transactionId: 1
// confirmTransaction()@account2 1
// transactions() 1
contract FooWallet is MultiSigWallet{
function FooWallet(address[] _owners,uint _required) MultiSigWallet(_owners, _required){
}
function getBalance() returns (uint) {
return this.balance;
}
}
// Why user ?
contract User {
function confirmTransaction(MultiSigWallet wallet ,uint txid){
wallet.confirmTransaction(txid);
}
}
//
// fallback() 100
// getBalance()
// initWallet2of3()
// getBalance() and getWalletBalance()
// testSign20f3()
// getBalance() and getWalletBalance()
//
contract TestWallet{
uint public txid;
MultiSigWallet w;
User user1 = new User();
User user2 = new User();
function initWallet2of3(){
address[] memory owners = new address[](3);
owners[0]=this;
owners[1]=user2;
owners[2]=user1;
w = new MultiSigWallet(owners, 2);
w.send(10 ether);
}
function testSign2of3() {
// _initWallet2of3();
bytes memory data = "foo";
// 1/3
txid = w.submitTransaction(0xdeed, 2 ether, data);
// 2/3
user1.confirmTransaction(w ,txid);
}
function getWalletBalance() returns (uint) {
return w.balance;
}
function getBalance() returns (uint) {
return this.balance;
}
function () payable {}
} | fallback() 100 getBalance() initWallet2of3() getBalance() and getWalletBalance() testSign20f3() getBalance() and getWalletBalance() | contract TestWallet{
uint public txid;
MultiSigWallet w;
User user1 = new User();
User user2 = new User();
function initWallet2of3(){
address[] memory owners = new address[](3);
owners[0]=this;
owners[1]=user2;
owners[2]=user1;
w = new MultiSigWallet(owners, 2);
w.send(10 ether);
}
function testSign2of3() {
bytes memory data = "foo";
txid = w.submitTransaction(0xdeed, 2 ether, data);
user1.confirmTransaction(w ,txid);
}
function getWalletBalance() returns (uint) {
return w.balance;
}
function getBalance() returns (uint) {
return this.balance;
}
function () payable {}
} | 1,006,450 | [
1,
4625,
348,
7953,
560,
30,
225,
5922,
1435,
2130,
2882,
6112,
1435,
1208,
16936,
22,
792,
23,
1435,
2882,
6112,
1435,
471,
13876,
6201,
13937,
1435,
1842,
2766,
3462,
74,
23,
1435,
2882,
6112,
1435,
471,
13876,
6201,
13937,
1435,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
7766,
16936,
95,
203,
377,
203,
565,
2254,
1071,
18372,
31,
203,
565,
5991,
8267,
16936,
341,
31,
203,
565,
2177,
729,
21,
273,
394,
2177,
5621,
203,
565,
2177,
729,
22,
273,
394,
2177,
5621,
203,
377,
203,
565,
445,
1208,
16936,
22,
792,
23,
1435,
95,
203,
3639,
1758,
8526,
3778,
25937,
273,
394,
1758,
8526,
12,
23,
1769,
203,
3639,
25937,
63,
20,
65,
33,
2211,
31,
203,
3639,
25937,
63,
21,
65,
33,
1355,
22,
31,
203,
3639,
25937,
63,
22,
65,
33,
1355,
21,
31,
203,
3639,
341,
273,
394,
5991,
8267,
16936,
12,
995,
414,
16,
576,
1769,
203,
3639,
341,
18,
4661,
12,
2163,
225,
2437,
1769,
203,
565,
289,
203,
377,
203,
565,
445,
1842,
2766,
22,
792,
23,
1435,
288,
203,
3639,
1731,
3778,
501,
273,
315,
11351,
14432,
203,
3639,
18372,
273,
341,
18,
9297,
3342,
12,
20,
92,
323,
329,
16,
576,
225,
2437,
16,
501,
1769,
203,
3639,
729,
21,
18,
10927,
3342,
12,
91,
269,
978,
350,
1769,
203,
565,
289,
203,
377,
203,
565,
445,
13876,
6201,
13937,
1435,
1135,
261,
11890,
13,
288,
203,
3639,
327,
341,
18,
12296,
31,
203,
565,
289,
203,
377,
203,
565,
445,
2882,
6112,
1435,
1135,
261,
11890,
13,
288,
203,
3639,
327,
333,
18,
12296,
31,
203,
565,
289,
203,
377,
203,
203,
565,
445,
1832,
8843,
429,
2618,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x45c00508C14601fd1C1e296eB3C0e3eEEdCa45D0/sources/contracts/exchangeIssuance/DEXAdapter.sol | * @title DEXAdapter @author Index Coop Adapter to execute swaps on different DEXes/ | library DEXAdapter {
using SafeERC20 for IERC20;
using PreciseUnitMath for uint256;
using SafeMath for uint256;
uint256 constant private MAX_UINT256 = type(uint256).max;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint256 public constant ROUNDING_ERROR_MARGIN = 2;
Copyright 2022 Index Cooperative
pragma solidity 0.6.10;
import { IUniswapV2Router02 } from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { ICurveCalculator } from "../interfaces/external/ICurveCalculator.sol";
import { ICurveAddressProvider } from "../interfaces/external/ICurveAddressProvider.sol";
import { ICurvePoolRegistry } from "../interfaces/external/ICurvePoolRegistry.sol";
import { ICurvePool } from "../interfaces/external/ICurvePool.sol";
import { ISwapRouter} from "../interfaces/external/ISwapRouter.sol";
import { IQuoter } from "../interfaces/IQuoter.sol";
import { IWETH } from "../interfaces/IWETH.sol";
import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol";
enum Exchange { None, Quickswap, Sushiswap, UniV3, Curve }
struct Addresses {
address quickRouter;
address sushiRouter;
address uniV3Router;
address uniV3Quoter;
address curveAddressProvider;
address curveCalculator;
address weth;
}
struct SwapData {
address[] path;
uint24[] fees;
address pool;
Exchange exchange;
}
struct CurvePoolData {
int128 nCoins;
uint256[8] balances;
uint256 A;
uint256 fee;
uint256[8] rates;
uint256[8] decimals;
}
function swapExactTokensForTokens(
Addresses memory _addresses,
uint256 _amountIn,
uint256 _minAmountOut,
SwapData memory _swapData
)
external
returns (uint256)
{
if (_swapData.path[0] == _swapData.path[_swapData.path.length -1]) {
return _amountIn;
}
if(_swapData.exchange == Exchange.Curve){
return _swapExactTokensForTokensCurve(
_swapData.path,
_swapData.pool,
_amountIn,
_minAmountOut,
_addresses
);
}
if(_swapData.exchange== Exchange.UniV3){
return _swapExactTokensForTokensUniV3(
_swapData.path,
_swapData.fees,
_amountIn,
_minAmountOut,
ISwapRouter(_addresses.uniV3Router)
);
return _swapExactTokensForTokensUniV2(
_swapData.path,
_amountIn,
_minAmountOut,
_getRouter(_swapData.exchange, _addresses)
);
}
}
function swapExactTokensForTokens(
Addresses memory _addresses,
uint256 _amountIn,
uint256 _minAmountOut,
SwapData memory _swapData
)
external
returns (uint256)
{
if (_swapData.path[0] == _swapData.path[_swapData.path.length -1]) {
return _amountIn;
}
if(_swapData.exchange == Exchange.Curve){
return _swapExactTokensForTokensCurve(
_swapData.path,
_swapData.pool,
_amountIn,
_minAmountOut,
_addresses
);
}
if(_swapData.exchange== Exchange.UniV3){
return _swapExactTokensForTokensUniV3(
_swapData.path,
_swapData.fees,
_amountIn,
_minAmountOut,
ISwapRouter(_addresses.uniV3Router)
);
return _swapExactTokensForTokensUniV2(
_swapData.path,
_amountIn,
_minAmountOut,
_getRouter(_swapData.exchange, _addresses)
);
}
}
function swapExactTokensForTokens(
Addresses memory _addresses,
uint256 _amountIn,
uint256 _minAmountOut,
SwapData memory _swapData
)
external
returns (uint256)
{
if (_swapData.path[0] == _swapData.path[_swapData.path.length -1]) {
return _amountIn;
}
if(_swapData.exchange == Exchange.Curve){
return _swapExactTokensForTokensCurve(
_swapData.path,
_swapData.pool,
_amountIn,
_minAmountOut,
_addresses
);
}
if(_swapData.exchange== Exchange.UniV3){
return _swapExactTokensForTokensUniV3(
_swapData.path,
_swapData.fees,
_amountIn,
_minAmountOut,
ISwapRouter(_addresses.uniV3Router)
);
return _swapExactTokensForTokensUniV2(
_swapData.path,
_amountIn,
_minAmountOut,
_getRouter(_swapData.exchange, _addresses)
);
}
}
function swapExactTokensForTokens(
Addresses memory _addresses,
uint256 _amountIn,
uint256 _minAmountOut,
SwapData memory _swapData
)
external
returns (uint256)
{
if (_swapData.path[0] == _swapData.path[_swapData.path.length -1]) {
return _amountIn;
}
if(_swapData.exchange == Exchange.Curve){
return _swapExactTokensForTokensCurve(
_swapData.path,
_swapData.pool,
_amountIn,
_minAmountOut,
_addresses
);
}
if(_swapData.exchange== Exchange.UniV3){
return _swapExactTokensForTokensUniV3(
_swapData.path,
_swapData.fees,
_amountIn,
_minAmountOut,
ISwapRouter(_addresses.uniV3Router)
);
return _swapExactTokensForTokensUniV2(
_swapData.path,
_amountIn,
_minAmountOut,
_getRouter(_swapData.exchange, _addresses)
);
}
}
} else {
function swapTokensForExactTokens(
Addresses memory _addresses,
uint256 _amountOut,
uint256 _maxAmountIn,
SwapData memory _swapData
)
external
returns (uint256 amountIn)
{
if (_swapData.path[0] == _swapData.path[_swapData.path.length -1]) {
return _amountOut;
}
if(_swapData.exchange == Exchange.Curve){
return _swapTokensForExactTokensCurve(
_swapData.path,
_swapData.pool,
_amountOut,
_maxAmountIn,
_addresses
);
}
if(_swapData.exchange == Exchange.UniV3){
return _swapTokensForExactTokensUniV3(
_swapData.path,
_swapData.fees,
_amountOut,
_maxAmountIn,
ISwapRouter(_addresses.uniV3Router)
);
return _swapTokensForExactTokensUniV2(
_swapData.path,
_amountOut,
_maxAmountIn,
_getRouter(_swapData.exchange, _addresses)
);
}
}
function swapTokensForExactTokens(
Addresses memory _addresses,
uint256 _amountOut,
uint256 _maxAmountIn,
SwapData memory _swapData
)
external
returns (uint256 amountIn)
{
if (_swapData.path[0] == _swapData.path[_swapData.path.length -1]) {
return _amountOut;
}
if(_swapData.exchange == Exchange.Curve){
return _swapTokensForExactTokensCurve(
_swapData.path,
_swapData.pool,
_amountOut,
_maxAmountIn,
_addresses
);
}
if(_swapData.exchange == Exchange.UniV3){
return _swapTokensForExactTokensUniV3(
_swapData.path,
_swapData.fees,
_amountOut,
_maxAmountIn,
ISwapRouter(_addresses.uniV3Router)
);
return _swapTokensForExactTokensUniV2(
_swapData.path,
_amountOut,
_maxAmountIn,
_getRouter(_swapData.exchange, _addresses)
);
}
}
function swapTokensForExactTokens(
Addresses memory _addresses,
uint256 _amountOut,
uint256 _maxAmountIn,
SwapData memory _swapData
)
external
returns (uint256 amountIn)
{
if (_swapData.path[0] == _swapData.path[_swapData.path.length -1]) {
return _amountOut;
}
if(_swapData.exchange == Exchange.Curve){
return _swapTokensForExactTokensCurve(
_swapData.path,
_swapData.pool,
_amountOut,
_maxAmountIn,
_addresses
);
}
if(_swapData.exchange == Exchange.UniV3){
return _swapTokensForExactTokensUniV3(
_swapData.path,
_swapData.fees,
_amountOut,
_maxAmountIn,
ISwapRouter(_addresses.uniV3Router)
);
return _swapTokensForExactTokensUniV2(
_swapData.path,
_amountOut,
_maxAmountIn,
_getRouter(_swapData.exchange, _addresses)
);
}
}
function swapTokensForExactTokens(
Addresses memory _addresses,
uint256 _amountOut,
uint256 _maxAmountIn,
SwapData memory _swapData
)
external
returns (uint256 amountIn)
{
if (_swapData.path[0] == _swapData.path[_swapData.path.length -1]) {
return _amountOut;
}
if(_swapData.exchange == Exchange.Curve){
return _swapTokensForExactTokensCurve(
_swapData.path,
_swapData.pool,
_amountOut,
_maxAmountIn,
_addresses
);
}
if(_swapData.exchange == Exchange.UniV3){
return _swapTokensForExactTokensUniV3(
_swapData.path,
_swapData.fees,
_amountOut,
_maxAmountIn,
ISwapRouter(_addresses.uniV3Router)
);
return _swapTokensForExactTokensUniV2(
_swapData.path,
_amountOut,
_maxAmountIn,
_getRouter(_swapData.exchange, _addresses)
);
}
}
} else {
function getAmountOut(
Addresses memory _addresses,
SwapData memory _swapData,
uint256 _amountIn
)
external
returns (uint256)
{
if (_swapData.path.length == 0 || _swapData.path[0] == _swapData.path[_swapData.path.length-1]) {
return _amountIn;
}
if (_swapData.exchange == Exchange.UniV3) {
return _getAmountOutUniV3(_swapData, _addresses.uniV3Quoter, _amountIn);
(int128 i, int128 j) = _getCoinIndices(
_swapData.pool,
_swapData.path[0],
_swapData.path[1],
ICurveAddressProvider(_addresses.curveAddressProvider)
);
return _getAmountOutCurve(_swapData.pool, i, j, _amountIn, _addresses);
return _getAmountOutUniV2(
_swapData,
_getRouter(_swapData.exchange, _addresses),
_amountIn
);
}
}
function getAmountOut(
Addresses memory _addresses,
SwapData memory _swapData,
uint256 _amountIn
)
external
returns (uint256)
{
if (_swapData.path.length == 0 || _swapData.path[0] == _swapData.path[_swapData.path.length-1]) {
return _amountIn;
}
if (_swapData.exchange == Exchange.UniV3) {
return _getAmountOutUniV3(_swapData, _addresses.uniV3Quoter, _amountIn);
(int128 i, int128 j) = _getCoinIndices(
_swapData.pool,
_swapData.path[0],
_swapData.path[1],
ICurveAddressProvider(_addresses.curveAddressProvider)
);
return _getAmountOutCurve(_swapData.pool, i, j, _amountIn, _addresses);
return _getAmountOutUniV2(
_swapData,
_getRouter(_swapData.exchange, _addresses),
_amountIn
);
}
}
function getAmountOut(
Addresses memory _addresses,
SwapData memory _swapData,
uint256 _amountIn
)
external
returns (uint256)
{
if (_swapData.path.length == 0 || _swapData.path[0] == _swapData.path[_swapData.path.length-1]) {
return _amountIn;
}
if (_swapData.exchange == Exchange.UniV3) {
return _getAmountOutUniV3(_swapData, _addresses.uniV3Quoter, _amountIn);
(int128 i, int128 j) = _getCoinIndices(
_swapData.pool,
_swapData.path[0],
_swapData.path[1],
ICurveAddressProvider(_addresses.curveAddressProvider)
);
return _getAmountOutCurve(_swapData.pool, i, j, _amountIn, _addresses);
return _getAmountOutUniV2(
_swapData,
_getRouter(_swapData.exchange, _addresses),
_amountIn
);
}
}
} else if (_swapData.exchange == Exchange.Curve) {
} else {
function getAmountIn(
Addresses memory _addresses,
SwapData memory _swapData,
uint256 _amountOut
)
external
returns (uint256)
{
if (_swapData.path.length == 0 || _swapData.path[0] == _swapData.path[_swapData.path.length-1]) {
return _amountOut;
}
if (_swapData.exchange == Exchange.UniV3) {
return _getAmountInUniV3(_swapData, _addresses.uniV3Quoter, _amountOut);
(int128 i, int128 j) = _getCoinIndices(
_swapData.pool,
_swapData.path[0],
_swapData.path[1],
ICurveAddressProvider(_addresses.curveAddressProvider)
);
return _getAmountInCurve(_swapData.pool, i, j, _amountOut, _addresses);
return _getAmountInUniV2(
_swapData,
_getRouter(_swapData.exchange, _addresses),
_amountOut
);
}
}
function getAmountIn(
Addresses memory _addresses,
SwapData memory _swapData,
uint256 _amountOut
)
external
returns (uint256)
{
if (_swapData.path.length == 0 || _swapData.path[0] == _swapData.path[_swapData.path.length-1]) {
return _amountOut;
}
if (_swapData.exchange == Exchange.UniV3) {
return _getAmountInUniV3(_swapData, _addresses.uniV3Quoter, _amountOut);
(int128 i, int128 j) = _getCoinIndices(
_swapData.pool,
_swapData.path[0],
_swapData.path[1],
ICurveAddressProvider(_addresses.curveAddressProvider)
);
return _getAmountInCurve(_swapData.pool, i, j, _amountOut, _addresses);
return _getAmountInUniV2(
_swapData,
_getRouter(_swapData.exchange, _addresses),
_amountOut
);
}
}
function getAmountIn(
Addresses memory _addresses,
SwapData memory _swapData,
uint256 _amountOut
)
external
returns (uint256)
{
if (_swapData.path.length == 0 || _swapData.path[0] == _swapData.path[_swapData.path.length-1]) {
return _amountOut;
}
if (_swapData.exchange == Exchange.UniV3) {
return _getAmountInUniV3(_swapData, _addresses.uniV3Quoter, _amountOut);
(int128 i, int128 j) = _getCoinIndices(
_swapData.pool,
_swapData.path[0],
_swapData.path[1],
ICurveAddressProvider(_addresses.curveAddressProvider)
);
return _getAmountInCurve(_swapData.pool, i, j, _amountOut, _addresses);
return _getAmountInUniV2(
_swapData,
_getRouter(_swapData.exchange, _addresses),
_amountOut
);
}
}
} else if (_swapData.exchange == Exchange.Curve) {
} else {
function _safeApprove(
IERC20 _token,
address _spender,
uint256 _requiredAllowance
)
internal
{
uint256 allowance = _token.allowance(address(this), _spender);
if (allowance < _requiredAllowance) {
_token.safeIncreaseAllowance(_spender, MAX_UINT256 - allowance);
}
}
function _safeApprove(
IERC20 _token,
address _spender,
uint256 _requiredAllowance
)
internal
{
uint256 allowance = _token.allowance(address(this), _spender);
if (allowance < _requiredAllowance) {
_token.safeIncreaseAllowance(_spender, MAX_UINT256 - allowance);
}
}
function _swapTokensForExactTokensUniV2(
address[] memory _path,
uint256 _amountOut,
uint256 _maxAmountIn,
IUniswapV2Router02 _router
)
private
returns (uint256)
{
_safeApprove(IERC20(_path[0]), address(_router), _maxAmountIn);
return _router.swapTokensForExactTokens(_amountOut, _maxAmountIn, _path, address(this), block.timestamp)[0];
}
function _swapTokensForExactTokensUniV3(
address[] memory _path,
uint24[] memory _fees,
uint256 _amountOut,
uint256 _maxAmountIn,
ISwapRouter _uniV3Router
)
private
returns(uint256)
{
require(_path.length == _fees.length + 1, "ExchangeIssuance: PATHS_FEES_MISMATCH");
_safeApprove(IERC20(_path[0]), address(_uniV3Router), _maxAmountIn);
if(_path.length == 2){
ISwapRouter.ExactOutputSingleParams memory params =
ISwapRouter.ExactOutputSingleParams({
tokenIn: _path[0],
tokenOut: _path[1],
fee: _fees[0],
recipient: address(this),
deadline: block.timestamp,
amountOut: _amountOut,
amountInMaximum: _maxAmountIn,
sqrtPriceLimitX96: 0
});
return _uniV3Router.exactOutputSingle(params);
bytes memory pathV3 = _encodePathV3(_path, _fees, true);
ISwapRouter.ExactOutputParams memory params =
ISwapRouter.ExactOutputParams({
path: pathV3,
recipient: address(this),
deadline: block.timestamp,
amountOut: _amountOut,
amountInMaximum: _maxAmountIn
});
return _uniV3Router.exactOutput(params);
}
}
function _swapTokensForExactTokensUniV3(
address[] memory _path,
uint24[] memory _fees,
uint256 _amountOut,
uint256 _maxAmountIn,
ISwapRouter _uniV3Router
)
private
returns(uint256)
{
require(_path.length == _fees.length + 1, "ExchangeIssuance: PATHS_FEES_MISMATCH");
_safeApprove(IERC20(_path[0]), address(_uniV3Router), _maxAmountIn);
if(_path.length == 2){
ISwapRouter.ExactOutputSingleParams memory params =
ISwapRouter.ExactOutputSingleParams({
tokenIn: _path[0],
tokenOut: _path[1],
fee: _fees[0],
recipient: address(this),
deadline: block.timestamp,
amountOut: _amountOut,
amountInMaximum: _maxAmountIn,
sqrtPriceLimitX96: 0
});
return _uniV3Router.exactOutputSingle(params);
bytes memory pathV3 = _encodePathV3(_path, _fees, true);
ISwapRouter.ExactOutputParams memory params =
ISwapRouter.ExactOutputParams({
path: pathV3,
recipient: address(this),
deadline: block.timestamp,
amountOut: _amountOut,
amountInMaximum: _maxAmountIn
});
return _uniV3Router.exactOutput(params);
}
}
function _swapTokensForExactTokensUniV3(
address[] memory _path,
uint24[] memory _fees,
uint256 _amountOut,
uint256 _maxAmountIn,
ISwapRouter _uniV3Router
)
private
returns(uint256)
{
require(_path.length == _fees.length + 1, "ExchangeIssuance: PATHS_FEES_MISMATCH");
_safeApprove(IERC20(_path[0]), address(_uniV3Router), _maxAmountIn);
if(_path.length == 2){
ISwapRouter.ExactOutputSingleParams memory params =
ISwapRouter.ExactOutputSingleParams({
tokenIn: _path[0],
tokenOut: _path[1],
fee: _fees[0],
recipient: address(this),
deadline: block.timestamp,
amountOut: _amountOut,
amountInMaximum: _maxAmountIn,
sqrtPriceLimitX96: 0
});
return _uniV3Router.exactOutputSingle(params);
bytes memory pathV3 = _encodePathV3(_path, _fees, true);
ISwapRouter.ExactOutputParams memory params =
ISwapRouter.ExactOutputParams({
path: pathV3,
recipient: address(this),
deadline: block.timestamp,
amountOut: _amountOut,
amountInMaximum: _maxAmountIn
});
return _uniV3Router.exactOutput(params);
}
}
} else {
function _swapTokensForExactTokensUniV3(
address[] memory _path,
uint24[] memory _fees,
uint256 _amountOut,
uint256 _maxAmountIn,
ISwapRouter _uniV3Router
)
private
returns(uint256)
{
require(_path.length == _fees.length + 1, "ExchangeIssuance: PATHS_FEES_MISMATCH");
_safeApprove(IERC20(_path[0]), address(_uniV3Router), _maxAmountIn);
if(_path.length == 2){
ISwapRouter.ExactOutputSingleParams memory params =
ISwapRouter.ExactOutputSingleParams({
tokenIn: _path[0],
tokenOut: _path[1],
fee: _fees[0],
recipient: address(this),
deadline: block.timestamp,
amountOut: _amountOut,
amountInMaximum: _maxAmountIn,
sqrtPriceLimitX96: 0
});
return _uniV3Router.exactOutputSingle(params);
bytes memory pathV3 = _encodePathV3(_path, _fees, true);
ISwapRouter.ExactOutputParams memory params =
ISwapRouter.ExactOutputParams({
path: pathV3,
recipient: address(this),
deadline: block.timestamp,
amountOut: _amountOut,
amountInMaximum: _maxAmountIn
});
return _uniV3Router.exactOutput(params);
}
}
function _swapExactTokensForTokensCurve(
address[] memory _path,
address _pool,
uint256 _amountIn,
uint256 _minAmountOut,
Addresses memory _addresses
)
private
returns (uint256 amountOut)
{
require(_path.length == 2, "ExchangeIssuance: CURVE_WRONG_PATH_LENGTH");
(int128 i, int128 j) = _getCoinIndices(_pool, _path[0], _path[1], ICurveAddressProvider(_addresses.curveAddressProvider));
if(_path[0] == ETH_ADDRESS){
IWETH(_addresses.weth).withdraw(_amountIn);
}
amountOut = _exchangeCurve(i, j, _pool, _amountIn, _minAmountOut, _path[0]);
if(_path[_path.length-1] == ETH_ADDRESS){
}
}
function _swapExactTokensForTokensCurve(
address[] memory _path,
address _pool,
uint256 _amountIn,
uint256 _minAmountOut,
Addresses memory _addresses
)
private
returns (uint256 amountOut)
{
require(_path.length == 2, "ExchangeIssuance: CURVE_WRONG_PATH_LENGTH");
(int128 i, int128 j) = _getCoinIndices(_pool, _path[0], _path[1], ICurveAddressProvider(_addresses.curveAddressProvider));
if(_path[0] == ETH_ADDRESS){
IWETH(_addresses.weth).withdraw(_amountIn);
}
amountOut = _exchangeCurve(i, j, _pool, _amountIn, _minAmountOut, _path[0]);
if(_path[_path.length-1] == ETH_ADDRESS){
}
}
function _swapExactTokensForTokensCurve(
address[] memory _path,
address _pool,
uint256 _amountIn,
uint256 _minAmountOut,
Addresses memory _addresses
)
private
returns (uint256 amountOut)
{
require(_path.length == 2, "ExchangeIssuance: CURVE_WRONG_PATH_LENGTH");
(int128 i, int128 j) = _getCoinIndices(_pool, _path[0], _path[1], ICurveAddressProvider(_addresses.curveAddressProvider));
if(_path[0] == ETH_ADDRESS){
IWETH(_addresses.weth).withdraw(_amountIn);
}
amountOut = _exchangeCurve(i, j, _pool, _amountIn, _minAmountOut, _path[0]);
if(_path[_path.length-1] == ETH_ADDRESS){
}
}
IWETH(_addresses.weth).deposit{value: amountOut}();
function _swapTokensForExactTokensCurve(
address[] memory _path,
address _pool,
uint256 _amountOut,
uint256 _maxAmountIn,
Addresses memory _addresses
)
private
returns (uint256)
{
require(_path.length == 2, "ExchangeIssuance: CURVE_WRONG_PATH_LENGTH");
(int128 i, int128 j) = _getCoinIndices(_pool, _path[0], _path[1], ICurveAddressProvider(_addresses.curveAddressProvider));
if(_path[0] == ETH_ADDRESS){
IWETH(_addresses.weth).withdraw(_maxAmountIn);
}
uint256 returnedAmountOut = _exchangeCurve(i, j, _pool, _maxAmountIn, _amountOut, _path[0]);
require(_amountOut <= returnedAmountOut, "ExchangeIssuance: CURVE_UNDERBOUGHT");
uint256 swappedBackAmountIn;
if(returnedAmountOut > _amountOut){
swappedBackAmountIn = _exchangeCurve(j, i, _pool, returnedAmountOut.sub(_amountOut), 0, _path[1]);
if(_path[0] == ETH_ADDRESS){
}
}
if(_path[_path.length-1] == ETH_ADDRESS){
}
return _maxAmountIn.sub(swappedBackAmountIn);
}
function _swapTokensForExactTokensCurve(
address[] memory _path,
address _pool,
uint256 _amountOut,
uint256 _maxAmountIn,
Addresses memory _addresses
)
private
returns (uint256)
{
require(_path.length == 2, "ExchangeIssuance: CURVE_WRONG_PATH_LENGTH");
(int128 i, int128 j) = _getCoinIndices(_pool, _path[0], _path[1], ICurveAddressProvider(_addresses.curveAddressProvider));
if(_path[0] == ETH_ADDRESS){
IWETH(_addresses.weth).withdraw(_maxAmountIn);
}
uint256 returnedAmountOut = _exchangeCurve(i, j, _pool, _maxAmountIn, _amountOut, _path[0]);
require(_amountOut <= returnedAmountOut, "ExchangeIssuance: CURVE_UNDERBOUGHT");
uint256 swappedBackAmountIn;
if(returnedAmountOut > _amountOut){
swappedBackAmountIn = _exchangeCurve(j, i, _pool, returnedAmountOut.sub(_amountOut), 0, _path[1]);
if(_path[0] == ETH_ADDRESS){
}
}
if(_path[_path.length-1] == ETH_ADDRESS){
}
return _maxAmountIn.sub(swappedBackAmountIn);
}
function _swapTokensForExactTokensCurve(
address[] memory _path,
address _pool,
uint256 _amountOut,
uint256 _maxAmountIn,
Addresses memory _addresses
)
private
returns (uint256)
{
require(_path.length == 2, "ExchangeIssuance: CURVE_WRONG_PATH_LENGTH");
(int128 i, int128 j) = _getCoinIndices(_pool, _path[0], _path[1], ICurveAddressProvider(_addresses.curveAddressProvider));
if(_path[0] == ETH_ADDRESS){
IWETH(_addresses.weth).withdraw(_maxAmountIn);
}
uint256 returnedAmountOut = _exchangeCurve(i, j, _pool, _maxAmountIn, _amountOut, _path[0]);
require(_amountOut <= returnedAmountOut, "ExchangeIssuance: CURVE_UNDERBOUGHT");
uint256 swappedBackAmountIn;
if(returnedAmountOut > _amountOut){
swappedBackAmountIn = _exchangeCurve(j, i, _pool, returnedAmountOut.sub(_amountOut), 0, _path[1]);
if(_path[0] == ETH_ADDRESS){
}
}
if(_path[_path.length-1] == ETH_ADDRESS){
}
return _maxAmountIn.sub(swappedBackAmountIn);
}
function _swapTokensForExactTokensCurve(
address[] memory _path,
address _pool,
uint256 _amountOut,
uint256 _maxAmountIn,
Addresses memory _addresses
)
private
returns (uint256)
{
require(_path.length == 2, "ExchangeIssuance: CURVE_WRONG_PATH_LENGTH");
(int128 i, int128 j) = _getCoinIndices(_pool, _path[0], _path[1], ICurveAddressProvider(_addresses.curveAddressProvider));
if(_path[0] == ETH_ADDRESS){
IWETH(_addresses.weth).withdraw(_maxAmountIn);
}
uint256 returnedAmountOut = _exchangeCurve(i, j, _pool, _maxAmountIn, _amountOut, _path[0]);
require(_amountOut <= returnedAmountOut, "ExchangeIssuance: CURVE_UNDERBOUGHT");
uint256 swappedBackAmountIn;
if(returnedAmountOut > _amountOut){
swappedBackAmountIn = _exchangeCurve(j, i, _pool, returnedAmountOut.sub(_amountOut), 0, _path[1]);
if(_path[0] == ETH_ADDRESS){
}
}
if(_path[_path.length-1] == ETH_ADDRESS){
}
return _maxAmountIn.sub(swappedBackAmountIn);
}
IWETH(_addresses.weth).deposit{ value: swappedBackAmountIn }();
function _swapTokensForExactTokensCurve(
address[] memory _path,
address _pool,
uint256 _amountOut,
uint256 _maxAmountIn,
Addresses memory _addresses
)
private
returns (uint256)
{
require(_path.length == 2, "ExchangeIssuance: CURVE_WRONG_PATH_LENGTH");
(int128 i, int128 j) = _getCoinIndices(_pool, _path[0], _path[1], ICurveAddressProvider(_addresses.curveAddressProvider));
if(_path[0] == ETH_ADDRESS){
IWETH(_addresses.weth).withdraw(_maxAmountIn);
}
uint256 returnedAmountOut = _exchangeCurve(i, j, _pool, _maxAmountIn, _amountOut, _path[0]);
require(_amountOut <= returnedAmountOut, "ExchangeIssuance: CURVE_UNDERBOUGHT");
uint256 swappedBackAmountIn;
if(returnedAmountOut > _amountOut){
swappedBackAmountIn = _exchangeCurve(j, i, _pool, returnedAmountOut.sub(_amountOut), 0, _path[1]);
if(_path[0] == ETH_ADDRESS){
}
}
if(_path[_path.length-1] == ETH_ADDRESS){
}
return _maxAmountIn.sub(swappedBackAmountIn);
}
IWETH(_addresses.weth).deposit{ value: _amountOut }();
function _exchangeCurve(
int128 _i,
int128 _j,
address _pool,
uint256 _amountIn,
uint256 _minAmountOut,
address _from
)
private
returns (uint256 amountOut)
{
ICurvePool pool = ICurvePool(_pool);
if(_from == ETH_ADDRESS){
_i,
_j,
_amountIn,
_minAmountOut
);
}
else {
IERC20(_from).approve(_pool, _amountIn);
amountOut = pool.exchange(
_i,
_j,
_amountIn,
_minAmountOut
);
}
}
function _exchangeCurve(
int128 _i,
int128 _j,
address _pool,
uint256 _amountIn,
uint256 _minAmountOut,
address _from
)
private
returns (uint256 amountOut)
{
ICurvePool pool = ICurvePool(_pool);
if(_from == ETH_ADDRESS){
_i,
_j,
_amountIn,
_minAmountOut
);
}
else {
IERC20(_from).approve(_pool, _amountIn);
amountOut = pool.exchange(
_i,
_j,
_amountIn,
_minAmountOut
);
}
}
amountOut = pool.exchange{value: _amountIn}(
function _exchangeCurve(
int128 _i,
int128 _j,
address _pool,
uint256 _amountIn,
uint256 _minAmountOut,
address _from
)
private
returns (uint256 amountOut)
{
ICurvePool pool = ICurvePool(_pool);
if(_from == ETH_ADDRESS){
_i,
_j,
_amountIn,
_minAmountOut
);
}
else {
IERC20(_from).approve(_pool, _amountIn);
amountOut = pool.exchange(
_i,
_j,
_amountIn,
_minAmountOut
);
}
}
function _getAmountInCurve(
address _pool,
int128 _i,
int128 _j,
uint256 _amountOut,
Addresses memory _addresses
)
private
view
returns (uint256)
{
CurvePoolData memory poolData = _getCurvePoolData(_pool, ICurveAddressProvider(_addresses.curveAddressProvider));
return ICurveCalculator(_addresses.curveCalculator).get_dx(
poolData.nCoins,
poolData.balances,
poolData.A,
poolData.fee,
poolData.rates,
poolData.decimals,
false,
_i,
_j,
_amountOut
) + ROUNDING_ERROR_MARGIN;
}
function _getAmountOutCurve(
address _pool,
int128 _i,
int128 _j,
uint256 _amountIn,
Addresses memory _addresses
)
private
view
returns (uint256)
{
return ICurvePool(_pool).get_dy(_i, _j, _amountIn);
}
function _getCurvePoolData(
address _pool,
ICurveAddressProvider _curveAddressProvider
) private view returns(CurvePoolData memory)
{
ICurvePoolRegistry registry = ICurvePoolRegistry(_curveAddressProvider.get_registry());
return CurvePoolData(
int128(registry.get_n_coins(_pool)[0]),
registry.get_balances(_pool),
registry.get_A(_pool),
registry.get_fees(_pool)[0],
registry.get_rates(_pool),
registry.get_decimals(_pool)
);
}
function _getCoinIndices(
address _pool,
address _from,
address _to,
ICurveAddressProvider _curveAddressProvider
)
private
view
returns (int128 i, int128 j)
{
ICurvePoolRegistry registry = ICurvePoolRegistry(_curveAddressProvider.get_registry());
i = 9;
j = 9;
address[8] memory poolCoins = registry.get_coins(_pool);
for(uint256 k = 0; k < 8; k++){
if(poolCoins[k] == _from){
i = int128(k);
}
else if(poolCoins[k] == _to){
j = int128(k);
}
if(poolCoins[k] == address(0) || (i != 9 && j != 9)){
break;
}
}
require(i != 9, "ExchangeIssuance: CURVE_FROM_NOT_FOUND");
require(j != 9, "ExchangeIssuance: CURVE_TO_NOT_FOUND");
return (i, j);
}
function _getCoinIndices(
address _pool,
address _from,
address _to,
ICurveAddressProvider _curveAddressProvider
)
private
view
returns (int128 i, int128 j)
{
ICurvePoolRegistry registry = ICurvePoolRegistry(_curveAddressProvider.get_registry());
i = 9;
j = 9;
address[8] memory poolCoins = registry.get_coins(_pool);
for(uint256 k = 0; k < 8; k++){
if(poolCoins[k] == _from){
i = int128(k);
}
else if(poolCoins[k] == _to){
j = int128(k);
}
if(poolCoins[k] == address(0) || (i != 9 && j != 9)){
break;
}
}
require(i != 9, "ExchangeIssuance: CURVE_FROM_NOT_FOUND");
require(j != 9, "ExchangeIssuance: CURVE_TO_NOT_FOUND");
return (i, j);
}
function _getCoinIndices(
address _pool,
address _from,
address _to,
ICurveAddressProvider _curveAddressProvider
)
private
view
returns (int128 i, int128 j)
{
ICurvePoolRegistry registry = ICurvePoolRegistry(_curveAddressProvider.get_registry());
i = 9;
j = 9;
address[8] memory poolCoins = registry.get_coins(_pool);
for(uint256 k = 0; k < 8; k++){
if(poolCoins[k] == _from){
i = int128(k);
}
else if(poolCoins[k] == _to){
j = int128(k);
}
if(poolCoins[k] == address(0) || (i != 9 && j != 9)){
break;
}
}
require(i != 9, "ExchangeIssuance: CURVE_FROM_NOT_FOUND");
require(j != 9, "ExchangeIssuance: CURVE_TO_NOT_FOUND");
return (i, j);
}
function _getCoinIndices(
address _pool,
address _from,
address _to,
ICurveAddressProvider _curveAddressProvider
)
private
view
returns (int128 i, int128 j)
{
ICurvePoolRegistry registry = ICurvePoolRegistry(_curveAddressProvider.get_registry());
i = 9;
j = 9;
address[8] memory poolCoins = registry.get_coins(_pool);
for(uint256 k = 0; k < 8; k++){
if(poolCoins[k] == _from){
i = int128(k);
}
else if(poolCoins[k] == _to){
j = int128(k);
}
if(poolCoins[k] == address(0) || (i != 9 && j != 9)){
break;
}
}
require(i != 9, "ExchangeIssuance: CURVE_FROM_NOT_FOUND");
require(j != 9, "ExchangeIssuance: CURVE_TO_NOT_FOUND");
return (i, j);
}
function _getCoinIndices(
address _pool,
address _from,
address _to,
ICurveAddressProvider _curveAddressProvider
)
private
view
returns (int128 i, int128 j)
{
ICurvePoolRegistry registry = ICurvePoolRegistry(_curveAddressProvider.get_registry());
i = 9;
j = 9;
address[8] memory poolCoins = registry.get_coins(_pool);
for(uint256 k = 0; k < 8; k++){
if(poolCoins[k] == _from){
i = int128(k);
}
else if(poolCoins[k] == _to){
j = int128(k);
}
if(poolCoins[k] == address(0) || (i != 9 && j != 9)){
break;
}
}
require(i != 9, "ExchangeIssuance: CURVE_FROM_NOT_FOUND");
require(j != 9, "ExchangeIssuance: CURVE_TO_NOT_FOUND");
return (i, j);
}
function _swapExactTokensForTokensUniV3(
address[] memory _path,
uint24[] memory _fees,
uint256 _amountIn,
uint256 _minAmountOut,
ISwapRouter _uniV3Router
)
private
returns (uint256)
{
require(_path.length == _fees.length + 1, "ExchangeIssuance: PATHS_FEES_MISMATCH");
_safeApprove(IERC20(_path[0]), address(_uniV3Router), _amountIn);
if(_path.length == 2){
ISwapRouter.ExactInputSingleParams memory params =
ISwapRouter.ExactInputSingleParams({
tokenIn: _path[0],
tokenOut: _path[1],
fee: _fees[0],
recipient: address(this),
deadline: block.timestamp,
amountIn: _amountIn,
amountOutMinimum: _minAmountOut,
sqrtPriceLimitX96: 0
});
return _uniV3Router.exactInputSingle(params);
bytes memory pathV3 = _encodePathV3(_path, _fees, false);
ISwapRouter.ExactInputParams memory params =
ISwapRouter.ExactInputParams({
path: pathV3,
recipient: address(this),
deadline: block.timestamp,
amountIn: _amountIn,
amountOutMinimum: _minAmountOut
});
uint amountOut = _uniV3Router.exactInput(params);
return amountOut;
}
}
function _swapExactTokensForTokensUniV3(
address[] memory _path,
uint24[] memory _fees,
uint256 _amountIn,
uint256 _minAmountOut,
ISwapRouter _uniV3Router
)
private
returns (uint256)
{
require(_path.length == _fees.length + 1, "ExchangeIssuance: PATHS_FEES_MISMATCH");
_safeApprove(IERC20(_path[0]), address(_uniV3Router), _amountIn);
if(_path.length == 2){
ISwapRouter.ExactInputSingleParams memory params =
ISwapRouter.ExactInputSingleParams({
tokenIn: _path[0],
tokenOut: _path[1],
fee: _fees[0],
recipient: address(this),
deadline: block.timestamp,
amountIn: _amountIn,
amountOutMinimum: _minAmountOut,
sqrtPriceLimitX96: 0
});
return _uniV3Router.exactInputSingle(params);
bytes memory pathV3 = _encodePathV3(_path, _fees, false);
ISwapRouter.ExactInputParams memory params =
ISwapRouter.ExactInputParams({
path: pathV3,
recipient: address(this),
deadline: block.timestamp,
amountIn: _amountIn,
amountOutMinimum: _minAmountOut
});
uint amountOut = _uniV3Router.exactInput(params);
return amountOut;
}
}
function _swapExactTokensForTokensUniV3(
address[] memory _path,
uint24[] memory _fees,
uint256 _amountIn,
uint256 _minAmountOut,
ISwapRouter _uniV3Router
)
private
returns (uint256)
{
require(_path.length == _fees.length + 1, "ExchangeIssuance: PATHS_FEES_MISMATCH");
_safeApprove(IERC20(_path[0]), address(_uniV3Router), _amountIn);
if(_path.length == 2){
ISwapRouter.ExactInputSingleParams memory params =
ISwapRouter.ExactInputSingleParams({
tokenIn: _path[0],
tokenOut: _path[1],
fee: _fees[0],
recipient: address(this),
deadline: block.timestamp,
amountIn: _amountIn,
amountOutMinimum: _minAmountOut,
sqrtPriceLimitX96: 0
});
return _uniV3Router.exactInputSingle(params);
bytes memory pathV3 = _encodePathV3(_path, _fees, false);
ISwapRouter.ExactInputParams memory params =
ISwapRouter.ExactInputParams({
path: pathV3,
recipient: address(this),
deadline: block.timestamp,
amountIn: _amountIn,
amountOutMinimum: _minAmountOut
});
uint amountOut = _uniV3Router.exactInput(params);
return amountOut;
}
}
} else {
function _swapExactTokensForTokensUniV3(
address[] memory _path,
uint24[] memory _fees,
uint256 _amountIn,
uint256 _minAmountOut,
ISwapRouter _uniV3Router
)
private
returns (uint256)
{
require(_path.length == _fees.length + 1, "ExchangeIssuance: PATHS_FEES_MISMATCH");
_safeApprove(IERC20(_path[0]), address(_uniV3Router), _amountIn);
if(_path.length == 2){
ISwapRouter.ExactInputSingleParams memory params =
ISwapRouter.ExactInputSingleParams({
tokenIn: _path[0],
tokenOut: _path[1],
fee: _fees[0],
recipient: address(this),
deadline: block.timestamp,
amountIn: _amountIn,
amountOutMinimum: _minAmountOut,
sqrtPriceLimitX96: 0
});
return _uniV3Router.exactInputSingle(params);
bytes memory pathV3 = _encodePathV3(_path, _fees, false);
ISwapRouter.ExactInputParams memory params =
ISwapRouter.ExactInputParams({
path: pathV3,
recipient: address(this),
deadline: block.timestamp,
amountIn: _amountIn,
amountOutMinimum: _minAmountOut
});
uint amountOut = _uniV3Router.exactInput(params);
return amountOut;
}
}
function _swapExactTokensForTokensUniV2(
address[] memory _path,
uint256 _amountIn,
uint256 _minAmountOut,
IUniswapV2Router02 _router
)
private
returns (uint256)
{
_safeApprove(IERC20(_path[0]), address(_router), _amountIn);
uint256[] memory result = _router.swapExactTokensForTokens(_amountIn, _minAmountOut, _path, address(this), block.timestamp);
return result[result.length-1];
}
function _getAmountOutUniV2(
SwapData memory _swapData,
IUniswapV2Router02 _router,
uint256 _amountIn
)
private
view
returns (uint256)
{
return _router.getAmountsOut(_amountIn, _swapData.path)[_swapData.path.length-1];
}
function _getAmountInUniV2(
SwapData memory _swapData,
IUniswapV2Router02 _router,
uint256 _amountOut
)
private
view
returns (uint256)
{
return _router.getAmountsIn(_amountOut, _swapData.path)[0];
}
function _getAmountOutUniV3(
SwapData memory _swapData,
address _quoter,
uint256 _amountIn
)
private
returns (uint256)
{
bytes memory path = _encodePathV3(_swapData.path, _swapData.fees, false);
return IQuoter(_quoter).quoteExactInput(path, _amountIn);
}
function _getAmountInUniV3(
SwapData memory _swapData,
address _quoter,
uint256 _amountOut
)
private
returns (uint256)
{
bytes memory path = _encodePathV3(_swapData.path, _swapData.fees, true);
return IQuoter(_quoter).quoteExactOutput(path, _amountOut);
}
function _encodePathV3(
address[] memory _path,
uint24[] memory _fees,
bool _reverseOrder
)
private
pure
returns(bytes memory encodedPath)
{
if(_reverseOrder){
encodedPath = abi.encodePacked(_path[_path.length-1]);
for(uint i = 0; i < _fees.length; i++){
uint index = _fees.length - i - 1;
encodedPath = abi.encodePacked(encodedPath, _fees[index], _path[index]);
}
encodedPath = abi.encodePacked(_path[0]);
for(uint i = 0; i < _fees.length; i++){
encodedPath = abi.encodePacked(encodedPath, _fees[i], _path[i+1]);
}
}
}
function _encodePathV3(
address[] memory _path,
uint24[] memory _fees,
bool _reverseOrder
)
private
pure
returns(bytes memory encodedPath)
{
if(_reverseOrder){
encodedPath = abi.encodePacked(_path[_path.length-1]);
for(uint i = 0; i < _fees.length; i++){
uint index = _fees.length - i - 1;
encodedPath = abi.encodePacked(encodedPath, _fees[index], _path[index]);
}
encodedPath = abi.encodePacked(_path[0]);
for(uint i = 0; i < _fees.length; i++){
encodedPath = abi.encodePacked(encodedPath, _fees[i], _path[i+1]);
}
}
}
function _encodePathV3(
address[] memory _path,
uint24[] memory _fees,
bool _reverseOrder
)
private
pure
returns(bytes memory encodedPath)
{
if(_reverseOrder){
encodedPath = abi.encodePacked(_path[_path.length-1]);
for(uint i = 0; i < _fees.length; i++){
uint index = _fees.length - i - 1;
encodedPath = abi.encodePacked(encodedPath, _fees[index], _path[index]);
}
encodedPath = abi.encodePacked(_path[0]);
for(uint i = 0; i < _fees.length; i++){
encodedPath = abi.encodePacked(encodedPath, _fees[i], _path[i+1]);
}
}
}
} else {
function _encodePathV3(
address[] memory _path,
uint24[] memory _fees,
bool _reverseOrder
)
private
pure
returns(bytes memory encodedPath)
{
if(_reverseOrder){
encodedPath = abi.encodePacked(_path[_path.length-1]);
for(uint i = 0; i < _fees.length; i++){
uint index = _fees.length - i - 1;
encodedPath = abi.encodePacked(encodedPath, _fees[index], _path[index]);
}
encodedPath = abi.encodePacked(_path[0]);
for(uint i = 0; i < _fees.length; i++){
encodedPath = abi.encodePacked(encodedPath, _fees[i], _path[i+1]);
}
}
}
function _getRouter(
Exchange _exchange,
Addresses memory _addresses
)
private
pure
returns (IUniswapV2Router02)
{
return IUniswapV2Router02(
(_exchange == Exchange.Quickswap) ? _addresses.quickRouter : _addresses.sushiRouter
);
}
}
| 9,182,626 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
2649,
2030,
60,
4216,
632,
4161,
3340,
7695,
556,
14238,
358,
1836,
1352,
6679,
603,
3775,
2030,
60,
281,
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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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2030,
60,
4216,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
565,
1450,
2962,
30708,
2802,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
203,
565,
2254,
5034,
5381,
3238,
4552,
67,
57,
3217,
5034,
273,
618,
12,
11890,
5034,
2934,
1896,
31,
203,
565,
1758,
1071,
5381,
512,
2455,
67,
15140,
273,
374,
17432,
1340,
1340,
41,
1340,
73,
41,
73,
41,
1340,
41,
73,
41,
73,
41,
1340,
9383,
41,
1340,
1340,
41,
1340,
1340,
1340,
73,
9383,
73,
41,
31,
203,
565,
2254,
5034,
1071,
5381,
27048,
1360,
67,
3589,
67,
19772,
7702,
273,
576,
31,
203,
203,
203,
203,
203,
565,
25417,
26599,
22,
3340,
7695,
4063,
1535,
203,
683,
9454,
18035,
560,
374,
18,
26,
18,
2163,
31,
203,
5666,
288,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
289,
628,
8787,
318,
291,
91,
438,
19,
90,
22,
17,
457,
16045,
627,
19,
16351,
87,
19,
15898,
19,
45,
984,
291,
91,
438,
58,
22,
8259,
3103,
18,
18281,
14432,
203,
5666,
288,
467,
654,
39,
3462,
289,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
2316,
19,
654,
39,
3462,
19,
45,
654,
39,
3462,
18,
18281,
14432,
203,
5666,
288,
14060,
654,
39,
3462,
289,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
2316,
19,
654,
39,
3462,
19,
9890,
654,
39,
3462,
18,
18281,
14432,
203,
5666,
288,
14060,
10477,
289,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
15949,
19,
9890,
10477,
18,
18281,
14432,
203,
5666,
288,
467,
9423,
19278,
289,
628,
315,
6216,
15898,
19,
9375,
19,
45,
9423,
19278,
18,
18281,
14432,
203,
5666,
288,
467,
9423,
1887,
2249,
289,
628,
315,
6216,
15898,
19,
9375,
19,
45,
9423,
1887,
2249,
18,
18281,
14432,
203,
5666,
288,
467,
9423,
2864,
4243,
289,
628,
315,
6216,
15898,
19,
9375,
19,
45,
9423,
2864,
4243,
18,
18281,
14432,
203,
5666,
288,
467,
9423,
2864,
289,
628,
315,
6216,
15898,
19,
9375,
19,
45,
9423,
2864,
18,
18281,
14432,
203,
5666,
288,
4437,
91,
438,
8259,
97,
628,
315,
6216,
15898,
19,
9375,
19,
5127,
91,
438,
8259,
18,
18281,
14432,
203,
5666,
288,
467,
7678,
264,
289,
628,
315,
6216,
15898,
19,
45,
7678,
264,
18,
18281,
14432,
203,
5666,
288,
467,
59,
1584,
44,
289,
628,
315,
6216,
15898,
19,
45,
59,
1584,
44,
18,
18281,
14432,
203,
5666,
288,
2962,
30708,
2802,
10477,
289,
628,
315,
6216,
2941,
19,
1386,
30708,
2802,
10477,
18,
18281,
14432,
203,
565,
2792,
18903,
288,
599,
16,
19884,
22270,
16,
348,
1218,
291,
91,
438,
16,
1351,
77,
58,
23,
16,
22901,
289,
203,
565,
1958,
23443,
288,
203,
3639,
1758,
9549,
8259,
31,
203,
3639,
1758,
272,
1218,
77,
8259,
31,
203,
3639,
1758,
7738,
58,
23,
8259,
31,
203,
3639,
1758,
7738,
58,
23,
7678,
264,
31,
203,
3639,
1758,
8882,
1887,
2249,
31,
203,
3639,
1758,
8882,
19278,
31,
203,
3639,
1758,
341,
546,
31,
203,
565,
289,
203,
203,
565,
1958,
12738,
751,
288,
203,
3639,
1758,
8526,
589,
31,
203,
3639,
2254,
3247,
8526,
1656,
281,
31,
203,
3639,
1758,
2845,
31,
203,
3639,
18903,
7829,
31,
203,
565,
289,
203,
203,
565,
1958,
22901,
2864,
751,
288,
203,
3639,
509,
10392,
290,
39,
9896,
31,
203,
3639,
2254,
5034,
63,
28,
65,
324,
26488,
31,
203,
3639,
2254,
5034,
432,
31,
203,
3639,
2254,
5034,
14036,
31,
203,
3639,
2254,
5034,
63,
28,
65,
17544,
31,
203,
3639,
2254,
5034,
63,
28,
65,
15105,
31,
203,
565,
289,
203,
203,
565,
445,
7720,
14332,
5157,
1290,
5157,
12,
203,
3639,
23443,
3778,
389,
13277,
16,
203,
3639,
2254,
5034,
389,
8949,
382,
16,
203,
3639,
2254,
5034,
389,
1154,
6275,
1182,
16,
203,
3639,
12738,
751,
3778,
389,
22270,
751,
203,
565,
262,
203,
3639,
3903,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
309,
261,
67,
22270,
751,
18,
803,
63,
20,
65,
422,
389,
22270,
751,
18,
803,
63,
67,
22270,
751,
18,
803,
18,
2469,
300,
21,
5717,
288,
203,
5411,
327,
389,
8949,
382,
31,
203,
3639,
289,
203,
203,
3639,
309,
24899,
22270,
751,
18,
16641,
422,
18903,
18,
9423,
15329,
203,
5411,
327,
389,
22270,
14332,
5157,
1290,
5157,
9423,
12,
203,
7734,
389,
22270,
751,
18,
803,
16,
203,
7734,
389,
22270,
751,
18,
6011,
16,
203,
7734,
389,
8949,
382,
16,
203,
7734,
389,
1154,
6275,
1182,
16,
203,
7734,
389,
13277,
203,
5411,
11272,
203,
3639,
289,
203,
3639,
309,
24899,
22270,
751,
18,
16641,
631,
18903,
18,
984,
77,
58,
23,
15329,
203,
5411,
327,
389,
22270,
14332,
5157,
1290,
5157,
984,
77,
58,
23,
12,
203,
7734,
389,
22270,
751,
18,
803,
16,
203,
7734,
389,
22270,
751,
18,
3030,
281,
16,
203,
7734,
389,
8949,
382,
16,
203,
7734,
389,
1154,
6275,
1182,
16,
203,
7734,
4437,
91,
438,
8259,
24899,
13277,
18,
318,
77,
58,
23,
8259,
13,
203,
5411,
11272,
203,
5411,
327,
389,
22270,
14332,
5157,
1290,
5157,
984,
77,
58,
22,
12,
203,
7734,
389,
22270,
751,
18,
803,
16,
203,
7734,
389,
8949,
382,
16,
203,
7734,
389,
1154,
6275,
1182,
16,
203,
7734,
389,
588,
8259,
24899,
22270,
751,
18,
16641,
16,
389,
13277,
13,
203,
5411,
11272,
203,
3639,
289,
203,
565,
289,
203,
203,
203,
565,
445,
7720,
14332,
5157,
1290,
5157,
12,
203,
3639,
23443,
3778,
389,
13277,
16,
203,
3639,
2254,
5034,
389,
8949,
382,
16,
203,
3639,
2254,
5034,
389,
1154,
6275,
1182,
16,
203,
3639,
12738,
751,
3778,
389,
22270,
751,
203,
565,
262,
203,
3639,
3903,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
309,
261,
67,
22270,
751,
18,
803,
63,
20,
65,
422,
389,
22270,
751,
18,
803,
63,
67,
22270,
751,
18,
803,
18,
2469,
300,
21,
5717,
288,
203,
5411,
327,
389,
8949,
382,
31,
203,
3639,
289,
203,
203,
3639,
309,
24899,
22270,
751,
18,
16641,
422,
18903,
18,
9423,
2
] |
./full_match/421613/0xD08Ab99480d02bf9C092828043f611BcDFEA917b/sources/src/libraries/SortitionSumTreeFactoryV2.sol | * @dev Create a sortition sum tree at the specified key. @param _key The key of the new tree. @param _K The number of children each node in the tree should have./ | function createTree(SortitionSumTrees storage self, bytes32 _key, uint256 _K) external {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
require(tree.K == 0, "Tree already exists.");
require(_K > 1, "K must be greater than one.");
tree.K = _K;
tree.nodes.push(0);
}
| 11,568,855 | [
1,
4625,
348,
7953,
560,
30,
380,
225,
632,
5206,
1788,
279,
1524,
608,
2142,
2151,
622,
326,
1269,
498,
18,
225,
632,
891,
389,
856,
1021,
498,
434,
326,
394,
2151,
18,
225,
632,
891,
389,
47,
1021,
1300,
434,
2325,
1517,
756,
316,
326,
2151,
1410,
1240,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2471,
12,
4416,
608,
3495,
26590,
2502,
365,
16,
1731,
1578,
389,
856,
16,
2254,
5034,
389,
47,
13,
3903,
288,
203,
3639,
5928,
608,
3495,
2471,
2502,
2151,
273,
365,
18,
3804,
608,
3495,
26590,
63,
67,
856,
15533,
203,
3639,
2583,
12,
3413,
18,
47,
422,
374,
16,
315,
2471,
1818,
1704,
1199,
1769,
203,
3639,
2583,
24899,
47,
405,
404,
16,
315,
47,
1297,
506,
6802,
2353,
1245,
1199,
1769,
203,
3639,
2151,
18,
47,
273,
389,
47,
31,
203,
3639,
2151,
18,
4690,
18,
6206,
12,
20,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.9;
import "./DelightBuildingManagerInterface.sol";
import "./DelightManager.sol";
import "./DelightArmyManager.sol";
import "./DelightItemManager.sol";
import "./Util/SafeMath.sol";
contract DelightBuildingManager is DelightBuildingManagerInterface, DelightManager {
using SafeMath for uint;
// Delight army manager
// Delight 부대 관리자
DelightArmyManager private armyManager;
// Delight item manager
// Delight 아이템 관리자
DelightItemManager private itemManager;
function setDelightArmyManagerOnce(address addr) external {
// The address has to be empty.
// 비어있는 주소인 경우에만
require(address(armyManager) == address(0));
armyManager = DelightArmyManager(addr);
}
function setDelightItemManagerOnce(address addr) external {
// The address has to be empty.
// 비어있는 주소인 경우에만
require(address(itemManager) == address(0));
itemManager = DelightItemManager(addr);
}
// Executes only if the sender is Delight.
// Sender가 Delight일때만 실행
modifier onlyDelight() {
require(
msg.sender == delight ||
msg.sender == address(armyManager) ||
msg.sender == address(itemManager)
);
_;
}
Building[] private buildings;
constructor(
DelightInfoInterface info,
DelightResource wood,
DelightResource stone,
DelightResource iron,
DelightResource ducat
) DelightManager(info, wood, stone, iron, ducat) public {
// Address 0 is not used.
// 0번지는 사용하지 않습니다.
buildings.push(Building({
kind : 99,
level : 0,
col : COL_RANGE,
row : ROW_RANGE,
owner : address(0),
buildTime : 0
}));
}
mapping(uint => mapping(uint => uint)) private positionToBuildingId;
mapping(address => uint[]) private ownerToHQIds;
// Returns the total number of buildings.
// 건물의 총 개수를 반환합니다.
function getBuildingCount() view external returns (uint) {
return buildings.length;
}
// Returns the information of a building.
// 건물의 정보를 반환합니다.
function getBuildingInfo(uint buildingId) view external returns (
uint kind,
uint level,
uint col,
uint row,
address owner,
uint buildTime
) {
Building memory building = buildings[buildingId];
return (
building.kind,
building.level,
building.col,
building.row,
building.owner,
building.buildTime
);
}
// Returns the IDs of the buildings located on a specific tile.
// 특정 위치의 건물 ID를 반환합니다.
function getPositionBuildingId(uint col, uint row) view external returns (uint) {
return positionToBuildingId[col][row];
}
// Returns the owners of the buildings located on a specific tile.
// 특정 위치의 건물의 주인을 반환합니다.
function getPositionBuildingOwner(uint col, uint row) view external returns (address) {
return buildings[positionToBuildingId[col][row]].owner;
}
// 소유주의 본부 ID들을 반환합니다.
function getOwnerHQIds(address owner) view external returns (uint[] memory) {
return ownerToHQIds[owner];
}
// 특정 위치의 건물의 버프 HP를 반환합니다.
function getBuildingBuffHP(uint col, uint row) view external returns (uint) {
uint buildingId = positionToBuildingId[col][row];
if (buildingId != 0) {
// 탑인 경우 버프 HP는 20
if (buildings[buildingId].kind == BUILDING_TOWER) {
return 20;
}
}
return 0;
}
// 특정 위치의 건물의 버프 데미지를 반환합니다.
function getBuildingBuffDamage(uint col, uint row) view external returns (uint) {
uint buildingId = positionToBuildingId[col][row];
if (buildingId != 0) {
// 탑인 경우 버프 데미지는 20
if (buildings[buildingId].kind == BUILDING_TOWER) {
return 20;
}
}
return 0;
}
// Builds a building.
// 건물을 짓습니다.
function build(address owner, uint kind, uint col, uint row) onlyDelight external {
// Checks the dimension.
// 범위를 체크합니다.
require(col < COL_RANGE && row < ROW_RANGE);
// There should be no building on the construction site.
// 필드에 건물이 존재하면 안됩니다.
require(positionToBuildingId[col][row] == 0);
address positionOwner = armyManager.getPositionOwner(col, row);
// There should be no enemy on the construction site.
// 필드에 적군이 존재하면 안됩니다.
require(positionOwner == address(0) || positionOwner == owner);
// Checks if a headquarter is near the construction site.
// 본부가 주변에 존재하는지 확인합니다.
bool existsHQAround = false;
for (uint i = 0; i < ownerToHQIds[owner].length; i += 1) {
Building memory building = buildings[ownerToHQIds[owner][i]];
uint hqCol = building.col;
uint hqRow = building.row;
if (
(col < hqCol ? hqCol - col : col - hqCol) +
(row < hqRow ? hqRow - row : row - hqRow) <= 3 + building.level.mul(2)
) {
existsHQAround = true;
break;
}
}
require(
// Checks if a headquarter is near the construction site.
// 본부가 주변에 존재하는지 확인합니다.
existsHQAround == true ||
// An HQ can be built even when there's no other HQ in the world, or where the builder's units are.
// 본부인 경우, 월드에 본부가 아예 없거나, 내 병사가 있는 위치에 지을 수 있습니다.
(kind == BUILDING_HQ && (ownerToHQIds[owner].length == 0 || positionOwner == owner))
);
// 만약 월드에 본부가 아예 없는 경우, 처음 짓는 곳 주변에 적군의 건물이 존재하면 안됩니다.
if (ownerToHQIds[owner].length == 0) {
for (uint i = (col <= 3 ? 0 : col - 3); i <= (col >= 96 ? 99 : col + 3); i += 1) {
for (uint j = (row <= 3 ? 0 : row - 3); j <= (row >= 96 ? 99 : row + 3); j += 1) {
require(positionToBuildingId[i][j] == 0 || buildings[positionToBuildingId[i][j]].owner == owner);
}
}
}
// Checks if there are enough resources to build the building.
// 건물을 짓는데 필요한 자원이 충분한지 확인합니다.
require(
wood.balanceOf(owner) >= info.getBuildingMaterialWood(kind) &&
stone.balanceOf(owner) >= info.getBuildingMaterialStone(kind) &&
iron.balanceOf(owner) >= info.getBuildingMaterialIron(kind) &&
ducat.balanceOf(owner) >= info.getBuildingMaterialDucat(kind)
);
uint buildingId = buildings.push(Building({
kind : kind,
level : 0,
col : col,
row : row,
owner : owner,
buildTime : now
})).sub(1);
positionToBuildingId[col][row] = buildingId;
if (kind == BUILDING_HQ) {
ownerToHQIds[owner].push(buildingId);
}
// Transfers the resources to Delight.
// 자원을 Delight로 이전합니다.
wood.transferFrom(owner, delight, info.getBuildingMaterialWood(kind));
stone.transferFrom(owner, delight, info.getBuildingMaterialStone(kind));
iron.transferFrom(owner, delight, info.getBuildingMaterialIron(kind));
ducat.transferFrom(owner, delight, info.getBuildingMaterialDucat(kind));
// Emits the event.
// 이벤트 발생
emit Build(buildingId);
}
// Upgrades an HQ.
// 본부를 업그레이드합니다.
function upgradeHQ(address owner, uint buildingId) onlyDelight external {
Building storage building = buildings[buildingId];
require(building.kind == BUILDING_HQ);
// Only the owner of the HQ can upgrade it.
// 건물 소유주만 업그레이드가 가능합니다.
require(building.owner == owner);
// The maximum level is 2.
// 최대 레벨은 2입니다. (0 ~ 2)
require(building.level < 2);
uint toLevel = building.level + 1;
// Checks if there are enough resources to upgrade the HQ.
// 본부를 업그레이드하는데 필요한 자원이 충분한지 확인합니다.
require(
wood.balanceOf(owner) >= info.getHQUpgradeMaterialWood(toLevel) &&
stone.balanceOf(owner) >= info.getHQUpgradeMaterialStone(toLevel) &&
iron.balanceOf(owner) >= info.getHQUpgradeMaterialIron(toLevel) &&
ducat.balanceOf(owner) >= info.getHQUpgradeMaterialDucat(toLevel)
);
// Transfers resources to Delight.
// 자원을 Delight로 이전합니다.
wood.transferFrom(owner, delight, info.getHQUpgradeMaterialWood(toLevel));
stone.transferFrom(owner, delight, info.getHQUpgradeMaterialStone(toLevel));
iron.transferFrom(owner, delight, info.getHQUpgradeMaterialIron(toLevel));
ducat.transferFrom(owner, delight, info.getHQUpgradeMaterialDucat(toLevel));
building.level = toLevel;
// Emits the event.
// 이벤트 발생
emit UpgradeHQ(buildingId);
}
// Creates an army from the building.
// 건물에서 부대를 생산합니다.
function createArmy(address owner, uint buildingId, uint unitCount) onlyDelight external {
Building memory building = buildings[buildingId];
// Only the owner of the building can create an army from it.
// 건물 소유주만 부대 생산이 가능합니다.
require(building.owner == owner);
uint unitKind;
// A hq creates knights.
// 본부의 경우 기사를 생산합니다.
if (building.kind == BUILDING_HQ) {
unitKind = UNIT_KNIGHT;
}
// A training center creates swordsmen.
// 훈련소의 경우 검병을 생산합니다.
else if (building.kind == BUILDING_TRAINING_CENTER) {
unitKind = UNIT_SWORDSMAN;
}
// An achery range creates archers.
// 사격소의 경우 궁수를 생산합니다.
else if (building.kind == BUILDING_ARCHERY_RANGE) {
unitKind = UNIT_ARCHER;
}
// A stable creates cavalry.
// 마굿간의 경우 기마병을 생산합니다.
else if (building.kind == BUILDING_STABLE) {
unitKind = UNIT_CAVALY;
}
else {
revert();
}
// Creates the army.
// 부대를 생산합니다.
armyManager.createArmy(owner, building.col, building.row, unitKind, unitCount);
}
// Destory the building on a specific tile.
// 특정 위치의 건물을 파괴합니다.
function destroyBuilding(uint col, uint row) onlyDelight external returns (
uint wood,
uint stone,
uint iron,
uint ducat
) {
uint buildingId = positionToBuildingId[col][row];
// The building must exist.
// 존재하는 건물이어야 합니다.
if (buildingId != 0) {
Building memory building = buildings[buildingId];
uint buildingKind = building.kind;
// If it's an HQ, it is removed from the HQ list.
// 본부인 경우, 본부 목록에서 제거합니다.
if (buildingKind == BUILDING_HQ) {
uint[] storage hqIds = ownerToHQIds[building.owner];
for (uint i = 0; i < hqIds.length - 1; i += 1) {
if (hqIds[i] == buildingId) {
for (; i < hqIds.length - 1; i += 1) {
hqIds[i] = hqIds[i + 1];
}
break;
}
}
hqIds.length -= 1;
// Returns the upgrade cost of the HQ.
// 본부 업그레이드 비용을 반환합니다.
for (uint i = 1; i <= building.level; i += 1) {
// Adds the returned material.
// 반환할 재료를 추가합니다.
wood = wood.add(info.getHQUpgradeMaterialWood(i));
stone = stone.add(info.getHQUpgradeMaterialStone(i));
iron = iron.add(info.getHQUpgradeMaterialIron(i));
ducat = ducat.add(info.getHQUpgradeMaterialDucat(i));
}
}
// Adds the returned material.
// 반환할 재료를 추가합니다.
wood = wood.add(info.getBuildingMaterialWood(buildingKind));
stone = stone.add(info.getBuildingMaterialStone(buildingKind));
iron = iron.add(info.getBuildingMaterialIron(buildingKind));
ducat = ducat.add(info.getBuildingMaterialDucat(buildingKind));
// Destroys the building.
// 건물을 파괴합니다.
delete buildings[buildingId];
delete positionToBuildingId[col][row];
// Emits the event.
// 이벤트 발생
emit DestroyBuilding(buildingId);
}
}
}
| Returns the owners of the buildings located on a specific tile. 특정 위치의 건물의 주인을 반환합니다. | function getPositionBuildingOwner(uint col, uint row) view external returns (address) {
return buildings[positionToBuildingId[col][row]].owner;
}
| 1,027,468 | [
1,
4625,
348,
7953,
560,
30,
225,
2860,
326,
25937,
434,
326,
1361,
899,
13801,
603,
279,
2923,
4769,
18,
225,
174,
237,
122,
173,
259,
248,
225,
173,
255,
231,
173,
122,
251,
173,
256,
251,
225,
171,
114,
117,
172,
110,
125,
173,
256,
251,
225,
173,
101,
125,
173,
256,
121,
173,
256,
231,
225,
172,
113,
251,
174,
252,
251,
174,
248,
107,
172,
238,
235,
172,
238,
102,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
14441,
16713,
5541,
12,
11890,
645,
16,
2254,
1027,
13,
1476,
3903,
1135,
261,
2867,
13,
288,
203,
202,
202,
2463,
1361,
899,
63,
3276,
774,
16713,
548,
63,
1293,
6362,
492,
65,
8009,
8443,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
import "@chainlink/contracts/src/v0.6/ChainlinkClient.sol";
import "@chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol";
import '@openzeppelin/contracts/access/Ownable.sol';
import "./IMobilityCampaigns.sol";
/**
* @title AdzerkAdClient creates an ad campaigns from a given ad server API
*/
contract AdzerkAdClient is ChainlinkClient, Ownable {
struct AdRequest {
address creator;
string campaignName;
uint budgetETH;
}
address public oracleAddress;
address public linkTokenAddress;
IMobilityCampaigns public mobilityCampaigns;
mapping(address => bool) public advertisers;
mapping(address => uint) public advertisersPaymentsLINK;
mapping(bytes32 => AdRequest) public adRequests;
modifier onlyAdvertiser() {
require(advertisers[msg.sender], 'AdzerkAdClient::onlyAdvertiser::msg.sender must have requested an ad import');
_;
}
/**
* @notice Deploy the contract with a specified address for the LINK
* and Oracle contract addresses
* @dev Sets the storage for the specified addresses
* @param _link The address of the LINK token contract
*/
constructor(address _link, address _oracle, address _campaignsContractAddress) public {
oracleAddress = _oracle;
mobilityCampaigns = IMobilityCampaigns(_campaignsContractAddress);
if (_link == address(0)) {
setPublicChainlinkToken();
linkTokenAddress = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571; // ChainlinkClient::LINK_TOKEN_POINTER
} else {
setChainlinkToken(_link);
linkTokenAddress = _link;
}
}
function setOracleAddress(address _oracle) external onlyOwner {
require(_oracle != address(0), 'AdzerkAdClient::setOracleAddress::_oracle cannot be 0 address');
oracleAddress = _oracle;
}
/**
* @notice Returns the address of the LINK token
* @dev This is the public implementation for chainlinkTokenAddress, which is
* an internal method of the ChainlinkClient contract
*/
function getChainlinkToken() public view returns (address) {
return chainlinkTokenAddress();
}
/*
* Allows an advertisers to import ads from their custom ad server
* NOTE: the address must have already approved the transfer of LINK with linkToken.approve()
* @param _jobId The bytes32 JobID to be executed
* @param _paymentLINK The payment in LINK for the request
* @param _apiURL The ad server URL to request data from
* @param _apiToken The ad server api auth token
* @param _pathCampaignName The dot-delimited path of top-level campaign name (response.data.campaign_name)
* @param _pathCampaignAdCount The number of ad creatives under the given campaign path (response.data.ads.length)
* @param _pathCampaignAdImage The dot-delimited path of ad creative images (response.data.ads[0].image_url)
*/
function importAds(
bytes32 _jobId,
uint256 _paymentLINK,
uint8 _pathCampaignAdCount,
string memory _apiURL,
string memory _campaignName,
string memory _pathCampaignAdImage
)
public
payable
returns (bytes32[] memory requestIds)
{
advertisersPaymentsLINK[msg.sender] = _paymentLINK;
// transfer required LINK tokens to this contract
require(LinkTokenInterface(linkTokenAddress).transferFrom(msg.sender, address(this), _paymentLINK));
// assert budget
require(msg.value > 0, 'AdzerkAdClient::importAds::msg.value must be greater than 0');
// split LINK evenly between requests
uint256 amountperAdLINK = _paymentLINK / _pathCampaignAdCount;
uint256 amountperAdETH = msg.value / _pathCampaignAdCount;
requestIds = new bytes32[](_pathCampaignAdCount);
for (uint8 i = 0; i < _pathCampaignAdCount; i++) {
Chainlink.Request memory req = buildChainlinkRequest(_jobId, address(this), this.fulfillImportAds.selector);
req.add("get", _apiURL);
// req.add("headers", "{\'X-Adzerk-ApiKey\':\'_apiToken\'}");
string[] memory path = new string[](2);
path[0] = "foo"; // @TODO: trying to access object at array index
path[1] = _pathCampaignAdImage;
req.addStringArray("path", path);
bytes32 requestId = sendChainlinkRequestTo(oracleAddress, req, amountperAdLINK);
adRequests[requestId] = AdRequest({
creator: msg.sender,
campaignName: _campaignName,
budgetETH: amountperAdETH
});
requestIds[i] = requestId;
}
return requestIds;
}
/**
* @notice The fulfill method from requests created by this contract
* @dev The recordChainlinkFulfillment protects this function from being called
* by anyone other than the oracle address that the request was sent to
* @param _requestId The ID that was generated for the request
* @param _data The answer provided by the oracle
*/
function fulfillImportAds(bytes32 _requestId, string memory _data)
public
recordChainlinkFulfillment(_requestId)
{
AdRequest memory request = adRequests[_requestId];
mobilityCampaigns.createCampaignImported(
request.creator,
request.campaignName,
_data
);
}
/**
* @notice Allows the owner to withdraw any LINK balance on the contract
*/
function withdrawLink() public onlyAdvertiser {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
require(link.transfer(msg.sender, advertisersPaymentsLINK[msg.sender]), "AdzerkAdClient::withdrawLink::Unable to transfer");
}
/**
* @notice Call this method if no response is received within 5 minutes
* @param _requestId The ID that was generated for the request to cancel
* @param _payment The payment specified for the request to cancel
* @param _callbackFunctionId The bytes4 callback function ID specified for
* the request to cancel
* @param _expiration The expiration generated for the request to cancel
*/
function cancelRequest(
bytes32 _requestId,
uint256 _payment,
bytes4 _callbackFunctionId,
uint256 _expiration
)
public
onlyAdvertiser
{
require(adRequests[_requestId].creator == msg.sender, 'AdzerkAdClient::cancelRequest::only request creator');
cancelChainlinkRequest(_requestId, _payment, _callbackFunctionId, _expiration);
}
}
| * @notice Allows the owner to withdraw any LINK balance on the contract/ | function withdrawLink() public onlyAdvertiser {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
require(link.transfer(msg.sender, advertisersPaymentsLINK[msg.sender]), "AdzerkAdClient::withdrawLink::Unable to transfer");
}
| 6,465,344 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
20392,
25619,
326,
3410,
358,
598,
9446,
1281,
22926,
11013,
603,
326,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
598,
9446,
2098,
1435,
1071,
1338,
1871,
1097,
15914,
288,
203,
565,
4048,
1345,
1358,
1692,
273,
4048,
1345,
1358,
12,
5639,
1232,
1345,
1887,
10663,
203,
565,
2583,
12,
1232,
18,
13866,
12,
3576,
18,
15330,
16,
16738,
291,
414,
23725,
10554,
63,
3576,
18,
15330,
65,
3631,
315,
1871,
24355,
79,
1871,
1227,
2866,
1918,
9446,
2098,
2866,
3370,
358,
7412,
8863,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDispatcher Interface
/// @author Enzyme Council <[email protected]>
interface IDispatcher {
function cancelMigration(address _vaultProxy, bool _bypassFailure) external;
function claimOwnership() external;
function deployVaultProxy(
address _vaultLib,
address _owner,
address _vaultAccessor,
string calldata _fundName
) external returns (address vaultProxy_);
function executeMigration(address _vaultProxy, bool _bypassFailure) external;
function getCurrentFundDeployer() external view returns (address currentFundDeployer_);
function getFundDeployerForVaultProxy(address _vaultProxy)
external
view
returns (address fundDeployer_);
function getMigrationRequestDetailsForVaultProxy(address _vaultProxy)
external
view
returns (
address nextFundDeployer_,
address nextVaultAccessor_,
address nextVaultLib_,
uint256 executableTimestamp_
);
function getMigrationTimelock() external view returns (uint256 migrationTimelock_);
function getNominatedOwner() external view returns (address nominatedOwner_);
function getOwner() external view returns (address owner_);
function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_);
function getTimelockRemainingForMigrationRequest(address _vaultProxy)
external
view
returns (uint256 secondsRemaining_);
function hasExecutableMigrationRequest(address _vaultProxy)
external
view
returns (bool hasExecutableRequest_);
function hasMigrationRequest(address _vaultProxy)
external
view
returns (bool hasMigrationRequest_);
function removeNominatedOwner() external;
function setCurrentFundDeployer(address _nextFundDeployer) external;
function setMigrationTimelock(uint256 _nextTimelock) external;
function setNominatedOwner(address _nextNominatedOwner) external;
function setSharesTokenSymbol(string calldata _nextSymbol) external;
function signalMigration(
address _vaultProxy,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExternalPosition Contract
/// @author Enzyme Council <[email protected]>
interface IExternalPosition {
function getDebtAssets() external returns (address[] memory, uint256[] memory);
function getManagedAssets() external returns (address[] memory, uint256[] memory);
function init(bytes memory) external;
function receiveCallFromVault(bytes memory) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExternalPositionVault interface
/// @author Enzyme Council <[email protected]>
/// Provides an interface to get the externalPositionLib for a given type from the Vault
interface IExternalPositionVault {
function getExternalPositionLibForType(uint256) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFreelyTransferableSharesVault Interface
/// @author Enzyme Council <[email protected]>
/// @notice Provides the interface for determining whether a vault's shares
/// are guaranteed to be freely transferable.
/// @dev DO NOT EDIT CONTRACT
interface IFreelyTransferableSharesVault {
function sharesAreFreelyTransferable()
external
view
returns (bool sharesAreFreelyTransferable_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IMigratableVault Interface
/// @author Enzyme Council <[email protected]>
/// @dev DO NOT EDIT CONTRACT
interface IMigratableVault {
function canMigrate(address _who) external view returns (bool canMigrate_);
function init(
address _owner,
address _accessor,
string calldata _fundName
) external;
function setAccessor(address _nextAccessor) external;
function setVaultLib(address _nextVaultLib) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFundDeployer Interface
/// @author Enzyme Council <[email protected]>
interface IFundDeployer {
function getOwner() external view returns (address);
function hasReconfigurationRequest(address) external view returns (bool);
function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool);
function isAllowedVaultCall(
address,
bytes4,
bytes32
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../persistent/dispatcher/IDispatcher.sol";
import "../../../../persistent/external-positions/IExternalPosition.sol";
import "../../../extensions/IExtension.sol";
import "../../../extensions/fee-manager/IFeeManager.sol";
import "../../../extensions/policy-manager/IPolicyManager.sol";
import "../../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol";
import "../../../infrastructure/gas-relayer/IGasRelayPaymaster.sol";
import "../../../infrastructure/gas-relayer/IGasRelayPaymasterDepositor.sol";
import "../../../infrastructure/value-interpreter/IValueInterpreter.sol";
import "../../../utils/beacon-proxy/IBeaconProxyFactory.sol";
import "../../../utils/AddressArrayLib.sol";
import "../../fund-deployer/IFundDeployer.sol";
import "../vault/IVault.sol";
import "./IComptroller.sol";
/// @title ComptrollerLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice The core logic library shared by all funds
contract ComptrollerLib is IComptroller, IGasRelayPaymasterDepositor, GasRelayRecipientMixin {
using AddressArrayLib for address[];
using SafeMath for uint256;
using SafeERC20 for ERC20;
event AutoProtocolFeeSharesBuybackSet(bool autoProtocolFeeSharesBuyback);
event BuyBackMaxProtocolFeeSharesFailed(
bytes indexed failureReturnData,
uint256 sharesAmount,
uint256 buybackValueInMln,
uint256 gav
);
event DeactivateFeeManagerFailed();
event GasRelayPaymasterSet(address gasRelayPaymaster);
event MigratedSharesDuePaid(uint256 sharesDue);
event PayProtocolFeeDuringDestructFailed();
event PreRedeemSharesHookFailed(
bytes indexed failureReturnData,
address indexed redeemer,
uint256 sharesAmount
);
event RedeemSharesInKindCalcGavFailed();
event SharesBought(
address indexed buyer,
uint256 investmentAmount,
uint256 sharesIssued,
uint256 sharesReceived
);
event SharesRedeemed(
address indexed redeemer,
address indexed recipient,
uint256 sharesAmount,
address[] receivedAssets,
uint256[] receivedAssetAmounts
);
event VaultProxySet(address vaultProxy);
// Constants and immutables - shared by all proxies
uint256 private constant ONE_HUNDRED_PERCENT = 10000;
uint256 private constant SHARES_UNIT = 10**18;
address
private constant SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS = 0x000000000000000000000000000000000000aaaa;
address private immutable DISPATCHER;
address private immutable EXTERNAL_POSITION_MANAGER;
address private immutable FUND_DEPLOYER;
address private immutable FEE_MANAGER;
address private immutable INTEGRATION_MANAGER;
address private immutable MLN_TOKEN;
address private immutable POLICY_MANAGER;
address private immutable PROTOCOL_FEE_RESERVE;
address private immutable VALUE_INTERPRETER;
address private immutable WETH_TOKEN;
// Pseudo-constants (can only be set once)
address internal denominationAsset;
address internal vaultProxy;
// True only for the one non-proxy
bool internal isLib;
// Storage
// Attempts to buy back protocol fee shares immediately after collection
bool internal autoProtocolFeeSharesBuyback;
// A reverse-mutex, granting atomic permission for particular contracts to make vault calls
bool internal permissionedVaultActionAllowed;
// A mutex to protect against reentrancy
bool internal reentranceLocked;
// A timelock after the last time shares were bought for an account
// that must expire before that account transfers or redeems their shares
uint256 internal sharesActionTimelock;
mapping(address => uint256) internal acctToLastSharesBoughtTimestamp;
// The contract which manages paying gas relayers
address private gasRelayPaymaster;
///////////////
// MODIFIERS //
///////////////
modifier allowsPermissionedVaultAction {
__assertPermissionedVaultActionNotAllowed();
permissionedVaultActionAllowed = true;
_;
permissionedVaultActionAllowed = false;
}
modifier locksReentrance() {
__assertNotReentranceLocked();
reentranceLocked = true;
_;
reentranceLocked = false;
}
modifier onlyFundDeployer() {
__assertIsFundDeployer();
_;
}
modifier onlyGasRelayPaymaster() {
__assertIsGasRelayPaymaster();
_;
}
modifier onlyOwner() {
__assertIsOwner(__msgSender());
_;
}
modifier onlyOwnerNotRelayable() {
__assertIsOwner(msg.sender);
_;
}
// ASSERTION HELPERS
// Modifiers are inefficient in terms of contract size,
// so we use helper functions to prevent repetitive inlining of expensive string values.
function __assertIsFundDeployer() private view {
require(msg.sender == getFundDeployer(), "Only FundDeployer callable");
}
function __assertIsGasRelayPaymaster() private view {
require(msg.sender == getGasRelayPaymaster(), "Only Gas Relay Paymaster callable");
}
function __assertIsOwner(address _who) private view {
require(_who == IVault(getVaultProxy()).getOwner(), "Only fund owner callable");
}
function __assertNotReentranceLocked() private view {
require(!reentranceLocked, "Re-entrance");
}
function __assertPermissionedVaultActionNotAllowed() private view {
require(!permissionedVaultActionAllowed, "Vault action re-entrance");
}
function __assertSharesActionNotTimelocked(address _vaultProxy, address _account)
private
view
{
uint256 lastSharesBoughtTimestamp = getLastSharesBoughtTimestampForAccount(_account);
require(
lastSharesBoughtTimestamp == 0 ||
block.timestamp.sub(lastSharesBoughtTimestamp) >= getSharesActionTimelock() ||
__hasPendingMigrationOrReconfiguration(_vaultProxy),
"Shares action timelocked"
);
}
constructor(
address _dispatcher,
address _protocolFeeReserve,
address _fundDeployer,
address _valueInterpreter,
address _externalPositionManager,
address _feeManager,
address _integrationManager,
address _policyManager,
address _gasRelayPaymasterFactory,
address _mlnToken,
address _wethToken
) public GasRelayRecipientMixin(_gasRelayPaymasterFactory) {
DISPATCHER = _dispatcher;
EXTERNAL_POSITION_MANAGER = _externalPositionManager;
FEE_MANAGER = _feeManager;
FUND_DEPLOYER = _fundDeployer;
INTEGRATION_MANAGER = _integrationManager;
MLN_TOKEN = _mlnToken;
POLICY_MANAGER = _policyManager;
PROTOCOL_FEE_RESERVE = _protocolFeeReserve;
VALUE_INTERPRETER = _valueInterpreter;
WETH_TOKEN = _wethToken;
isLib = true;
}
/////////////
// GENERAL //
/////////////
/// @notice Calls a specified action on an Extension
/// @param _extension The Extension contract to call (e.g., FeeManager)
/// @param _actionId An ID representing the action to take on the extension (see extension)
/// @param _callArgs The encoded data for the call
/// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy
/// (for access control). Uses a mutex of sorts that allows "permissioned vault actions"
/// during calls originating from this function.
function callOnExtension(
address _extension,
uint256 _actionId,
bytes calldata _callArgs
) external override locksReentrance allowsPermissionedVaultAction {
require(
_extension == getFeeManager() ||
_extension == getIntegrationManager() ||
_extension == getExternalPositionManager(),
"callOnExtension: _extension invalid"
);
IExtension(_extension).receiveCallFromComptroller(__msgSender(), _actionId, _callArgs);
}
/// @notice Makes an arbitrary call with the VaultProxy contract as the sender
/// @param _contract The contract to call
/// @param _selector The selector to call
/// @param _encodedArgs The encoded arguments for the call
/// @return returnData_ The data returned by the call
function vaultCallOnContract(
address _contract,
bytes4 _selector,
bytes calldata _encodedArgs
) external onlyOwner returns (bytes memory returnData_) {
require(
IFundDeployer(getFundDeployer()).isAllowedVaultCall(
_contract,
_selector,
keccak256(_encodedArgs)
),
"vaultCallOnContract: Not allowed"
);
return
IVault(getVaultProxy()).callOnContract(
_contract,
abi.encodePacked(_selector, _encodedArgs)
);
}
/// @dev Helper to check if a VaultProxy has a pending migration or reconfiguration request
function __hasPendingMigrationOrReconfiguration(address _vaultProxy)
private
view
returns (bool hasPendingMigrationOrReconfiguration)
{
return
IDispatcher(getDispatcher()).hasMigrationRequest(_vaultProxy) ||
IFundDeployer(getFundDeployer()).hasReconfigurationRequest(_vaultProxy);
}
//////////////////
// PROTOCOL FEE //
//////////////////
/// @notice Buys back shares collected as protocol fee at a discounted shares price, using MLN
/// @param _sharesAmount The amount of shares to buy back
function buyBackProtocolFeeShares(uint256 _sharesAmount) external {
address vaultProxyCopy = vaultProxy;
require(
IVault(vaultProxyCopy).canManageAssets(__msgSender()),
"buyBackProtocolFeeShares: Unauthorized"
);
uint256 gav = calcGav();
IVault(vaultProxyCopy).buyBackProtocolFeeShares(
_sharesAmount,
__getBuybackValueInMln(vaultProxyCopy, _sharesAmount, gav),
gav
);
}
/// @notice Sets whether to attempt to buyback protocol fee shares immediately when collected
/// @param _nextAutoProtocolFeeSharesBuyback True if protocol fee shares should be attempted
/// to be bought back immediately when collected
function setAutoProtocolFeeSharesBuyback(bool _nextAutoProtocolFeeSharesBuyback)
external
onlyOwner
{
autoProtocolFeeSharesBuyback = _nextAutoProtocolFeeSharesBuyback;
emit AutoProtocolFeeSharesBuybackSet(_nextAutoProtocolFeeSharesBuyback);
}
/// @dev Helper to buyback the max available protocol fee shares, during an auto-buyback
function __buyBackMaxProtocolFeeShares(address _vaultProxy, uint256 _gav) private {
uint256 sharesAmount = ERC20(_vaultProxy).balanceOf(getProtocolFeeReserve());
uint256 buybackValueInMln = __getBuybackValueInMln(_vaultProxy, sharesAmount, _gav);
try
IVault(_vaultProxy).buyBackProtocolFeeShares(sharesAmount, buybackValueInMln, _gav)
{} catch (bytes memory reason) {
emit BuyBackMaxProtocolFeeSharesFailed(reason, sharesAmount, buybackValueInMln, _gav);
}
}
/// @dev Helper to buyback the max available protocol fee shares
function __getBuybackValueInMln(
address _vaultProxy,
uint256 _sharesAmount,
uint256 _gav
) private returns (uint256 buybackValueInMln_) {
address denominationAssetCopy = getDenominationAsset();
uint256 grossShareValue = __calcGrossShareValue(
_gav,
ERC20(_vaultProxy).totalSupply(),
10**uint256(ERC20(denominationAssetCopy).decimals())
);
uint256 buybackValueInDenominationAsset = grossShareValue.mul(_sharesAmount).div(
SHARES_UNIT
);
return
IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue(
denominationAssetCopy,
buybackValueInDenominationAsset,
getMlnToken()
);
}
////////////////////////////////
// PERMISSIONED VAULT ACTIONS //
////////////////////////////////
/// @notice Makes a permissioned, state-changing call on the VaultProxy contract
/// @param _action The enum representing the VaultAction to perform on the VaultProxy
/// @param _actionData The call data for the action to perform
function permissionedVaultAction(IVault.VaultAction _action, bytes calldata _actionData)
external
override
{
__assertPermissionedVaultAction(msg.sender, _action);
// Validate action as needed
if (_action == IVault.VaultAction.RemoveTrackedAsset) {
require(
abi.decode(_actionData, (address)) != getDenominationAsset(),
"permissionedVaultAction: Cannot untrack denomination asset"
);
}
IVault(getVaultProxy()).receiveValidatedVaultAction(_action, _actionData);
}
/// @dev Helper to assert that a caller is allowed to perform a particular VaultAction.
/// Uses this pattern rather than multiple `require` statements to save on contract size.
function __assertPermissionedVaultAction(address _caller, IVault.VaultAction _action)
private
view
{
bool validAction;
if (permissionedVaultActionAllowed) {
// Calls are roughly ordered by likely frequency
if (_caller == getIntegrationManager()) {
if (
_action == IVault.VaultAction.AddTrackedAsset ||
_action == IVault.VaultAction.RemoveTrackedAsset ||
_action == IVault.VaultAction.WithdrawAssetTo ||
_action == IVault.VaultAction.ApproveAssetSpender
) {
validAction = true;
}
} else if (_caller == getFeeManager()) {
if (
_action == IVault.VaultAction.MintShares ||
_action == IVault.VaultAction.BurnShares ||
_action == IVault.VaultAction.TransferShares
) {
validAction = true;
}
} else if (_caller == getExternalPositionManager()) {
if (
_action == IVault.VaultAction.CallOnExternalPosition ||
_action == IVault.VaultAction.AddExternalPosition ||
_action == IVault.VaultAction.RemoveExternalPosition
) {
validAction = true;
}
}
}
require(validAction, "__assertPermissionedVaultAction: Action not allowed");
}
///////////////
// LIFECYCLE //
///////////////
// Ordered by execution in the lifecycle
/// @notice Initializes a fund with its core config
/// @param _denominationAsset The asset in which the fund's value should be denominated
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @dev Pseudo-constructor per proxy.
/// No need to assert access because this is called atomically on deployment,
/// and once it's called, it cannot be called again.
function init(address _denominationAsset, uint256 _sharesActionTimelock) external override {
require(getDenominationAsset() == address(0), "init: Already initialized");
require(
IValueInterpreter(getValueInterpreter()).isSupportedPrimitiveAsset(_denominationAsset),
"init: Bad denomination asset"
);
denominationAsset = _denominationAsset;
sharesActionTimelock = _sharesActionTimelock;
}
/// @notice Sets the VaultProxy
/// @param _vaultProxy The VaultProxy contract
/// @dev No need to assert anything beyond FundDeployer access.
/// Called atomically with init(), but after ComptrollerProxy has been deployed.
function setVaultProxy(address _vaultProxy) external override onlyFundDeployer {
vaultProxy = _vaultProxy;
emit VaultProxySet(_vaultProxy);
}
/// @notice Runs atomic logic after a ComptrollerProxy has become its vaultProxy's `accessor`
/// @param _isMigration True if a migrated fund is being activated
/// @dev No need to assert anything beyond FundDeployer access.
function activate(bool _isMigration) external override onlyFundDeployer {
address vaultProxyCopy = getVaultProxy();
if (_isMigration) {
// Distribute any shares in the VaultProxy to the fund owner.
// This is a mechanism to ensure that even in the edge case of a fund being unable
// to payout fee shares owed during migration, these shares are not lost.
uint256 sharesDue = ERC20(vaultProxyCopy).balanceOf(vaultProxyCopy);
if (sharesDue > 0) {
IVault(vaultProxyCopy).transferShares(
vaultProxyCopy,
IVault(vaultProxyCopy).getOwner(),
sharesDue
);
emit MigratedSharesDuePaid(sharesDue);
}
}
IVault(vaultProxyCopy).addTrackedAsset(getDenominationAsset());
// Activate extensions
IExtension(getFeeManager()).activateForFund(_isMigration);
IExtension(getPolicyManager()).activateForFund(_isMigration);
}
/// @notice Wind down and destroy a ComptrollerProxy that is active
/// @param _deactivateFeeManagerGasLimit The amount of gas to forward to deactivate the FeeManager
/// @param _payProtocolFeeGasLimit The amount of gas to forward to pay the protocol fee
/// @dev No need to assert anything beyond FundDeployer access.
/// Uses the try/catch pattern throughout out of an abundance of caution for the function's success.
/// All external calls must use limited forwarded gas to ensure that a migration to another release
/// does not get bricked by logic that consumes too much gas for the block limit.
function destructActivated(
uint256 _deactivateFeeManagerGasLimit,
uint256 _payProtocolFeeGasLimit
) external override onlyFundDeployer allowsPermissionedVaultAction {
// Forwarding limited gas here also protects fee recipients by guaranteeing that fee payout logic
// will run in the next function call
try IVault(getVaultProxy()).payProtocolFee{gas: _payProtocolFeeGasLimit}() {} catch {
emit PayProtocolFeeDuringDestructFailed();
}
// Do not attempt to auto-buyback protocol fee shares in this case,
// as the call is gav-dependent and can consume too much gas
// Deactivate extensions only as-necessary
// Pays out shares outstanding for fees
try
IExtension(getFeeManager()).deactivateForFund{gas: _deactivateFeeManagerGasLimit}()
{} catch {
emit DeactivateFeeManagerFailed();
}
__selfDestruct();
}
/// @notice Destroy a ComptrollerProxy that has not been activated
function destructUnactivated() external override onlyFundDeployer {
__selfDestruct();
}
/// @dev Helper to self-destruct the contract.
/// There should never be ETH in the ComptrollerLib,
/// so no need to waste gas to get the fund owner
function __selfDestruct() private {
// Not necessary, but failsafe to protect the lib against selfdestruct
require(!isLib, "__selfDestruct: Only delegate callable");
selfdestruct(payable(address(this)));
}
////////////////
// ACCOUNTING //
////////////////
/// @notice Calculates the gross asset value (GAV) of the fund
/// @return gav_ The fund GAV
function calcGav() public override returns (uint256 gav_) {
address vaultProxyAddress = getVaultProxy();
address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets();
address[] memory externalPositions = IVault(vaultProxyAddress)
.getActiveExternalPositions();
if (assets.length == 0 && externalPositions.length == 0) {
return 0;
}
uint256[] memory balances = new uint256[](assets.length);
for (uint256 i; i < assets.length; i++) {
balances[i] = ERC20(assets[i]).balanceOf(vaultProxyAddress);
}
gav_ = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue(
assets,
balances,
getDenominationAsset()
);
if (externalPositions.length > 0) {
for (uint256 i; i < externalPositions.length; i++) {
uint256 externalPositionValue = __calcExternalPositionValue(externalPositions[i]);
gav_ = gav_.add(externalPositionValue);
}
}
return gav_;
}
/// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset
/// @return grossShareValue_ The amount of the denomination asset per share
/// @dev Does not account for any fees outstanding.
function calcGrossShareValue() external override returns (uint256 grossShareValue_) {
uint256 gav = calcGav();
grossShareValue_ = __calcGrossShareValue(
gav,
ERC20(getVaultProxy()).totalSupply(),
10**uint256(ERC20(getDenominationAsset()).decimals())
);
return grossShareValue_;
}
// @dev Helper for calculating a external position value. Prevents from stack too deep
function __calcExternalPositionValue(address _externalPosition)
private
returns (uint256 value_)
{
(address[] memory managedAssets, uint256[] memory managedAmounts) = IExternalPosition(
_externalPosition
)
.getManagedAssets();
uint256 managedValue = IValueInterpreter(getValueInterpreter())
.calcCanonicalAssetsTotalValue(managedAssets, managedAmounts, getDenominationAsset());
(address[] memory debtAssets, uint256[] memory debtAmounts) = IExternalPosition(
_externalPosition
)
.getDebtAssets();
uint256 debtValue = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue(
debtAssets,
debtAmounts,
getDenominationAsset()
);
if (managedValue > debtValue) {
value_ = managedValue.sub(debtValue);
}
return value_;
}
/// @dev Helper for calculating the gross share value
function __calcGrossShareValue(
uint256 _gav,
uint256 _sharesSupply,
uint256 _denominationAssetUnit
) private pure returns (uint256 grossShareValue_) {
if (_sharesSupply == 0) {
return _denominationAssetUnit;
}
return _gav.mul(SHARES_UNIT).div(_sharesSupply);
}
///////////////////
// PARTICIPATION //
///////////////////
// BUY SHARES
/// @notice Buys shares on behalf of another user
/// @param _buyer The account on behalf of whom to buy shares
/// @param _investmentAmount The amount of the fund's denomination asset with which to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy
/// @return sharesReceived_ The actual amount of shares received
/// @dev This function is freely callable if there is no sharesActionTimelock set, but it is
/// limited to a list of trusted callers otherwise, in order to prevent a griefing attack
/// where the caller buys shares for a _buyer, thereby resetting their lastSharesBought value.
function buySharesOnBehalf(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity
) external returns (uint256 sharesReceived_) {
bool hasSharesActionTimelock = getSharesActionTimelock() > 0;
address canonicalSender = __msgSender();
require(
!hasSharesActionTimelock ||
IFundDeployer(getFundDeployer()).isAllowedBuySharesOnBehalfCaller(canonicalSender),
"buySharesOnBehalf: Unauthorized"
);
return
__buyShares(
_buyer,
_investmentAmount,
_minSharesQuantity,
hasSharesActionTimelock,
canonicalSender
);
}
/// @notice Buys shares
/// @param _investmentAmount The amount of the fund's denomination asset
/// with which to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy
/// @return sharesReceived_ The actual amount of shares received
function buyShares(uint256 _investmentAmount, uint256 _minSharesQuantity)
external
returns (uint256 sharesReceived_)
{
bool hasSharesActionTimelock = getSharesActionTimelock() > 0;
address canonicalSender = __msgSender();
return
__buyShares(
canonicalSender,
_investmentAmount,
_minSharesQuantity,
hasSharesActionTimelock,
canonicalSender
);
}
/// @dev Helper for buy shares logic
function __buyShares(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity,
bool _hasSharesActionTimelock,
address _canonicalSender
) private locksReentrance allowsPermissionedVaultAction returns (uint256 sharesReceived_) {
// Enforcing a _minSharesQuantity also validates `_investmentAmount > 0`
// and guarantees the function cannot succeed while minting 0 shares
require(_minSharesQuantity > 0, "__buyShares: _minSharesQuantity must be >0");
address vaultProxyCopy = getVaultProxy();
require(
!_hasSharesActionTimelock || !__hasPendingMigrationOrReconfiguration(vaultProxyCopy),
"__buyShares: Pending migration or reconfiguration"
);
uint256 gav = calcGav();
// Gives Extensions a chance to run logic prior to the minting of bought shares.
// Fees implementing this hook should be aware that
// it might be the case that _investmentAmount != actualInvestmentAmount,
// if the denomination asset charges a transfer fee, for example.
__preBuySharesHook(_buyer, _investmentAmount, gav);
// Pay the protocol fee after running other fees, but before minting new shares
IVault(vaultProxyCopy).payProtocolFee();
if (doesAutoProtocolFeeSharesBuyback()) {
__buyBackMaxProtocolFeeShares(vaultProxyCopy, gav);
}
// Transfer the investment asset to the fund.
// Does not follow the checks-effects-interactions pattern, but it is necessary to
// do this delta balance calculation before calculating shares to mint.
uint256 receivedInvestmentAmount = __transferFromWithReceivedAmount(
getDenominationAsset(),
_canonicalSender,
vaultProxyCopy,
_investmentAmount
);
// Calculate the amount of shares to issue with the investment amount
uint256 sharePrice = __calcGrossShareValue(
gav,
ERC20(vaultProxyCopy).totalSupply(),
10**uint256(ERC20(getDenominationAsset()).decimals())
);
uint256 sharesIssued = receivedInvestmentAmount.mul(SHARES_UNIT).div(sharePrice);
// Mint shares to the buyer
uint256 prevBuyerShares = ERC20(vaultProxyCopy).balanceOf(_buyer);
IVault(vaultProxyCopy).mintShares(_buyer, sharesIssued);
// Gives Extensions a chance to run logic after shares are issued
__postBuySharesHook(_buyer, receivedInvestmentAmount, sharesIssued, gav);
// The number of actual shares received may differ from shares issued due to
// how the PostBuyShares hooks are invoked by Extensions (i.e., fees)
sharesReceived_ = ERC20(vaultProxyCopy).balanceOf(_buyer).sub(prevBuyerShares);
require(
sharesReceived_ >= _minSharesQuantity,
"__buyShares: Shares received < _minSharesQuantity"
);
if (_hasSharesActionTimelock) {
acctToLastSharesBoughtTimestamp[_buyer] = block.timestamp;
}
emit SharesBought(_buyer, receivedInvestmentAmount, sharesIssued, sharesReceived_);
return sharesReceived_;
}
/// @dev Helper for Extension actions immediately prior to issuing shares
function __preBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _gav
) private {
IFeeManager(getFeeManager()).invokeHook(
IFeeManager.FeeHook.PreBuyShares,
abi.encode(_buyer, _investmentAmount),
_gav
);
}
/// @dev Helper for Extension actions immediately after issuing shares.
/// This could be cleaned up so both Extensions take the same encoded args and handle GAV
/// in the same way, but there is not the obvious need for gas savings of recycling
/// the GAV value for the current policies as there is for the fees.
function __postBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _sharesIssued,
uint256 _preBuySharesGav
) private {
uint256 gav = _preBuySharesGav.add(_investmentAmount);
IFeeManager(getFeeManager()).invokeHook(
IFeeManager.FeeHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued),
gav
);
IPolicyManager(getPolicyManager()).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued, gav)
);
}
/// @dev Helper to execute ERC20.transferFrom() while calculating the actual amount received
function __transferFromWithReceivedAmount(
address _asset,
address _sender,
address _recipient,
uint256 _transferAmount
) private returns (uint256 receivedAmount_) {
uint256 preTransferRecipientBalance = ERC20(_asset).balanceOf(_recipient);
ERC20(_asset).safeTransferFrom(_sender, _recipient, _transferAmount);
return ERC20(_asset).balanceOf(_recipient).sub(preTransferRecipientBalance);
}
// REDEEM SHARES
/// @notice Redeems a specified amount of the sender's shares for specified asset proportions
/// @param _recipient The account that will receive the specified assets
/// @param _sharesQuantity The quantity of shares to redeem
/// @param _payoutAssets The assets to payout
/// @param _payoutAssetPercentages The percentage of the owed amount to pay out in each asset
/// @return payoutAmounts_ The amount of each asset paid out to the _recipient
/// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value.
/// _payoutAssetPercentages must total exactly 100%. In order to specify less and forgo the
/// remaining gav owed on the redeemed shares, pass in address(0) with the percentage to forego.
/// Unlike redeemSharesInKind(), this function allows policies to run and prevent redemption.
function redeemSharesForSpecificAssets(
address _recipient,
uint256 _sharesQuantity,
address[] calldata _payoutAssets,
uint256[] calldata _payoutAssetPercentages
) external locksReentrance returns (uint256[] memory payoutAmounts_) {
address canonicalSender = __msgSender();
require(
_payoutAssets.length == _payoutAssetPercentages.length,
"redeemSharesForSpecificAssets: Unequal arrays"
);
require(
_payoutAssets.isUniqueSet(),
"redeemSharesForSpecificAssets: Duplicate payout asset"
);
uint256 gav = calcGav();
IVault vaultProxyContract = IVault(getVaultProxy());
(uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup(
vaultProxyContract,
canonicalSender,
_sharesQuantity,
true,
gav
);
payoutAmounts_ = __payoutSpecifiedAssetPercentages(
vaultProxyContract,
_recipient,
_payoutAssets,
_payoutAssetPercentages,
gav.mul(sharesToRedeem).div(sharesSupply)
);
// Run post-redemption in order to have access to the payoutAmounts
__postRedeemSharesForSpecificAssetsHook(
canonicalSender,
_recipient,
sharesToRedeem,
_payoutAssets,
payoutAmounts_,
gav
);
emit SharesRedeemed(
canonicalSender,
_recipient,
sharesToRedeem,
_payoutAssets,
payoutAmounts_
);
return payoutAmounts_;
}
/// @notice Redeems a specified amount of the sender's shares
/// for a proportionate slice of the vault's assets
/// @param _recipient The account that will receive the proportionate slice of assets
/// @param _sharesQuantity The quantity of shares to redeem
/// @param _additionalAssets Additional (non-tracked) assets to claim
/// @param _assetsToSkip Tracked assets to forfeit
/// @return payoutAssets_ The assets paid out to the _recipient
/// @return payoutAmounts_ The amount of each asset paid out to the _recipient
/// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value.
/// Any claim to passed _assetsToSkip will be forfeited entirely. This should generally
/// only be exercised if a bad asset is causing redemption to fail.
/// This function should never fail without a way to bypass the failure, which is assured
/// through two mechanisms:
/// 1. The FeeManager is called with the try/catch pattern to assure that calls to it
/// can never block redemption.
/// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited)
/// by explicitly specifying _assetsToSkip.
/// Because of these assurances, shares should always be redeemable, with the exception
/// of the timelock period on shares actions that must be respected.
function redeemSharesInKind(
address _recipient,
uint256 _sharesQuantity,
address[] calldata _additionalAssets,
address[] calldata _assetsToSkip
)
external
locksReentrance
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_)
{
address canonicalSender = __msgSender();
require(
_additionalAssets.isUniqueSet(),
"redeemSharesInKind: _additionalAssets contains duplicates"
);
require(
_assetsToSkip.isUniqueSet(),
"redeemSharesInKind: _assetsToSkip contains duplicates"
);
// Parse the payout assets given optional params to add or skip assets.
// Note that there is no validation that the _additionalAssets are known assets to
// the protocol. This means that the redeemer could specify a malicious asset,
// but since all state-changing, user-callable functions on this contract share the
// non-reentrant modifier, there is nowhere to perform a reentrancy attack.
payoutAssets_ = __parseRedemptionPayoutAssets(
IVault(vaultProxy).getTrackedAssets(),
_additionalAssets,
_assetsToSkip
);
// If protocol fee shares will be auto-bought back, attempt to calculate GAV to pass into fees,
// as we will require GAV later during the buyback.
uint256 gavOrZero;
if (doesAutoProtocolFeeSharesBuyback()) {
// Since GAV calculation can fail with a revering price or a no-longer-supported asset,
// we must try/catch GAV calculation to ensure that in-kind redemption can still succeed
try this.calcGav() returns (uint256 gav) {
gavOrZero = gav;
} catch {
emit RedeemSharesInKindCalcGavFailed();
}
}
(uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup(
IVault(vaultProxy),
canonicalSender,
_sharesQuantity,
false,
gavOrZero
);
// Calculate and transfer payout asset amounts due to _recipient
payoutAmounts_ = new uint256[](payoutAssets_.length);
for (uint256 i; i < payoutAssets_.length; i++) {
payoutAmounts_[i] = ERC20(payoutAssets_[i])
.balanceOf(vaultProxy)
.mul(sharesToRedeem)
.div(sharesSupply);
// Transfer payout asset to _recipient
if (payoutAmounts_[i] > 0) {
IVault(vaultProxy).withdrawAssetTo(
payoutAssets_[i],
_recipient,
payoutAmounts_[i]
);
}
}
emit SharesRedeemed(
canonicalSender,
_recipient,
sharesToRedeem,
payoutAssets_,
payoutAmounts_
);
return (payoutAssets_, payoutAmounts_);
}
/// @dev Helper to parse an array of payout assets during redemption, taking into account
/// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets.
/// All input arrays are assumed to be unique.
function __parseRedemptionPayoutAssets(
address[] memory _trackedAssets,
address[] memory _additionalAssets,
address[] memory _assetsToSkip
) private pure returns (address[] memory payoutAssets_) {
address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip);
if (_additionalAssets.length == 0) {
return trackedAssetsToPayout;
}
// Add additional assets. Duplicates of trackedAssets are ignored.
bool[] memory indexesToAdd = new bool[](_additionalAssets.length);
uint256 additionalItemsCount;
for (uint256 i; i < _additionalAssets.length; i++) {
if (!trackedAssetsToPayout.contains(_additionalAssets[i])) {
indexesToAdd[i] = true;
additionalItemsCount++;
}
}
if (additionalItemsCount == 0) {
return trackedAssetsToPayout;
}
payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount));
for (uint256 i; i < trackedAssetsToPayout.length; i++) {
payoutAssets_[i] = trackedAssetsToPayout[i];
}
uint256 payoutAssetsIndex = trackedAssetsToPayout.length;
for (uint256 i; i < _additionalAssets.length; i++) {
if (indexesToAdd[i]) {
payoutAssets_[payoutAssetsIndex] = _additionalAssets[i];
payoutAssetsIndex++;
}
}
return payoutAssets_;
}
/// @dev Helper to payout specified asset percentages during redeemSharesForSpecificAssets()
function __payoutSpecifiedAssetPercentages(
IVault vaultProxyContract,
address _recipient,
address[] calldata _payoutAssets,
uint256[] calldata _payoutAssetPercentages,
uint256 _owedGav
) private returns (uint256[] memory payoutAmounts_) {
address denominationAssetCopy = getDenominationAsset();
uint256 percentagesTotal;
payoutAmounts_ = new uint256[](_payoutAssets.length);
for (uint256 i; i < _payoutAssets.length; i++) {
percentagesTotal = percentagesTotal.add(_payoutAssetPercentages[i]);
// Used to explicitly specify less than 100% in total _payoutAssetPercentages
if (_payoutAssets[i] == SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS) {
continue;
}
payoutAmounts_[i] = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue(
denominationAssetCopy,
_owedGav.mul(_payoutAssetPercentages[i]).div(ONE_HUNDRED_PERCENT),
_payoutAssets[i]
);
// Guards against corner case of primitive-to-derivative asset conversion that floors to 0,
// or redeeming a very low shares amount and/or percentage where asset value owed is 0
require(
payoutAmounts_[i] > 0,
"__payoutSpecifiedAssetPercentages: Zero amount for asset"
);
vaultProxyContract.withdrawAssetTo(_payoutAssets[i], _recipient, payoutAmounts_[i]);
}
require(
percentagesTotal == ONE_HUNDRED_PERCENT,
"__payoutSpecifiedAssetPercentages: Percents must total 100%"
);
return payoutAmounts_;
}
/// @dev Helper for system actions immediately prior to redeeming shares.
/// Policy validation is not currently allowed on redemption, to ensure continuous redeemability.
function __preRedeemSharesHook(
address _redeemer,
uint256 _sharesToRedeem,
bool _forSpecifiedAssets,
uint256 _gavIfCalculated
) private allowsPermissionedVaultAction {
try
IFeeManager(getFeeManager()).invokeHook(
IFeeManager.FeeHook.PreRedeemShares,
abi.encode(_redeemer, _sharesToRedeem, _forSpecifiedAssets),
_gavIfCalculated
)
{} catch (bytes memory reason) {
emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesToRedeem);
}
}
/// @dev Helper to run policy validation after other logic for redeeming shares for specific assets.
/// Avoids stack-too-deep error.
function __postRedeemSharesForSpecificAssetsHook(
address _redeemer,
address _recipient,
uint256 _sharesToRedeemPostFees,
address[] memory _assets,
uint256[] memory _assetAmounts,
uint256 _gavPreRedeem
) private {
IPolicyManager(getPolicyManager()).validatePolicies(
address(this),
IPolicyManager.PolicyHook.RedeemSharesForSpecificAssets,
abi.encode(
_redeemer,
_recipient,
_sharesToRedeemPostFees,
_assets,
_assetAmounts,
_gavPreRedeem
)
);
}
/// @dev Helper to execute common pre-shares redemption logic
function __redeemSharesSetup(
IVault vaultProxyContract,
address _redeemer,
uint256 _sharesQuantityInput,
bool _forSpecifiedAssets,
uint256 _gavIfCalculated
) private returns (uint256 sharesToRedeem_, uint256 sharesSupply_) {
__assertSharesActionNotTimelocked(address(vaultProxyContract), _redeemer);
ERC20 sharesContract = ERC20(address(vaultProxyContract));
uint256 preFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer);
if (_sharesQuantityInput == type(uint256).max) {
sharesToRedeem_ = preFeesRedeemerSharesBalance;
} else {
sharesToRedeem_ = _sharesQuantityInput;
}
require(sharesToRedeem_ > 0, "__redeemSharesSetup: No shares to redeem");
__preRedeemSharesHook(_redeemer, sharesToRedeem_, _forSpecifiedAssets, _gavIfCalculated);
// Update the redemption amount if fees were charged (or accrued) to the redeemer
uint256 postFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer);
if (_sharesQuantityInput == type(uint256).max) {
sharesToRedeem_ = postFeesRedeemerSharesBalance;
} else if (postFeesRedeemerSharesBalance < preFeesRedeemerSharesBalance) {
sharesToRedeem_ = sharesToRedeem_.sub(
preFeesRedeemerSharesBalance.sub(postFeesRedeemerSharesBalance)
);
}
// Pay the protocol fee after running other fees, but before burning shares
vaultProxyContract.payProtocolFee();
if (_gavIfCalculated > 0 && doesAutoProtocolFeeSharesBuyback()) {
__buyBackMaxProtocolFeeShares(address(vaultProxyContract), _gavIfCalculated);
}
// Destroy the shares after getting the shares supply
sharesSupply_ = sharesContract.totalSupply();
vaultProxyContract.burnShares(_redeemer, sharesToRedeem_);
return (sharesToRedeem_, sharesSupply_);
}
// TRANSFER SHARES
/// @notice Runs logic prior to transferring shares that are not freely transferable
/// @param _sender The sender of the shares
/// @param _recipient The recipient of the shares
/// @param _amount The amount of shares
function preTransferSharesHook(
address _sender,
address _recipient,
uint256 _amount
) external override {
address vaultProxyCopy = getVaultProxy();
require(msg.sender == vaultProxyCopy, "preTransferSharesHook: Only VaultProxy callable");
__assertSharesActionNotTimelocked(vaultProxyCopy, _sender);
IPolicyManager(getPolicyManager()).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PreTransferShares,
abi.encode(_sender, _recipient, _amount)
);
}
/// @notice Runs logic prior to transferring shares that are freely transferable
/// @param _sender The sender of the shares
/// @dev No need to validate caller, as policies are not run
function preTransferSharesHookFreelyTransferable(address _sender) external view override {
__assertSharesActionNotTimelocked(getVaultProxy(), _sender);
}
/////////////////
// GAS RELAYER //
/////////////////
/// @notice Deploys a paymaster contract and deposits WETH, enabling gas relaying
function deployGasRelayPaymaster() external onlyOwnerNotRelayable {
require(
getGasRelayPaymaster() == address(0),
"deployGasRelayPaymaster: Paymaster already deployed"
);
bytes memory constructData = abi.encodeWithSignature("init(address)", getVaultProxy());
address paymaster = IBeaconProxyFactory(getGasRelayPaymasterFactory()).deployProxy(
constructData
);
__setGasRelayPaymaster(paymaster);
__depositToGasRelayPaymaster(paymaster);
}
/// @notice Tops up the gas relay paymaster deposit
function depositToGasRelayPaymaster() external onlyOwner {
__depositToGasRelayPaymaster(getGasRelayPaymaster());
}
/// @notice Pull WETH from vault to gas relay paymaster
/// @param _amount Amount of the WETH to pull from the vault
function pullWethForGasRelayer(uint256 _amount) external override onlyGasRelayPaymaster {
IVault(getVaultProxy()).withdrawAssetTo(getWethToken(), getGasRelayPaymaster(), _amount);
}
/// @notice Sets the gasRelayPaymaster variable value
/// @param _nextGasRelayPaymaster The next gasRelayPaymaster value
function setGasRelayPaymaster(address _nextGasRelayPaymaster)
external
override
onlyFundDeployer
{
__setGasRelayPaymaster(_nextGasRelayPaymaster);
}
/// @notice Removes the gas relay paymaster, withdrawing the remaining WETH balance
/// and disabling gas relaying
function shutdownGasRelayPaymaster() external onlyOwnerNotRelayable {
IGasRelayPaymaster(gasRelayPaymaster).withdrawBalance();
IVault(vaultProxy).addTrackedAsset(getWethToken());
delete gasRelayPaymaster;
emit GasRelayPaymasterSet(address(0));
}
/// @dev Helper to deposit to the gas relay paymaster
function __depositToGasRelayPaymaster(address _paymaster) private {
IGasRelayPaymaster(_paymaster).deposit();
}
/// @dev Helper to set the next `gasRelayPaymaster` variable
function __setGasRelayPaymaster(address _nextGasRelayPaymaster) private {
gasRelayPaymaster = _nextGasRelayPaymaster;
emit GasRelayPaymasterSet(_nextGasRelayPaymaster);
}
///////////////////
// STATE GETTERS //
///////////////////
// LIB IMMUTABLES
/// @notice Gets the `DISPATCHER` variable
/// @return dispatcher_ The `DISPATCHER` variable value
function getDispatcher() public view returns (address dispatcher_) {
return DISPATCHER;
}
/// @notice Gets the `EXTERNAL_POSITION_MANAGER` variable
/// @return externalPositionManager_ The `EXTERNAL_POSITION_MANAGER` variable value
function getExternalPositionManager()
public
view
override
returns (address externalPositionManager_)
{
return EXTERNAL_POSITION_MANAGER;
}
/// @notice Gets the `FEE_MANAGER` variable
/// @return feeManager_ The `FEE_MANAGER` variable value
function getFeeManager() public view override returns (address feeManager_) {
return FEE_MANAGER;
}
/// @notice Gets the `FUND_DEPLOYER` variable
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
function getFundDeployer() public view override returns (address fundDeployer_) {
return FUND_DEPLOYER;
}
/// @notice Gets the `INTEGRATION_MANAGER` variable
/// @return integrationManager_ The `INTEGRATION_MANAGER` variable value
function getIntegrationManager() public view override returns (address integrationManager_) {
return INTEGRATION_MANAGER;
}
/// @notice Gets the `MLN_TOKEN` variable
/// @return mlnToken_ The `MLN_TOKEN` variable value
function getMlnToken() public view returns (address mlnToken_) {
return MLN_TOKEN;
}
/// @notice Gets the `POLICY_MANAGER` variable
/// @return policyManager_ The `POLICY_MANAGER` variable value
function getPolicyManager() public view override returns (address policyManager_) {
return POLICY_MANAGER;
}
/// @notice Gets the `PROTOCOL_FEE_RESERVE` variable
/// @return protocolFeeReserve_ The `PROTOCOL_FEE_RESERVE` variable value
function getProtocolFeeReserve() public view returns (address protocolFeeReserve_) {
return PROTOCOL_FEE_RESERVE;
}
/// @notice Gets the `VALUE_INTERPRETER` variable
/// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value
function getValueInterpreter() public view returns (address valueInterpreter_) {
return VALUE_INTERPRETER;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() public view returns (address wethToken_) {
return WETH_TOKEN;
}
// PROXY STORAGE
/// @notice Checks if collected protocol fee shares are automatically bought back
/// while buying or redeeming shares
/// @return doesAutoBuyback_ True if shares are automatically bought back
function doesAutoProtocolFeeSharesBuyback() public view returns (bool doesAutoBuyback_) {
return autoProtocolFeeSharesBuyback;
}
/// @notice Gets the `denominationAsset` variable
/// @return denominationAsset_ The `denominationAsset` variable value
function getDenominationAsset() public view override returns (address denominationAsset_) {
return denominationAsset;
}
/// @notice Gets the `gasRelayPaymaster` variable
/// @return gasRelayPaymaster_ The `gasRelayPaymaster` variable value
function getGasRelayPaymaster() public view override returns (address gasRelayPaymaster_) {
return gasRelayPaymaster;
}
/// @notice Gets the timestamp of the last time shares were bought for a given account
/// @param _who The account for which to get the timestamp
/// @return lastSharesBoughtTimestamp_ The timestamp of the last shares bought
function getLastSharesBoughtTimestampForAccount(address _who)
public
view
returns (uint256 lastSharesBoughtTimestamp_)
{
return acctToLastSharesBoughtTimestamp[_who];
}
/// @notice Gets the `sharesActionTimelock` variable
/// @return sharesActionTimelock_ The `sharesActionTimelock` variable value
function getSharesActionTimelock() public view returns (uint256 sharesActionTimelock_) {
return sharesActionTimelock;
}
/// @notice Gets the `vaultProxy` variable
/// @return vaultProxy_ The `vaultProxy` variable value
function getVaultProxy() public view override returns (address vaultProxy_) {
return vaultProxy;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../vault/IVault.sol";
/// @title IComptroller Interface
/// @author Enzyme Council <[email protected]>
interface IComptroller {
function activate(bool) external;
function calcGav() external returns (uint256);
function calcGrossShareValue() external returns (uint256);
function callOnExtension(
address,
uint256,
bytes calldata
) external;
function destructActivated(uint256, uint256) external;
function destructUnactivated() external;
function getDenominationAsset() external view returns (address);
function getExternalPositionManager() external view returns (address);
function getFeeManager() external view returns (address);
function getFundDeployer() external view returns (address);
function getGasRelayPaymaster() external view returns (address);
function getIntegrationManager() external view returns (address);
function getPolicyManager() external view returns (address);
function getVaultProxy() external view returns (address);
function init(address, uint256) external;
function permissionedVaultAction(IVault.VaultAction, bytes calldata) external;
function preTransferSharesHook(
address,
address,
uint256
) external;
function preTransferSharesHookFreelyTransferable(address) external view;
function setGasRelayPaymaster(address) external;
function setVaultProxy(address) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../persistent/vault/interfaces/IExternalPositionVault.sol";
import "../../../../persistent/vault/interfaces/IFreelyTransferableSharesVault.sol";
import "../../../../persistent/vault/interfaces/IMigratableVault.sol";
/// @title IVault Interface
/// @author Enzyme Council <[email protected]>
interface IVault is IMigratableVault, IFreelyTransferableSharesVault, IExternalPositionVault {
enum VaultAction {
None,
// Shares management
BurnShares,
MintShares,
TransferShares,
// Asset management
AddTrackedAsset,
ApproveAssetSpender,
RemoveTrackedAsset,
WithdrawAssetTo,
// External position management
AddExternalPosition,
CallOnExternalPosition,
RemoveExternalPosition
}
function addTrackedAsset(address) external;
function burnShares(address, uint256) external;
function buyBackProtocolFeeShares(
uint256,
uint256,
uint256
) external;
function callOnContract(address, bytes calldata) external returns (bytes memory);
function canManageAssets(address) external view returns (bool);
function canRelayCalls(address) external view returns (bool);
function getAccessor() external view returns (address);
function getOwner() external view returns (address);
function getActiveExternalPositions() external view returns (address[] memory);
function getTrackedAssets() external view returns (address[] memory);
function isActiveExternalPosition(address) external view returns (bool);
function isTrackedAsset(address) external view returns (bool);
function mintShares(address, uint256) external;
function payProtocolFee() external;
function receiveValidatedVaultAction(VaultAction, bytes calldata) external;
function setAccessorForFundReconfiguration(address) external;
function setSymbol(string calldata) external;
function transferShares(
address,
address,
uint256
) external;
function withdrawAssetTo(
address,
address,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExtension Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all extensions
interface IExtension {
function activateForFund(bool _isMigration) external;
function deactivateForFund() external;
function receiveCallFromComptroller(
address _caller,
uint256 _actionId,
bytes calldata _callArgs
) external;
function setConfigForFund(
address _comptrollerProxy,
address _vaultProxy,
bytes calldata _configData
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title FeeManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the FeeManager
interface IFeeManager {
// No fees for the current release are implemented post-redeemShares
enum FeeHook {Continuous, PreBuyShares, PostBuyShares, PreRedeemShares}
enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding}
function invokeHook(
FeeHook,
bytes calldata,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title PolicyManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the PolicyManager
interface IPolicyManager {
// When updating PolicyHook, also update these functions in PolicyManager:
// 1. __getAllPolicyHooks()
// 2. __policyHookRestrictsCurrentInvestorActions()
enum PolicyHook {
PostBuyShares,
PostCallOnIntegration,
PreTransferShares,
RedeemSharesForSpecificAssets,
AddTrackedAssets,
RemoveTrackedAssets,
CreateExternalPosition,
PostCallOnExternalPosition,
RemoveExternalPosition,
ReactivateExternalPosition
}
function validatePolicies(
address,
PolicyHook,
bytes calldata
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import "../../utils/beacon-proxy/IBeaconProxyFactory.sol";
import "./IGasRelayPaymaster.sol";
pragma solidity 0.6.12;
/// @title GasRelayRecipientMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin that enables receiving GSN-relayed calls
/// @dev IMPORTANT: Do not use storage var in this contract,
/// unless it is no longer inherited by the VaultLib
abstract contract GasRelayRecipientMixin {
address internal immutable GAS_RELAY_PAYMASTER_FACTORY;
constructor(address _gasRelayPaymasterFactory) internal {
GAS_RELAY_PAYMASTER_FACTORY = _gasRelayPaymasterFactory;
}
/// @dev Helper to parse the canonical sender of a tx based on whether it has been relayed
function __msgSender() internal view returns (address payable canonicalSender_) {
if (msg.data.length >= 24 && msg.sender == getGasRelayTrustedForwarder()) {
assembly {
canonicalSender_ := shr(96, calldataload(sub(calldatasize(), 20)))
}
return canonicalSender_;
}
return msg.sender;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `GAS_RELAY_PAYMASTER_FACTORY` variable
/// @return gasRelayPaymasterFactory_ The `GAS_RELAY_PAYMASTER_FACTORY` variable value
function getGasRelayPaymasterFactory()
public
view
returns (address gasRelayPaymasterFactory_)
{
return GAS_RELAY_PAYMASTER_FACTORY;
}
/// @notice Gets the trusted forwarder for GSN relaying
/// @return trustedForwarder_ The trusted forwarder
function getGasRelayTrustedForwarder() public view returns (address trustedForwarder_) {
return
IGasRelayPaymaster(
IBeaconProxyFactory(getGasRelayPaymasterFactory()).getCanonicalLib()
)
.trustedForwarder();
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../interfaces/IGsnPaymaster.sol";
/// @title IGasRelayPaymaster Interface
/// @author Enzyme Council <[email protected]>
interface IGasRelayPaymaster is IGsnPaymaster {
function deposit() external;
function withdrawBalance() external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IGasRelayPaymasterDepositor Interface
/// @author Enzyme Council <[email protected]>
interface IGasRelayPaymasterDepositor {
function pullWethForGasRelayer(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IValueInterpreter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for ValueInterpreter
interface IValueInterpreter {
function calcCanonicalAssetValue(
address,
uint256,
address
) external returns (uint256);
function calcCanonicalAssetsTotalValue(
address[] calldata,
uint256[] calldata,
address
) external returns (uint256);
function isSupportedAsset(address) external view returns (bool);
function isSupportedDerivativeAsset(address) external view returns (bool);
function isSupportedPrimitiveAsset(address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IGsnForwarder interface
/// @author Enzyme Council <[email protected]>
interface IGsnForwarder {
struct ForwardRequest {
address from;
address to;
uint256 value;
uint256 gas;
uint256 nonce;
bytes data;
uint256 validUntil;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IGsnTypes.sol";
/// @title IGsnPaymaster interface
/// @author Enzyme Council <[email protected]>
interface IGsnPaymaster {
struct GasAndDataLimits {
uint256 acceptanceBudget;
uint256 preRelayedCallGasLimit;
uint256 postRelayedCallGasLimit;
uint256 calldataSizeLimit;
}
function getGasAndDataLimits() external view returns (GasAndDataLimits memory limits);
function getHubAddr() external view returns (address);
function getRelayHubDeposit() external view returns (uint256);
function preRelayedCall(
IGsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
) external returns (bytes memory context, bool rejectOnRecipientRevert);
function postRelayedCall(
bytes calldata context,
bool success,
uint256 gasUseWithoutPost,
IGsnTypes.RelayData calldata relayData
) external;
function trustedForwarder() external view returns (address);
function versionPaymaster() external view returns (string memory);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IGsnForwarder.sol";
/// @title IGsnTypes Interface
/// @author Enzyme Council <[email protected]>
interface IGsnTypes {
struct RelayData {
uint256 gasPrice;
uint256 pctRelayFee;
uint256 baseRelayFee;
address relayWorker;
address paymaster;
address forwarder;
bytes paymasterData;
uint256 clientId;
}
struct RelayRequest {
IGsnForwarder.ForwardRequest request;
RelayData relayData;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title WETH Interface
/// @author Enzyme Council <[email protected]>
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../core/fund/comptroller/ComptrollerLib.sol";
import "../interfaces/IWETH.sol";
import "../utils/AssetHelpers.sol";
/// @title DepositWrapper Contract
/// @author Enzyme Council <[email protected]>
/// @notice Logic related to wrapping deposit actions
contract DepositWrapper is AssetHelpers {
address private immutable WETH_TOKEN;
constructor(address _weth) public {
WETH_TOKEN = _weth;
}
/// @dev Needed in case WETH not fully used during exchangeAndBuyShares,
/// to unwrap into ETH and refund
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Exchanges ETH into a fund's denomination asset and then buys shares
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _minSharesQuantity The minimum quantity of shares to buy with the sent ETH
/// @param _exchange The exchange on which to execute the swap to the denomination asset
/// @param _exchangeApproveTarget The address that should be given an allowance of WETH
/// for the given _exchange
/// @param _exchangeData The data with which to call the exchange to execute the swap
/// to the denomination asset
/// @param _minInvestmentAmount The minimum amount of the denomination asset
/// to receive in the trade for investment (not necessary for WETH)
/// @return sharesReceived_ The actual amount of shares received
/// @dev Use a reasonable _minInvestmentAmount always, in case the exchange
/// does not perform as expected (low incoming asset amount, blend of assets, etc).
/// If the fund's denomination asset is WETH, _exchange, _exchangeApproveTarget, _exchangeData,
/// and _minInvestmentAmount will be ignored.
function exchangeEthAndBuyShares(
address _comptrollerProxy,
address _denominationAsset,
uint256 _minSharesQuantity,
address _exchange,
address _exchangeApproveTarget,
bytes calldata _exchangeData,
uint256 _minInvestmentAmount
) external payable returns (uint256 sharesReceived_) {
// Wrap ETH into WETH
IWETH(payable(getWethToken())).deposit{value: msg.value}();
// If denominationAsset is WETH, can just buy shares directly
if (_denominationAsset == getWethToken()) {
__approveAssetMaxAsNeeded(getWethToken(), _comptrollerProxy, msg.value);
return __buyShares(_comptrollerProxy, msg.sender, msg.value, _minSharesQuantity);
}
// Exchange ETH to the fund's denomination asset
__approveAssetMaxAsNeeded(getWethToken(), _exchangeApproveTarget, msg.value);
(bool success, bytes memory returnData) = _exchange.call(_exchangeData);
require(success, string(returnData));
// Confirm the amount received in the exchange is above the min acceptable amount
uint256 investmentAmount = ERC20(_denominationAsset).balanceOf(address(this));
require(
investmentAmount >= _minInvestmentAmount,
"exchangeAndBuyShares: _minInvestmentAmount not met"
);
// Give the ComptrollerProxy max allowance for its denomination asset as necessary
__approveAssetMaxAsNeeded(_denominationAsset, _comptrollerProxy, investmentAmount);
// Buy fund shares
sharesReceived_ = __buyShares(
_comptrollerProxy,
msg.sender,
investmentAmount,
_minSharesQuantity
);
// Unwrap and refund any remaining WETH not used in the exchange
uint256 remainingWeth = ERC20(getWethToken()).balanceOf(address(this));
if (remainingWeth > 0) {
IWETH(payable(getWethToken())).withdraw(remainingWeth);
(success, returnData) = msg.sender.call{value: remainingWeth}("");
require(success, string(returnData));
}
return sharesReceived_;
}
// PRIVATE FUNCTIONS
/// @dev Helper for buying shares
function __buyShares(
address _comptrollerProxy,
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity
) private returns (uint256 sharesReceived_) {
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
sharesReceived_ = comptrollerProxyContract.buySharesOnBehalf(
_buyer,
_investmentAmount,
_minSharesQuantity
);
return sharesReceived_;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() public view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AddressArray Library
/// @author Enzyme Council <[email protected]>
/// @notice A library to extend the address array data type
library AddressArrayLib {
/////////////
// STORAGE //
/////////////
/// @dev Helper to remove an item from a storage array
function removeStorageItem(address[] storage _self, address _itemToRemove)
internal
returns (bool removed_)
{
uint256 itemCount = _self.length;
for (uint256 i; i < itemCount; i++) {
if (_self[i] == _itemToRemove) {
if (i < itemCount - 1) {
_self[i] = _self[itemCount - 1];
}
_self.pop();
removed_ = true;
break;
}
}
return removed_;
}
////////////
// MEMORY //
////////////
/// @dev Helper to add an item to an array. Does not assert uniqueness of the new item.
function addItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
nextArray_ = new address[](_self.length + 1);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
nextArray_[_self.length] = _itemToAdd;
return nextArray_;
}
/// @dev Helper to add an item to an array, only if it is not already in the array.
function addUniqueItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
if (contains(_self, _itemToAdd)) {
return _self;
}
return addItem(_self, _itemToAdd);
}
/// @dev Helper to verify if an array contains a particular value
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
/// @dev Helper to merge the unique items of a second array.
/// Does not consider uniqueness of either array, only relative uniqueness.
/// Preserves ordering.
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
/// @dev Helper to verify if array is a set of unique values.
/// Does not assert length > 0.
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
/// @dev Helper to remove items from an array. Removes all matching occurrences of each item.
/// Does not assert uniqueness of either array.
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
} else if (remainingItemsCount > 0) {
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/// @title AssetHelpers Contract
/// @author Enzyme Council <[email protected]>
/// @notice A util contract for common token actions
abstract contract AssetHelpers {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/// @dev Helper to approve a target account with the max amount of an asset.
/// This is helpful for fully trusted contracts, such as adapters that
/// interact with external protocol like Uniswap, Compound, etc.
function __approveAssetMaxAsNeeded(
address _asset,
address _target,
uint256 _neededAmount
) internal {
uint256 allowance = ERC20(_asset).allowance(address(this), _target);
if (allowance < _neededAmount) {
if (allowance > 0) {
ERC20(_asset).safeApprove(_target, 0);
}
ERC20(_asset).safeApprove(_target, type(uint256).max);
}
}
/// @dev Helper to transfer full asset balances from the current contract to a target
function __pushFullAssetBalances(address _target, address[] memory _assets)
internal
returns (uint256[] memory amountsTransferred_)
{
amountsTransferred_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
ERC20 assetContract = ERC20(_assets[i]);
amountsTransferred_[i] = assetContract.balanceOf(address(this));
if (amountsTransferred_[i] > 0) {
assetContract.safeTransfer(_target, amountsTransferred_[i]);
}
}
return amountsTransferred_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IBeacon interface
/// @author Enzyme Council <[email protected]>
interface IBeacon {
function getCanonicalLib() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import "./IBeacon.sol";
pragma solidity 0.6.12;
/// @title IBeaconProxyFactory interface
/// @author Enzyme Council <[email protected]>
interface IBeaconProxyFactory is IBeacon {
function deployProxy(bytes memory _constructData) external returns (address proxy_);
function setCanonicalLib(address _canonicalLib) external;
} | Since GAV calculation can fail with a revering price or a no-longer-supported asset, we must try/catch GAV calculation to ensure that in-kind redemption can still succeed | function __preBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _gav
}
function __postBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _sharesIssued,
uint256 _preBuySharesGav
}
function __transferFromWithReceivedAmount(
address _asset,
address _sender,
address _recipient,
uint256 _transferAmount
}
function redeemSharesForSpecificAssets(
address _recipient,
uint256 _sharesQuantity,
address[] calldata _payoutAssets,
uint256[] calldata _payoutAssetPercentages
}
function redeemSharesInKind(
address _recipient,
uint256 _sharesQuantity,
address[] calldata _additionalAssets,
address[] calldata _assetsToSkip
)
external
locksReentrance
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_)
if (doesAutoProtocolFeeSharesBuyback()) {
try this.calcGav() returns (uint256 gav) {
gavOrZero = gav;
emit RedeemSharesInKindCalcGavFailed();
}
}
(uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup(
IVault(vaultProxy),
canonicalSender,
_sharesQuantity,
false,
gavOrZero
);
| 122,373 | [
1,
4625,
348,
7953,
560,
30,
225,
7897,
611,
5856,
11096,
848,
2321,
598,
279,
283,
502,
310,
6205,
578,
279,
1158,
17,
9379,
693,
17,
4127,
3310,
16,
732,
1297,
775,
19,
14683,
611,
5856,
11096,
358,
3387,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034,
389,
75,
842,
203,
565,
289,
203,
203,
565,
445,
1001,
2767,
38,
9835,
24051,
5394,
12,
203,
3639,
1758,
389,
70,
16213,
16,
203,
3639,
2254,
5034,
389,
5768,
395,
475,
6275,
16,
203,
3639,
2254,
5034,
389,
30720,
7568,
5957,
16,
203,
3639,
2254,
5034,
389,
1484,
38,
9835,
24051,
43,
842,
203,
565,
289,
203,
203,
565,
445,
1001,
13866,
1265,
1190,
8872,
6275,
12,
203,
3639,
1758,
389,
9406,
16,
203,
3639,
1758,
389,
15330,
16,
203,
3639,
1758,
389,
20367,
16,
203,
3639,
2254,
5034,
389,
13866,
6275,
203,
565,
289,
203,
203,
203,
565,
445,
283,
24903,
24051,
1290,
9969,
10726,
12,
203,
3639,
1758,
389,
20367,
16,
203,
3639,
2254,
5034,
389,
30720,
12035,
16,
203,
3639,
1758,
8526,
745,
892,
389,
84,
2012,
10726,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
389,
84,
2012,
6672,
8410,
1023,
203,
565,
289,
203,
203,
565,
445,
283,
24903,
24051,
382,
5677,
12,
203,
3639,
1758,
389,
20367,
16,
203,
3639,
2254,
5034,
389,
30720,
12035,
16,
203,
3639,
1758,
8526,
745,
892,
389,
13996,
10726,
16,
203,
3639,
1758,
8526,
745,
892,
389,
9971,
774,
6368,
203,
565,
262,
203,
3639,
3903,
203,
3639,
13046,
426,
8230,
1359,
203,
3639,
1135,
261,
2867,
8526,
3778,
293,
2012,
10726,
67,
16,
2254,
5034,
8526,
3778,
293,
2012,
6275,
87,
67,
13,
203,
3639,
309,
261,
20657,
4965,
5752,
14667,
24051,
38,
9835,
823,
10756,
288,
203,
5411,
775,
333,
18,
12448,
43,
842,
1435,
1135,
261,
11890,
5034,
314,
842,
13,
288,
203,
7734,
314,
842,
1162,
7170,
273,
314,
842,
31,
203,
7734,
3626,
868,
24903,
24051,
382,
5677,
25779,
43,
842,
2925,
5621,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
261,
11890,
5034,
24123,
774,
426,
24903,
16,
2254,
5034,
24123,
3088,
1283,
13,
273,
1001,
266,
24903,
24051,
7365,
12,
203,
5411,
467,
12003,
12,
26983,
3886,
3631,
203,
5411,
7378,
12021,
16,
203,
5411,
389,
30720,
12035,
16,
203,
5411,
629,
16,
203,
5411,
314,
842,
1162,
7170,
203,
3639,
11272,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x19BEC0cCDf4e2cDcb216c2b2162c08A2B4c655b9/sources/contracts/UtilityWenUpgradeable.sol | * @notice Sets the collection max supply @param _maxSupply The max supply of the collection/ | function setMaxSupply(uint _maxSupply) external onlyOwner {
maxSupply = _maxSupply;
}
| 2,935,995 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
20392,
11511,
326,
1849,
943,
14467,
632,
891,
389,
1896,
3088,
1283,
1021,
943,
14467,
434,
326,
1849,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: contracts/libraries/TransferHelper.sol
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: APPROVE_FAILED");
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: TRANSFER_FAILED");
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: TRANSFER_FROM_FAILED");
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, "TransferHelper: ETH_TRANSFER_FAILED");
}
}
// File: contracts/libraries/SafeMath.sol
pragma solidity =0.6.6;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
}
// File: dxswap-core/contracts/interfaces/IDXswapPair.sol
pragma solidity >=0.5.0;
interface IDXswapPair {
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 swapFee() external view returns (uint32);
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;
function setSwapFee(uint32) external;
}
// File: contracts/libraries/DXswapLibrary.sol
pragma solidity >=0.5.0;
library DXswapLibrary {
using SafeMath for uint256;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, "DXswapLibrary: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), "DXswapLibrary: ZERO_ADDRESS");
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(
address factory,
address tokenA,
address tokenB
) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"2db943b381c6ef706828ea5e89f480bd449d4d3a2b98e6da97b30d0eb41fb6d6" // init code hash
)
)
)
);
}
// fetches and sorts the reserves for a pair
function getReserves(
address factory,
address tokenA,
address tokenB
) internal view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) = IDXswapPair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// fetches and sorts the reserves for a pair
function getSwapFee(
address factory,
address tokenA,
address tokenB
) internal view returns (uint256 swapFee) {
(address token0, ) = sortTokens(tokenA, tokenB);
swapFee = IDXswapPair(pairFor(factory, tokenA, tokenB)).swapFee();
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) internal pure returns (uint256 amountB) {
require(amountA > 0, "DXswapLibrary: INSUFFICIENT_AMOUNT");
require(reserveA > 0 && reserveB > 0, "DXswapLibrary: INSUFFICIENT_LIQUIDITY");
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut,
uint256 swapFee
) internal pure returns (uint256 amountOut) {
require(amountIn > 0, "DXswapLibrary: INSUFFICIENT_INPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > 0, "DXswapLibrary: INSUFFICIENT_LIQUIDITY");
uint256 amountInWithFee = amountIn.mul(uint256(10000).sub(swapFee));
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(10000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut,
uint256 swapFee
) internal pure returns (uint256 amountIn) {
require(amountOut > 0, "DXswapLibrary: INSUFFICIENT_OUTPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > 0, "DXswapLibrary: INSUFFICIENT_LIQUIDITY");
uint256 numerator = reserveIn.mul(amountOut).mul(10000);
uint256 denominator = reserveOut.sub(amountOut).mul(uint256(10000).sub(swapFee));
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(
address factory,
uint256 amountIn,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "DXswapLibrary: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[0] = amountIn;
for (uint256 i; i < path.length - 1; i++) {
(uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut, getSwapFee(factory, path[i], path[i + 1]));
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(
address factory,
uint256 amountOut,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "DXswapLibrary: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint256 i = path.length - 1; i > 0; i--) {
(uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut, getSwapFee(factory, path[i - 1], path[i]));
}
}
}
// File: contracts/interfaces/IDXswapFactory.sol
pragma solidity >=0.5.0;
interface IDXswapFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint256);
function INIT_CODE_PAIR_HASH() external pure returns (bytes32);
function feeTo() external view returns (address);
function protocolFeeDenominator() external view returns (uint8);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function setProtocolFee(uint8 _protocolFee) external;
function setSwapFee(address pair, uint32 swapFee) external;
}
// File: contracts/interfaces/IERC20.sol
pragma solidity >=0.5.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
}
// File: contracts/interfaces/IWETH.sol
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
function balanceOf(address guy) external returns (uint256);
function approve(address guy, uint256 wad) external returns (bool);
}
// File: contracts/interfaces/IBatchExchange.sol
pragma solidity >=0.5.0;
interface IBatchExchange {
function tokenAddressToIdMap(address addr) external view returns (uint16);
function tokenIdToAddressMap(uint16 id) external view returns (address);
function hasToken(address addr) external view returns (bool);
function placeOrder(
uint16 buyToken,
uint16 sellToken,
uint32 validUntil,
uint128 buyAmount,
uint128 sellAmount
) external returns (uint256);
function placeValidFromOrders(
uint16[] calldata buyTokens,
uint16[] calldata sellTokens,
uint32[] calldata validFroms,
uint32[] calldata validUntils,
uint128[] calldata buyAmounts,
uint128[] calldata sellAmounts
) external returns (uint16[] memory orderIds);
function cancelOrders(uint16[] calldata orderIds) external;
}
// File: contracts/interfaces/IEpochTokenLocker.sol
pragma solidity >=0.5.0;
interface IEpochTokenLocker {
function deposit(address token, uint256 amount) external;
function withdraw(address user, address token) external;
function getCurrentBatchId() external view returns (uint32);
function requestWithdraw(address token, uint256 amount) external;
function BATCH_TIME() external view returns (uint32);
}
// File: contracts/libraries/FixedPoint.sol
pragma solidity >=0.5.0;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint256 _x;
}
uint8 private constant RESOLUTION = 112;
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) {
require(x != 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112(self._x / uint224(x));
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) {
uint256 z;
require(y == 0 || (z = uint256(self._x) * y) / y == uint256(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
return uq144x112(z);
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << RESOLUTION) / denominator);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
}
// File: contracts/libraries/DXswapOracleLibrary.sol
pragma solidity >=0.5.0;
// library with helper methods for oracles that are concerned with computing average prices
library DXswapOracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2**32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(address pair)
internal
view
returns (
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestamp
)
{
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IDXswapPair(pair).price0CumulativeLast();
price1Cumulative = IDXswapPair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IDXswapPair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint256(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint256(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
// File: contracts/OracleCreator.sol
pragma solidity =0.6.6;
contract OracleCreator {
using FixedPoint for *;
using SafeMath for uint256;
event OracleCreated(
uint256 indexed _oracleIndex,
address indexed _pair,
uint256 _windowTime
);
struct Oracle{
uint256 windowTime;
address token0;
address token1;
IDXswapPair pair;
uint32 blockTimestampLast;
uint256 price0CumulativeLast;
uint256 price1CumulativeLast;
FixedPoint.uq112x112 price0Average;
FixedPoint.uq112x112 price1Average;
uint256 observationsCount;
address owner;
}
mapping(uint256 => Oracle) public oracles;
uint256 public oraclesIndex;
function createOracle(
uint256 windowTime,
address pair
) public returns (uint256 oracleId) {
IDXswapPair sourcePair = IDXswapPair(pair);
address token0 = sourcePair.token0();
address token1 = sourcePair.token1();
(,, uint32 blockTimestampLast) = sourcePair.getReserves();
oracles[oraclesIndex] = Oracle({
windowTime: windowTime,
token0: token0,
token1: token1,
pair: sourcePair,
blockTimestampLast: blockTimestampLast,
price0CumulativeLast: sourcePair.price0CumulativeLast(),
price1CumulativeLast: sourcePair.price1CumulativeLast(),
price0Average: FixedPoint.uq112x112(0),
price1Average: FixedPoint.uq112x112(0),
observationsCount: 0,
owner: msg.sender
});
oracleId = oraclesIndex;
oraclesIndex++;
emit OracleCreated(oracleId, address(sourcePair), windowTime);
}
function update(uint256 oracleIndex) public {
Oracle storage oracle = oracles[oracleIndex];
require(msg.sender == oracle.owner, 'OracleCreator: CALLER_NOT_OWNER');
require(oracle.observationsCount < 2, 'OracleCreator: FINISHED_OBERSERVATION');
(uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) =
DXswapOracleLibrary.currentCumulativePrices(address(oracle.pair));
uint32 timeElapsed = blockTimestamp - oracle.blockTimestampLast; // overflow is desired
// first update can be executed immediately. Ensure that at least one full period has passed since the first update
require(
oracle.observationsCount == 0 || timeElapsed >= oracle.windowTime,
'OracleCreator: PERIOD_NOT_ELAPSED'
);
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
oracle.price0Average = FixedPoint.uq112x112(
uint224((price0Cumulative - oracle.price0CumulativeLast) / timeElapsed)
);
oracle.price1Average = FixedPoint.uq112x112(
uint224((price1Cumulative - oracle.price1CumulativeLast) / timeElapsed)
);
oracle.price0CumulativeLast = price0Cumulative;
oracle.price1CumulativeLast = price1Cumulative;
oracle.blockTimestampLast = blockTimestamp;
oracle.observationsCount++;
}
// note this will always return 0 before update has been called successfully for the first time.
function consult(uint256 oracleIndex, address token, uint256 amountIn) external view returns (uint256 amountOut) {
Oracle storage oracle = oracles[oracleIndex];
FixedPoint.uq112x112 memory avg;
if (token == oracle.token0) {
avg = oracle.price0Average;
} else {
require(token == oracle.token1, 'OracleCreator: INVALID_TOKEN');
avg = oracle.price1Average;
}
amountOut = avg.mul(amountIn).decode144();
}
function isOracleFinalized(uint256 oracleIndex) external view returns (bool){
return oracles[oracleIndex].observationsCount == 2;
}
function getOracleDetails(uint256 oracleIndex) external view returns (Oracle memory) {
return oracles[oracleIndex];
}
}
// File: contracts/GnosisProtocolRelayer.sol
pragma solidity =0.6.6;
pragma experimental ABIEncoderV2;
contract GnosisProtocolRelayer {
using SafeMath for uint256;
event NewOrder(
uint256 indexed _orderIndex
);
event PlacedTrade(
uint256 indexed _orderIndex,
uint256 _gpOrderID,
uint16 buyToken,
uint16 sellToken,
uint32 validUntil,
uint128 expectedAmountMin,
uint128 tokenInAmount
);
event PlacedExactTrade(
uint16 _gpOrderID,
uint16 buyToken,
uint16 sellToken,
uint32 validFrom,
uint32 validUntil,
uint128 tokenOutAmount,
uint128 tokenInAmount
);
event WithdrawnExpiredOrder(
uint256 indexed _orderIndex
);
struct Order {
address tokenIn;
address tokenOut;
uint128 tokenInAmount;
uint128 minTokenOutAmount;
uint256 priceTolerance;
uint256 minReserve;
address oraclePair;
uint256 startDate;
uint256 deadline;
uint256 oracleId;
uint256 gpOrderId;
address factory;
bool executed;
}
uint256 public immutable GAS_ORACLE_UPDATE = 168364;
uint256 public immutable PARTS_PER_MILLION = 1000000;
uint256 public immutable BOUNTY = 0.01 ether;
uint256 public immutable ORACLE_WINDOW_TIME = 120; // 2 Minutes
uint32 public immutable BATCH_TIME;
uint32 public immutable UINT32_MAX_VALUE = 2**32 - 1;
uint128 public immutable UINT128_MAX_VALUE = 2**128 - 1;
address public immutable batchExchange;
address public immutable epochTokenLocker;
address payable public owner;
address public immutable WETH;
OracleCreator public oracleCreator;
uint256 public orderCount;
mapping(uint256 => Order) public orders;
mapping(address => bool) public exchangeFactoryWhitelist;
constructor(
address payable _owner,
address _batchExchange,
address _epochTokenLocker,
address[] memory _factoryWhitelist,
address _WETH,
OracleCreator _oracleCreater
) public {
require(_factoryWhitelist.length > 0, 'GnosisProtocolRelayer: MISSING_FACTORY_WHITELIST');
batchExchange = _batchExchange;
epochTokenLocker = _epochTokenLocker;
oracleCreator = _oracleCreater;
owner = _owner;
WETH = _WETH;
BATCH_TIME = IEpochTokenLocker(_epochTokenLocker).BATCH_TIME();
for (uint i=0; i < _factoryWhitelist.length; i++) {
exchangeFactoryWhitelist[_factoryWhitelist[i]] = true;
}
}
function orderTrade(
address tokenIn,
address tokenOut,
uint128 tokenInAmount,
uint128 minTokenOutAmount,
uint256 priceTolerance,
uint256 minReserve,
uint256 startDate,
uint256 deadline,
address factory
) external payable returns (uint256 orderIndex) {
require(exchangeFactoryWhitelist[factory], 'GnosisProtocolRelayer: INVALID_FACTORY');
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
require(tokenIn != tokenOut, 'GnosisProtocolRelayer: INVALID_PAIR');
require(tokenInAmount > 0 && minTokenOutAmount > 0, 'GnosisProtocolRelayer: INVALID_TOKEN_AMOUNT');
require(priceTolerance <= PARTS_PER_MILLION, 'GnosisProtocolRelayer: INVALID_TOLERANCE');
require(deadline <= UINT32_MAX_VALUE, 'GnosisProtocolRelayer: INVALID_DEADLINE');
require(block.timestamp <= deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
if (tokenIn == address(0)) {
require(address(this).balance >= tokenInAmount, 'GnosisProtocolRelayer: INSUFFICIENT_ETH');
tokenIn = WETH;
IWETH(WETH).deposit{value: tokenInAmount}();
} else if (tokenOut == address(0)) {
tokenOut = WETH;
}
require(IERC20(tokenIn).balanceOf(address(this)) >= tokenInAmount, 'GnosisProtocolRelayer: INSUFFIENT_TOKEN_IN');
address pair = _pair(tokenIn, tokenOut, factory);
require(pair != address(0), 'GnosisProtocolRelayer: UNKOWN_PAIR');
orderIndex = _OrderIndex();
orders[orderIndex] = Order({
tokenIn: tokenIn,
tokenOut: tokenOut,
tokenInAmount: tokenInAmount,
minTokenOutAmount: minTokenOutAmount,
priceTolerance: priceTolerance,
minReserve: minReserve,
oraclePair: pair,
startDate: startDate,
deadline: deadline,
oracleId: 0,
gpOrderId: 0,
factory: factory,
executed: false
});
/* Create an oracle to calculate average price */
orders[orderIndex].oracleId = oracleCreator.createOracle(ORACLE_WINDOW_TIME, pair);
emit NewOrder(orderIndex);
}
function placeTrade(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(!order.executed, 'GnosisProtocolRelayer: ORDER_EXECUTED');
require(oracleCreator.isOracleFinalized(order.oracleId) , 'GnosisProtocolRelayer: OBSERVATION_RUNNING');
require(block.timestamp <= order.deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
require(block.timestamp > order.startDate , 'GnosisProtocolRelayer: FUTURE_STARTDATE');
order.executed = true;
/* Approve token on Gnosis Protocol */
TransferHelper.safeApprove(order.tokenIn, epochTokenLocker, order.tokenInAmount);
/* Deposit token in Gnosis Protocol */
IEpochTokenLocker(epochTokenLocker).deposit(order.tokenIn, order.tokenInAmount);
/* Lookup TokenIds in Gnosis Protocol */
uint16 sellToken = IBatchExchange(batchExchange).tokenAddressToIdMap(order.tokenIn);
uint16 buyToken = IBatchExchange(batchExchange).tokenAddressToIdMap(order.tokenOut);
uint256 expectedAmount = oracleCreator.consult(
order.oracleId,
order.tokenIn == address(0) ? WETH : order.tokenIn,
order.tokenInAmount
);
uint256 expectedAmountMin = expectedAmount.sub(expectedAmount.mul(order.priceTolerance) / PARTS_PER_MILLION);
require(expectedAmountMin >= order.minTokenOutAmount, 'GnosisProtocolRelayer: INVALID_PRICE_RANGE');
require(expectedAmountMin <= UINT128_MAX_VALUE,'GnosisProtocolRelayer: AMOUNT_OUT_OF_RANGE');
/* Calculate batch Deadline (5 Minutes window) */
uint32 validUntil = uint32(order.deadline/BATCH_TIME);
uint256 gpOrderId = IBatchExchange(batchExchange).placeOrder(buyToken, sellToken, validUntil, uint128(expectedAmountMin), order.tokenInAmount);
order.gpOrderId = gpOrderId;
emit PlacedTrade(orderIndex, gpOrderId, buyToken, sellToken, validUntil, uint128(expectedAmountMin), order.tokenInAmount);
}
function placeExactTrade(
address tokenIn,
address tokenOut,
uint128 tokenInAmount,
uint128 tokenOutAmount,
uint256 startDate,
uint256 deadline
) external {
require(startDate < deadline, 'GnosisProtocolRelayer: INVALID_STARTDATE');
require(block.timestamp <= deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
require(deadline <= UINT32_MAX_VALUE, 'GnosisProtocolRelayer: INVALID_DEADLINE');
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
require(tokenIn != tokenOut, 'GnosisProtocolRelayer: INVALID_PAIR');
require(tokenInAmount > 0 && tokenOutAmount > 0, 'GnosisProtocolRelayer: INVALID_TOKEN_AMOUNT');
if (tokenIn == address(0)) {
require(address(this).balance >= tokenInAmount, 'GnosisProtocolRelayer: INSUFFICIENT_ETH');
tokenIn = WETH;
IWETH(WETH).deposit{value: tokenInAmount}();
} else if (tokenOut == address(0)) {
tokenOut = WETH;
}
require(IERC20(tokenIn).balanceOf(address(this)) >= tokenInAmount, 'GnosisProtocolRelayer: INSUFFIENT_TOKEN_IN');
/* Extend startDate if needed, to make sure the order will be placed on GP */
if(startDate <= block.timestamp){
startDate = block.timestamp.add(ORACLE_WINDOW_TIME) < deadline ? block.timestamp.add(ORACLE_WINDOW_TIME) : startDate;
}
/* Approve token on Gnosis Protocol */
TransferHelper.safeApprove(tokenIn, epochTokenLocker, tokenInAmount);
/* Deposit token in Gnosis Protocol */
IEpochTokenLocker(epochTokenLocker).deposit(tokenIn, tokenInAmount);
uint16[] memory sellTokens = new uint16[](1);
uint16[] memory buyTokens = new uint16[](1);
uint32[] memory validFroms = new uint32[](1);
uint32[] memory validUntils = new uint32[](1);
uint128[] memory buyAmounts = new uint128[](1);
uint128[] memory sellAmounts = new uint128[](1);
/* Lookup TokenIds in Gnosis Protocol */
sellTokens[0] = IBatchExchange(batchExchange).tokenAddressToIdMap(tokenIn);
buyTokens[0] = IBatchExchange(batchExchange).tokenAddressToIdMap(tokenOut);
validFroms[0] = uint32(startDate/BATCH_TIME);
validUntils[0] = uint32(deadline/BATCH_TIME);
buyAmounts[0] = tokenOutAmount;
sellAmounts[0] = tokenInAmount;
uint16[] memory gpOrderId = IBatchExchange(batchExchange).placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts);
emit PlacedExactTrade(gpOrderId[0], buyTokens[0], sellTokens[0], validFroms[0], validUntils[0], buyAmounts[0], sellAmounts[0]);
}
function cancelOrder(uint16 gpOrderId) external {
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
uint16[] memory orderArray = new uint16[](1);
orderArray[0] = uint16(gpOrderId);
IBatchExchange(batchExchange).cancelOrders(orderArray);
}
// Updates a price oracle and sends a bounty to msg.sender
function updateOracle(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(block.timestamp <= order.deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
require(!oracleCreator.isOracleFinalized(order.oracleId) , 'GnosisProtocolRelayer: OBSERVATION_ENDED');
require(block.timestamp > order.startDate, 'GnosisProtocolRelayer: FUTURE_STARTDATE');
uint256 amountBounty = GAS_ORACLE_UPDATE.mul(tx.gasprice).add(BOUNTY);
(uint reserve0, uint reserve1,) = IDXswapPair(order.oraclePair).getReserves();
address token0 = IDXswapPair(order.oraclePair).token0();
address tokenIn = order.tokenIn == address(0) ? WETH : order.tokenIn;
// Makes sure the reserve of TokenIn is higher then minReserve
if(tokenIn == token0){
require(
reserve0 >= order.minReserve,
'GnosisProtocolRelayer: RESERVE_TO_LOW'
);
} else {
require(
reserve1 >= order.minReserve,
'GnosisProtocolRelayer: RESERVE_TO_LOW'
);
}
oracleCreator.update(order.oracleId);
if(address(this).balance >= amountBounty){
TransferHelper.safeTransferETH(msg.sender, amountBounty);
}
}
function withdrawExpiredOrder(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(block.timestamp > order.deadline, 'GnosisProtocolRelayer: DEADLINE_NOT_REACHED');
require(!order.executed, 'GnosisProtocolRelayer: ORDER_EXECUTED');
if (order.tokenIn == WETH) {
IWETH(WETH).withdraw(order.tokenInAmount);
TransferHelper.safeTransferETH(owner, order.tokenInAmount);
} else {
TransferHelper.safeTransfer(order.tokenIn, owner, order.tokenInAmount);
}
order.executed = true;
emit WithdrawnExpiredOrder(orderIndex);
}
// Requests a token withdraw on GP
function requestWithdraw(address token, uint256 amount) public{
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
IEpochTokenLocker(epochTokenLocker).requestWithdraw(token,amount);
}
// Releases tokens from Gnosis Protocol
function withdrawToken(address token) public {
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
IEpochTokenLocker(epochTokenLocker).withdraw(address(this), token);
if (token == WETH) {
uint balance = IWETH(WETH).balanceOf(address(this));
IWETH(WETH).withdraw(balance);
ETHWithdraw(balance);
} else {
uint balance = IERC20(token).balanceOf(address(this));
ERC20Withdraw(token, balance);
}
}
// Internal function to return the pair address on a given factory
function _pair(address tokenA, address tokenB, address factory) internal view returns (address pair) {
require(exchangeFactoryWhitelist[factory], 'GnosisProtocolRelayer: INVALID_FACTORY');
pair = IDXswapFactory(factory).getPair(tokenA, tokenB);
}
// Returns an OrderIndex that is used to reference liquidity orders
function _OrderIndex() internal returns(uint256 orderIndex){
orderIndex = orderCount;
orderCount++;
}
function changeOwner(address payable _newOwner) public{
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
owner = _newOwner;
}
// Allows the owner to withdraw any ERC20 from the relayer
function ERC20Withdraw(address token, uint256 amount) public {
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
TransferHelper.safeTransfer(token, owner, amount);
}
// Allows the owner to withdraw any ETH amount from the relayer
function ETHWithdraw(uint256 amount) public {
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
TransferHelper.safeTransferETH(owner, amount);
}
// Returns the data of one specific order
function GetOrderDetails(uint256 orderIndex) external view returns (Order memory) {
return orders[orderIndex];
}
receive() external payable {}
} | bytes4(keccak256(bytes('approve(address,uint256)'))); | ) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: APPROVE_FAILED");
}
| 409,897 | [
1,
4625,
348,
7953,
560,
30,
225,
1731,
24,
12,
79,
24410,
581,
5034,
12,
3890,
2668,
12908,
537,
12,
2867,
16,
11890,
5034,
2506,
3719,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0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25,
24852,
27,
70,
23,
16,
358,
16,
460,
10019,
203,
3639,
2583,
12,
4768,
597,
261,
892,
18,
2469,
422,
374,
747,
24126,
18,
3922,
12,
892,
16,
261,
6430,
3719,
3631,
315,
5912,
2276,
30,
14410,
3373,
3412,
67,
11965,
8863,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Copyright 2020 DODO ZOO.
SPDX-License-Identifier: Apache-2.0
*/
pragma solidity 0.6.9;
pragma experimental ABIEncoderV2;
import {IDODOApproveProxy} from "../DODOApproveProxy.sol";
import {IERC20} from "../../intf/IERC20.sol";
import {IWETH} from "../../intf/IWETH.sol";
import {SafeMath} from "../../lib/SafeMath.sol";
import {UniversalERC20} from "../lib/UniversalERC20.sol";
import {SafeERC20} from "../../lib/SafeERC20.sol";
import {IDODOAdapter} from "../intf/IDODOAdapter.sol";
/**
* @title DODORouteProxy
* @author DODO Breeder
*
* @notice Entrance of Split trading in DODO platform
*/
contract DODORouteProxy {
using SafeMath for uint256;
using UniversalERC20 for IERC20;
// ============ Storage ============
address constant _ETH_ADDRESS_ = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public immutable _WETH_;
address public immutable _DODO_APPROVE_PROXY_;
struct PoolInfo {
uint256 direction;
uint256 poolEdition;
uint256 weight;
address pool;
address adapter;
bytes moreInfo;
}
// ============ Events ============
event OrderHistory(
address fromToken,
address toToken,
address sender,
uint256 fromAmount,
uint256 returnAmount
);
// ============ Modifiers ============
modifier judgeExpired(uint256 deadLine) {
require(deadLine >= block.timestamp, "DODORouteProxy: EXPIRED");
_;
}
fallback() external payable {}
receive() external payable {}
constructor (
address payable weth,
address dodoApproveProxy
) public {
_WETH_ = weth;
_DODO_APPROVE_PROXY_ = dodoApproveProxy;
}
function mixSwap(
address fromToken,
address toToken,
uint256 fromTokenAmount,
uint256 minReturnAmount,
address[] memory mixAdapters,
address[] memory mixPairs,
address[] memory assetTo,
uint256 directions,
bool,
uint256 deadLine
) external payable judgeExpired(deadLine) returns (uint256 returnAmount) {
require(mixPairs.length > 0, "DODORouteProxy: PAIRS_EMPTY");
require(mixPairs.length == mixAdapters.length, "DODORouteProxy: PAIR_ADAPTER_NOT_MATCH");
require(mixPairs.length == assetTo.length - 1, "DODORouteProxy: PAIR_ASSETTO_NOT_MATCH");
require(minReturnAmount > 0, "DODORouteProxy: RETURN_AMOUNT_ZERO");
address _fromToken = fromToken;
address _toToken = toToken;
uint256 _fromTokenAmount = fromTokenAmount;
uint256 toTokenOriginBalance = IERC20(_toToken).universalBalanceOf(msg.sender);
_deposit(msg.sender, assetTo[0], _fromToken, _fromTokenAmount, _fromToken == _ETH_ADDRESS_);
for (uint256 i = 0; i < mixPairs.length; i++) {
if (directions & 1 == 0) {
IDODOAdapter(mixAdapters[i]).sellBase(assetTo[i + 1],mixPairs[i], "");
} else {
IDODOAdapter(mixAdapters[i]).sellQuote(assetTo[i + 1],mixPairs[i], "");
}
directions = directions >> 1;
}
if(_toToken == _ETH_ADDRESS_) {
returnAmount = IWETH(_WETH_).balanceOf(address(this));
IWETH(_WETH_).withdraw(returnAmount);
msg.sender.transfer(returnAmount);
}else {
returnAmount = IERC20(_toToken).tokenBalanceOf(msg.sender).sub(toTokenOriginBalance);
}
require(returnAmount >= minReturnAmount, "DODORouteProxy: Return amount is not enough");
emit OrderHistory(
_fromToken,
_toToken,
msg.sender,
_fromTokenAmount,
returnAmount
);
}
function dodoMutliSwap(
uint256 fromTokenAmount,
uint256 minReturnAmount,
uint256[] memory totalWeight,
uint256[] memory splitNumber,
address[] memory midToken,
address[] memory assetFrom,
bytes[] memory sequence,
uint256 deadLine
) external payable judgeExpired(deadLine) returns (uint256 returnAmount) {
require(assetFrom.length == splitNumber.length, 'DODORouteProxy: PAIR_ASSETTO_NOT_MATCH');
require(minReturnAmount > 0, "DODORouteProxy: RETURN_AMOUNT_ZERO");
uint256 _fromTokenAmount = fromTokenAmount;
address fromToken = midToken[0];
address toToken = midToken[midToken.length - 1];
uint256 toTokenOriginBalance = IERC20(toToken).universalBalanceOf(msg.sender);
_deposit(msg.sender, assetFrom[0], fromToken, _fromTokenAmount, fromToken == _ETH_ADDRESS_);
_multiSwap(totalWeight, midToken, splitNumber, sequence, assetFrom);
if(toToken == _ETH_ADDRESS_) {
returnAmount = IWETH(_WETH_).balanceOf(address(this));
IWETH(_WETH_).withdraw(returnAmount);
msg.sender.transfer(returnAmount);
}else {
returnAmount = IERC20(toToken).tokenBalanceOf(msg.sender).sub(toTokenOriginBalance);
}
require(returnAmount >= minReturnAmount, "DODORouteProxy: Return amount is not enough");
emit OrderHistory(
fromToken,
toToken,
msg.sender,
_fromTokenAmount,
returnAmount
);
}
//====================== internal =======================
function _multiSwap(
uint256[] memory totalWeight,
address[] memory midToken,
uint256[] memory splitNumber,
bytes[] memory swapSequence,
address[] memory assetFrom
) internal {
for(uint256 i = 1; i < splitNumber.length; i++) {
// define midtoken address, ETH -> WETH address
uint256 curTotalAmount = IERC20(midToken[i]).tokenBalanceOf(assetFrom[i-1]);
uint256 curTotalWeight = totalWeight[i-1];
for(uint256 j = splitNumber[i-1]; j < splitNumber[i]; j++) {
PoolInfo memory curPoolInfo;
{
(address pool, address adapter, uint256 mixPara, bytes memory moreInfo) = abi.decode(swapSequence[j], (address, address, uint256, bytes));
curPoolInfo.direction = mixPara >> 17;
curPoolInfo.weight = (0xffff & mixPara) >> 9;
curPoolInfo.poolEdition = (0xff & mixPara);
curPoolInfo.pool = pool;
curPoolInfo.adapter = adapter;
curPoolInfo.moreInfo = moreInfo;
}
if(assetFrom[i-1] == address(this)) {
uint256 curAmount = curTotalAmount.div(curTotalWeight).mul(curPoolInfo.weight);
if(curPoolInfo.poolEdition == 1) {
//For using transferFrom pool (like dodoV1, Curve)
IERC20(midToken[i]).transfer(curPoolInfo.adapter, curAmount);
} else {
//For using transfer pool (like dodoV2)
IERC20(midToken[i]).transfer(curPoolInfo.pool, curAmount);
}
}
if(curPoolInfo.direction == 0) {
IDODOAdapter(curPoolInfo.adapter).sellBase(assetFrom[i], curPoolInfo.pool, curPoolInfo.moreInfo);
} else {
IDODOAdapter(curPoolInfo.adapter).sellQuote(assetFrom[i], curPoolInfo.pool, curPoolInfo.moreInfo);
}
}
}
}
function _deposit(
address from,
address to,
address token,
uint256 amount,
bool isETH
) internal {
if (isETH) {
if (amount > 0) {
IWETH(_WETH_).deposit{value: amount}();
if (to != address(this)) SafeERC20.safeTransfer(IERC20(_WETH_), to, amount);
}
} else {
IDODOApproveProxy(_DODO_APPROVE_PROXY_).claimTokens(token, from, to, amount);
}
}
} | * @title DODORouteProxy @author DODO Breeder @notice Entrance of Split trading in DODO platform/ ============ Storage ============ | contract DODORouteProxy {
using SafeMath for uint256;
using UniversalERC20 for IERC20;
address constant _ETH_ADDRESS_ = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public immutable _WETH_;
address public immutable _DODO_APPROVE_PROXY_;
import {IDODOApproveProxy} from "../DODOApproveProxy.sol";
import {IERC20} from "../../intf/IERC20.sol";
import {IWETH} from "../../intf/IWETH.sol";
import {SafeMath} from "../../lib/SafeMath.sol";
import {UniversalERC20} from "../lib/UniversalERC20.sol";
import {SafeERC20} from "../../lib/SafeERC20.sol";
import {IDODOAdapter} from "../intf/IDODOAdapter.sol";
struct PoolInfo {
uint256 direction;
uint256 poolEdition;
uint256 weight;
address pool;
address adapter;
bytes moreInfo;
}
event OrderHistory(
address fromToken,
address toToken,
address sender,
uint256 fromAmount,
uint256 returnAmount
);
modifier judgeExpired(uint256 deadLine) {
require(deadLine >= block.timestamp, "DODORouteProxy: EXPIRED");
_;
}
constructor (
address payable weth,
address dodoApproveProxy
fallback() external payable {}
receive() external payable {}
) public {
_WETH_ = weth;
_DODO_APPROVE_PROXY_ = dodoApproveProxy;
}
function mixSwap(
address fromToken,
address toToken,
uint256 fromTokenAmount,
uint256 minReturnAmount,
address[] memory mixAdapters,
address[] memory mixPairs,
address[] memory assetTo,
uint256 directions,
bool,
uint256 deadLine
) external payable judgeExpired(deadLine) returns (uint256 returnAmount) {
require(mixPairs.length > 0, "DODORouteProxy: PAIRS_EMPTY");
require(mixPairs.length == mixAdapters.length, "DODORouteProxy: PAIR_ADAPTER_NOT_MATCH");
require(mixPairs.length == assetTo.length - 1, "DODORouteProxy: PAIR_ASSETTO_NOT_MATCH");
require(minReturnAmount > 0, "DODORouteProxy: RETURN_AMOUNT_ZERO");
address _fromToken = fromToken;
address _toToken = toToken;
uint256 _fromTokenAmount = fromTokenAmount;
uint256 toTokenOriginBalance = IERC20(_toToken).universalBalanceOf(msg.sender);
_deposit(msg.sender, assetTo[0], _fromToken, _fromTokenAmount, _fromToken == _ETH_ADDRESS_);
for (uint256 i = 0; i < mixPairs.length; i++) {
if (directions & 1 == 0) {
IDODOAdapter(mixAdapters[i]).sellBase(assetTo[i + 1],mixPairs[i], "");
IDODOAdapter(mixAdapters[i]).sellQuote(assetTo[i + 1],mixPairs[i], "");
}
directions = directions >> 1;
}
if(_toToken == _ETH_ADDRESS_) {
returnAmount = IWETH(_WETH_).balanceOf(address(this));
IWETH(_WETH_).withdraw(returnAmount);
msg.sender.transfer(returnAmount);
returnAmount = IERC20(_toToken).tokenBalanceOf(msg.sender).sub(toTokenOriginBalance);
}
require(returnAmount >= minReturnAmount, "DODORouteProxy: Return amount is not enough");
emit OrderHistory(
_fromToken,
_toToken,
msg.sender,
_fromTokenAmount,
returnAmount
);
}
function mixSwap(
address fromToken,
address toToken,
uint256 fromTokenAmount,
uint256 minReturnAmount,
address[] memory mixAdapters,
address[] memory mixPairs,
address[] memory assetTo,
uint256 directions,
bool,
uint256 deadLine
) external payable judgeExpired(deadLine) returns (uint256 returnAmount) {
require(mixPairs.length > 0, "DODORouteProxy: PAIRS_EMPTY");
require(mixPairs.length == mixAdapters.length, "DODORouteProxy: PAIR_ADAPTER_NOT_MATCH");
require(mixPairs.length == assetTo.length - 1, "DODORouteProxy: PAIR_ASSETTO_NOT_MATCH");
require(minReturnAmount > 0, "DODORouteProxy: RETURN_AMOUNT_ZERO");
address _fromToken = fromToken;
address _toToken = toToken;
uint256 _fromTokenAmount = fromTokenAmount;
uint256 toTokenOriginBalance = IERC20(_toToken).universalBalanceOf(msg.sender);
_deposit(msg.sender, assetTo[0], _fromToken, _fromTokenAmount, _fromToken == _ETH_ADDRESS_);
for (uint256 i = 0; i < mixPairs.length; i++) {
if (directions & 1 == 0) {
IDODOAdapter(mixAdapters[i]).sellBase(assetTo[i + 1],mixPairs[i], "");
IDODOAdapter(mixAdapters[i]).sellQuote(assetTo[i + 1],mixPairs[i], "");
}
directions = directions >> 1;
}
if(_toToken == _ETH_ADDRESS_) {
returnAmount = IWETH(_WETH_).balanceOf(address(this));
IWETH(_WETH_).withdraw(returnAmount);
msg.sender.transfer(returnAmount);
returnAmount = IERC20(_toToken).tokenBalanceOf(msg.sender).sub(toTokenOriginBalance);
}
require(returnAmount >= minReturnAmount, "DODORouteProxy: Return amount is not enough");
emit OrderHistory(
_fromToken,
_toToken,
msg.sender,
_fromTokenAmount,
returnAmount
);
}
function mixSwap(
address fromToken,
address toToken,
uint256 fromTokenAmount,
uint256 minReturnAmount,
address[] memory mixAdapters,
address[] memory mixPairs,
address[] memory assetTo,
uint256 directions,
bool,
uint256 deadLine
) external payable judgeExpired(deadLine) returns (uint256 returnAmount) {
require(mixPairs.length > 0, "DODORouteProxy: PAIRS_EMPTY");
require(mixPairs.length == mixAdapters.length, "DODORouteProxy: PAIR_ADAPTER_NOT_MATCH");
require(mixPairs.length == assetTo.length - 1, "DODORouteProxy: PAIR_ASSETTO_NOT_MATCH");
require(minReturnAmount > 0, "DODORouteProxy: RETURN_AMOUNT_ZERO");
address _fromToken = fromToken;
address _toToken = toToken;
uint256 _fromTokenAmount = fromTokenAmount;
uint256 toTokenOriginBalance = IERC20(_toToken).universalBalanceOf(msg.sender);
_deposit(msg.sender, assetTo[0], _fromToken, _fromTokenAmount, _fromToken == _ETH_ADDRESS_);
for (uint256 i = 0; i < mixPairs.length; i++) {
if (directions & 1 == 0) {
IDODOAdapter(mixAdapters[i]).sellBase(assetTo[i + 1],mixPairs[i], "");
IDODOAdapter(mixAdapters[i]).sellQuote(assetTo[i + 1],mixPairs[i], "");
}
directions = directions >> 1;
}
if(_toToken == _ETH_ADDRESS_) {
returnAmount = IWETH(_WETH_).balanceOf(address(this));
IWETH(_WETH_).withdraw(returnAmount);
msg.sender.transfer(returnAmount);
returnAmount = IERC20(_toToken).tokenBalanceOf(msg.sender).sub(toTokenOriginBalance);
}
require(returnAmount >= minReturnAmount, "DODORouteProxy: Return amount is not enough");
emit OrderHistory(
_fromToken,
_toToken,
msg.sender,
_fromTokenAmount,
returnAmount
);
}
} else {
function mixSwap(
address fromToken,
address toToken,
uint256 fromTokenAmount,
uint256 minReturnAmount,
address[] memory mixAdapters,
address[] memory mixPairs,
address[] memory assetTo,
uint256 directions,
bool,
uint256 deadLine
) external payable judgeExpired(deadLine) returns (uint256 returnAmount) {
require(mixPairs.length > 0, "DODORouteProxy: PAIRS_EMPTY");
require(mixPairs.length == mixAdapters.length, "DODORouteProxy: PAIR_ADAPTER_NOT_MATCH");
require(mixPairs.length == assetTo.length - 1, "DODORouteProxy: PAIR_ASSETTO_NOT_MATCH");
require(minReturnAmount > 0, "DODORouteProxy: RETURN_AMOUNT_ZERO");
address _fromToken = fromToken;
address _toToken = toToken;
uint256 _fromTokenAmount = fromTokenAmount;
uint256 toTokenOriginBalance = IERC20(_toToken).universalBalanceOf(msg.sender);
_deposit(msg.sender, assetTo[0], _fromToken, _fromTokenAmount, _fromToken == _ETH_ADDRESS_);
for (uint256 i = 0; i < mixPairs.length; i++) {
if (directions & 1 == 0) {
IDODOAdapter(mixAdapters[i]).sellBase(assetTo[i + 1],mixPairs[i], "");
IDODOAdapter(mixAdapters[i]).sellQuote(assetTo[i + 1],mixPairs[i], "");
}
directions = directions >> 1;
}
if(_toToken == _ETH_ADDRESS_) {
returnAmount = IWETH(_WETH_).balanceOf(address(this));
IWETH(_WETH_).withdraw(returnAmount);
msg.sender.transfer(returnAmount);
returnAmount = IERC20(_toToken).tokenBalanceOf(msg.sender).sub(toTokenOriginBalance);
}
require(returnAmount >= minReturnAmount, "DODORouteProxy: Return amount is not enough");
emit OrderHistory(
_fromToken,
_toToken,
msg.sender,
_fromTokenAmount,
returnAmount
);
}
}else {
function dodoMutliSwap(
uint256 fromTokenAmount,
uint256 minReturnAmount,
uint256[] memory totalWeight,
uint256[] memory splitNumber,
address[] memory midToken,
address[] memory assetFrom,
bytes[] memory sequence,
uint256 deadLine
) external payable judgeExpired(deadLine) returns (uint256 returnAmount) {
require(assetFrom.length == splitNumber.length, 'DODORouteProxy: PAIR_ASSETTO_NOT_MATCH');
require(minReturnAmount > 0, "DODORouteProxy: RETURN_AMOUNT_ZERO");
uint256 _fromTokenAmount = fromTokenAmount;
address fromToken = midToken[0];
address toToken = midToken[midToken.length - 1];
uint256 toTokenOriginBalance = IERC20(toToken).universalBalanceOf(msg.sender);
_deposit(msg.sender, assetFrom[0], fromToken, _fromTokenAmount, fromToken == _ETH_ADDRESS_);
_multiSwap(totalWeight, midToken, splitNumber, sequence, assetFrom);
if(toToken == _ETH_ADDRESS_) {
returnAmount = IWETH(_WETH_).balanceOf(address(this));
IWETH(_WETH_).withdraw(returnAmount);
msg.sender.transfer(returnAmount);
returnAmount = IERC20(toToken).tokenBalanceOf(msg.sender).sub(toTokenOriginBalance);
}
require(returnAmount >= minReturnAmount, "DODORouteProxy: Return amount is not enough");
emit OrderHistory(
fromToken,
toToken,
msg.sender,
_fromTokenAmount,
returnAmount
);
}
function dodoMutliSwap(
uint256 fromTokenAmount,
uint256 minReturnAmount,
uint256[] memory totalWeight,
uint256[] memory splitNumber,
address[] memory midToken,
address[] memory assetFrom,
bytes[] memory sequence,
uint256 deadLine
) external payable judgeExpired(deadLine) returns (uint256 returnAmount) {
require(assetFrom.length == splitNumber.length, 'DODORouteProxy: PAIR_ASSETTO_NOT_MATCH');
require(minReturnAmount > 0, "DODORouteProxy: RETURN_AMOUNT_ZERO");
uint256 _fromTokenAmount = fromTokenAmount;
address fromToken = midToken[0];
address toToken = midToken[midToken.length - 1];
uint256 toTokenOriginBalance = IERC20(toToken).universalBalanceOf(msg.sender);
_deposit(msg.sender, assetFrom[0], fromToken, _fromTokenAmount, fromToken == _ETH_ADDRESS_);
_multiSwap(totalWeight, midToken, splitNumber, sequence, assetFrom);
if(toToken == _ETH_ADDRESS_) {
returnAmount = IWETH(_WETH_).balanceOf(address(this));
IWETH(_WETH_).withdraw(returnAmount);
msg.sender.transfer(returnAmount);
returnAmount = IERC20(toToken).tokenBalanceOf(msg.sender).sub(toTokenOriginBalance);
}
require(returnAmount >= minReturnAmount, "DODORouteProxy: Return amount is not enough");
emit OrderHistory(
fromToken,
toToken,
msg.sender,
_fromTokenAmount,
returnAmount
);
}
}else {
function _multiSwap(
uint256[] memory totalWeight,
address[] memory midToken,
uint256[] memory splitNumber,
bytes[] memory swapSequence,
address[] memory assetFrom
) internal {
for(uint256 i = 1; i < splitNumber.length; i++) {
uint256 curTotalAmount = IERC20(midToken[i]).tokenBalanceOf(assetFrom[i-1]);
uint256 curTotalWeight = totalWeight[i-1];
for(uint256 j = splitNumber[i-1]; j < splitNumber[i]; j++) {
PoolInfo memory curPoolInfo;
{
(address pool, address adapter, uint256 mixPara, bytes memory moreInfo) = abi.decode(swapSequence[j], (address, address, uint256, bytes));
curPoolInfo.direction = mixPara >> 17;
curPoolInfo.weight = (0xffff & mixPara) >> 9;
curPoolInfo.poolEdition = (0xff & mixPara);
curPoolInfo.pool = pool;
curPoolInfo.adapter = adapter;
curPoolInfo.moreInfo = moreInfo;
}
if(assetFrom[i-1] == address(this)) {
uint256 curAmount = curTotalAmount.div(curTotalWeight).mul(curPoolInfo.weight);
if(curPoolInfo.poolEdition == 1) {
IERC20(midToken[i]).transfer(curPoolInfo.adapter, curAmount);
IERC20(midToken[i]).transfer(curPoolInfo.pool, curAmount);
}
}
if(curPoolInfo.direction == 0) {
IDODOAdapter(curPoolInfo.adapter).sellBase(assetFrom[i], curPoolInfo.pool, curPoolInfo.moreInfo);
IDODOAdapter(curPoolInfo.adapter).sellQuote(assetFrom[i], curPoolInfo.pool, curPoolInfo.moreInfo);
}
}
}
}
function _multiSwap(
uint256[] memory totalWeight,
address[] memory midToken,
uint256[] memory splitNumber,
bytes[] memory swapSequence,
address[] memory assetFrom
) internal {
for(uint256 i = 1; i < splitNumber.length; i++) {
uint256 curTotalAmount = IERC20(midToken[i]).tokenBalanceOf(assetFrom[i-1]);
uint256 curTotalWeight = totalWeight[i-1];
for(uint256 j = splitNumber[i-1]; j < splitNumber[i]; j++) {
PoolInfo memory curPoolInfo;
{
(address pool, address adapter, uint256 mixPara, bytes memory moreInfo) = abi.decode(swapSequence[j], (address, address, uint256, bytes));
curPoolInfo.direction = mixPara >> 17;
curPoolInfo.weight = (0xffff & mixPara) >> 9;
curPoolInfo.poolEdition = (0xff & mixPara);
curPoolInfo.pool = pool;
curPoolInfo.adapter = adapter;
curPoolInfo.moreInfo = moreInfo;
}
if(assetFrom[i-1] == address(this)) {
uint256 curAmount = curTotalAmount.div(curTotalWeight).mul(curPoolInfo.weight);
if(curPoolInfo.poolEdition == 1) {
IERC20(midToken[i]).transfer(curPoolInfo.adapter, curAmount);
IERC20(midToken[i]).transfer(curPoolInfo.pool, curAmount);
}
}
if(curPoolInfo.direction == 0) {
IDODOAdapter(curPoolInfo.adapter).sellBase(assetFrom[i], curPoolInfo.pool, curPoolInfo.moreInfo);
IDODOAdapter(curPoolInfo.adapter).sellQuote(assetFrom[i], curPoolInfo.pool, curPoolInfo.moreInfo);
}
}
}
}
function _multiSwap(
uint256[] memory totalWeight,
address[] memory midToken,
uint256[] memory splitNumber,
bytes[] memory swapSequence,
address[] memory assetFrom
) internal {
for(uint256 i = 1; i < splitNumber.length; i++) {
uint256 curTotalAmount = IERC20(midToken[i]).tokenBalanceOf(assetFrom[i-1]);
uint256 curTotalWeight = totalWeight[i-1];
for(uint256 j = splitNumber[i-1]; j < splitNumber[i]; j++) {
PoolInfo memory curPoolInfo;
{
(address pool, address adapter, uint256 mixPara, bytes memory moreInfo) = abi.decode(swapSequence[j], (address, address, uint256, bytes));
curPoolInfo.direction = mixPara >> 17;
curPoolInfo.weight = (0xffff & mixPara) >> 9;
curPoolInfo.poolEdition = (0xff & mixPara);
curPoolInfo.pool = pool;
curPoolInfo.adapter = adapter;
curPoolInfo.moreInfo = moreInfo;
}
if(assetFrom[i-1] == address(this)) {
uint256 curAmount = curTotalAmount.div(curTotalWeight).mul(curPoolInfo.weight);
if(curPoolInfo.poolEdition == 1) {
IERC20(midToken[i]).transfer(curPoolInfo.adapter, curAmount);
IERC20(midToken[i]).transfer(curPoolInfo.pool, curAmount);
}
}
if(curPoolInfo.direction == 0) {
IDODOAdapter(curPoolInfo.adapter).sellBase(assetFrom[i], curPoolInfo.pool, curPoolInfo.moreInfo);
IDODOAdapter(curPoolInfo.adapter).sellQuote(assetFrom[i], curPoolInfo.pool, curPoolInfo.moreInfo);
}
}
}
}
function _multiSwap(
uint256[] memory totalWeight,
address[] memory midToken,
uint256[] memory splitNumber,
bytes[] memory swapSequence,
address[] memory assetFrom
) internal {
for(uint256 i = 1; i < splitNumber.length; i++) {
uint256 curTotalAmount = IERC20(midToken[i]).tokenBalanceOf(assetFrom[i-1]);
uint256 curTotalWeight = totalWeight[i-1];
for(uint256 j = splitNumber[i-1]; j < splitNumber[i]; j++) {
PoolInfo memory curPoolInfo;
{
(address pool, address adapter, uint256 mixPara, bytes memory moreInfo) = abi.decode(swapSequence[j], (address, address, uint256, bytes));
curPoolInfo.direction = mixPara >> 17;
curPoolInfo.weight = (0xffff & mixPara) >> 9;
curPoolInfo.poolEdition = (0xff & mixPara);
curPoolInfo.pool = pool;
curPoolInfo.adapter = adapter;
curPoolInfo.moreInfo = moreInfo;
}
if(assetFrom[i-1] == address(this)) {
uint256 curAmount = curTotalAmount.div(curTotalWeight).mul(curPoolInfo.weight);
if(curPoolInfo.poolEdition == 1) {
IERC20(midToken[i]).transfer(curPoolInfo.adapter, curAmount);
IERC20(midToken[i]).transfer(curPoolInfo.pool, curAmount);
}
}
if(curPoolInfo.direction == 0) {
IDODOAdapter(curPoolInfo.adapter).sellBase(assetFrom[i], curPoolInfo.pool, curPoolInfo.moreInfo);
IDODOAdapter(curPoolInfo.adapter).sellQuote(assetFrom[i], curPoolInfo.pool, curPoolInfo.moreInfo);
}
}
}
}
function _multiSwap(
uint256[] memory totalWeight,
address[] memory midToken,
uint256[] memory splitNumber,
bytes[] memory swapSequence,
address[] memory assetFrom
) internal {
for(uint256 i = 1; i < splitNumber.length; i++) {
uint256 curTotalAmount = IERC20(midToken[i]).tokenBalanceOf(assetFrom[i-1]);
uint256 curTotalWeight = totalWeight[i-1];
for(uint256 j = splitNumber[i-1]; j < splitNumber[i]; j++) {
PoolInfo memory curPoolInfo;
{
(address pool, address adapter, uint256 mixPara, bytes memory moreInfo) = abi.decode(swapSequence[j], (address, address, uint256, bytes));
curPoolInfo.direction = mixPara >> 17;
curPoolInfo.weight = (0xffff & mixPara) >> 9;
curPoolInfo.poolEdition = (0xff & mixPara);
curPoolInfo.pool = pool;
curPoolInfo.adapter = adapter;
curPoolInfo.moreInfo = moreInfo;
}
if(assetFrom[i-1] == address(this)) {
uint256 curAmount = curTotalAmount.div(curTotalWeight).mul(curPoolInfo.weight);
if(curPoolInfo.poolEdition == 1) {
IERC20(midToken[i]).transfer(curPoolInfo.adapter, curAmount);
IERC20(midToken[i]).transfer(curPoolInfo.pool, curAmount);
}
}
if(curPoolInfo.direction == 0) {
IDODOAdapter(curPoolInfo.adapter).sellBase(assetFrom[i], curPoolInfo.pool, curPoolInfo.moreInfo);
IDODOAdapter(curPoolInfo.adapter).sellQuote(assetFrom[i], curPoolInfo.pool, curPoolInfo.moreInfo);
}
}
}
}
function _multiSwap(
uint256[] memory totalWeight,
address[] memory midToken,
uint256[] memory splitNumber,
bytes[] memory swapSequence,
address[] memory assetFrom
) internal {
for(uint256 i = 1; i < splitNumber.length; i++) {
uint256 curTotalAmount = IERC20(midToken[i]).tokenBalanceOf(assetFrom[i-1]);
uint256 curTotalWeight = totalWeight[i-1];
for(uint256 j = splitNumber[i-1]; j < splitNumber[i]; j++) {
PoolInfo memory curPoolInfo;
{
(address pool, address adapter, uint256 mixPara, bytes memory moreInfo) = abi.decode(swapSequence[j], (address, address, uint256, bytes));
curPoolInfo.direction = mixPara >> 17;
curPoolInfo.weight = (0xffff & mixPara) >> 9;
curPoolInfo.poolEdition = (0xff & mixPara);
curPoolInfo.pool = pool;
curPoolInfo.adapter = adapter;
curPoolInfo.moreInfo = moreInfo;
}
if(assetFrom[i-1] == address(this)) {
uint256 curAmount = curTotalAmount.div(curTotalWeight).mul(curPoolInfo.weight);
if(curPoolInfo.poolEdition == 1) {
IERC20(midToken[i]).transfer(curPoolInfo.adapter, curAmount);
IERC20(midToken[i]).transfer(curPoolInfo.pool, curAmount);
}
}
if(curPoolInfo.direction == 0) {
IDODOAdapter(curPoolInfo.adapter).sellBase(assetFrom[i], curPoolInfo.pool, curPoolInfo.moreInfo);
IDODOAdapter(curPoolInfo.adapter).sellQuote(assetFrom[i], curPoolInfo.pool, curPoolInfo.moreInfo);
}
}
}
}
} else {
function _multiSwap(
uint256[] memory totalWeight,
address[] memory midToken,
uint256[] memory splitNumber,
bytes[] memory swapSequence,
address[] memory assetFrom
) internal {
for(uint256 i = 1; i < splitNumber.length; i++) {
uint256 curTotalAmount = IERC20(midToken[i]).tokenBalanceOf(assetFrom[i-1]);
uint256 curTotalWeight = totalWeight[i-1];
for(uint256 j = splitNumber[i-1]; j < splitNumber[i]; j++) {
PoolInfo memory curPoolInfo;
{
(address pool, address adapter, uint256 mixPara, bytes memory moreInfo) = abi.decode(swapSequence[j], (address, address, uint256, bytes));
curPoolInfo.direction = mixPara >> 17;
curPoolInfo.weight = (0xffff & mixPara) >> 9;
curPoolInfo.poolEdition = (0xff & mixPara);
curPoolInfo.pool = pool;
curPoolInfo.adapter = adapter;
curPoolInfo.moreInfo = moreInfo;
}
if(assetFrom[i-1] == address(this)) {
uint256 curAmount = curTotalAmount.div(curTotalWeight).mul(curPoolInfo.weight);
if(curPoolInfo.poolEdition == 1) {
IERC20(midToken[i]).transfer(curPoolInfo.adapter, curAmount);
IERC20(midToken[i]).transfer(curPoolInfo.pool, curAmount);
}
}
if(curPoolInfo.direction == 0) {
IDODOAdapter(curPoolInfo.adapter).sellBase(assetFrom[i], curPoolInfo.pool, curPoolInfo.moreInfo);
IDODOAdapter(curPoolInfo.adapter).sellQuote(assetFrom[i], curPoolInfo.pool, curPoolInfo.moreInfo);
}
}
}
}
} else {
function _deposit(
address from,
address to,
address token,
uint256 amount,
bool isETH
) internal {
if (isETH) {
if (amount > 0) {
if (to != address(this)) SafeERC20.safeTransfer(IERC20(_WETH_), to, amount);
}
IDODOApproveProxy(_DODO_APPROVE_PROXY_).claimTokens(token, from, to, amount);
}
}
function _deposit(
address from,
address to,
address token,
uint256 amount,
bool isETH
) internal {
if (isETH) {
if (amount > 0) {
if (to != address(this)) SafeERC20.safeTransfer(IERC20(_WETH_), to, amount);
}
IDODOApproveProxy(_DODO_APPROVE_PROXY_).claimTokens(token, from, to, amount);
}
}
function _deposit(
address from,
address to,
address token,
uint256 amount,
bool isETH
) internal {
if (isETH) {
if (amount > 0) {
if (to != address(this)) SafeERC20.safeTransfer(IERC20(_WETH_), to, amount);
}
IDODOApproveProxy(_DODO_APPROVE_PROXY_).claimTokens(token, from, to, amount);
}
}
IWETH(_WETH_).deposit{value: amount}();
} else {
} | 12,807,015 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
2649,
463,
1212,
916,
2571,
3886,
632,
4161,
463,
2311,
605,
15656,
264,
632,
20392,
1374,
313,
1359,
434,
5385,
1284,
7459,
316,
463,
2311,
4072,
19,
422,
1432,
631,
5235,
422,
1432,
631,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
463,
1212,
916,
2571,
3886,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
27705,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
203,
565,
1758,
5381,
389,
1584,
44,
67,
15140,
67,
273,
374,
17432,
1340,
1340,
41,
1340,
73,
41,
73,
41,
1340,
41,
73,
41,
73,
41,
1340,
9383,
41,
1340,
1340,
41,
1340,
1340,
1340,
73,
9383,
73,
41,
31,
203,
565,
1758,
1071,
11732,
389,
59,
1584,
44,
67,
31,
203,
565,
1758,
1071,
11732,
389,
40,
2311,
67,
2203,
3373,
3412,
67,
16085,
67,
31,
203,
203,
203,
203,
5666,
288,
734,
2311,
12053,
537,
3886,
97,
628,
315,
6216,
40,
2311,
12053,
537,
3886,
18,
18281,
14432,
203,
5666,
288,
45,
654,
39,
3462,
97,
628,
315,
16644,
17655,
19,
45,
654,
39,
3462,
18,
18281,
14432,
203,
5666,
288,
45,
59,
1584,
44,
97,
628,
315,
16644,
17655,
19,
45,
59,
1584,
44,
18,
18281,
14432,
203,
5666,
288,
9890,
10477,
97,
628,
315,
16644,
2941,
19,
9890,
10477,
18,
18281,
14432,
203,
5666,
288,
984,
14651,
654,
39,
3462,
97,
628,
315,
6216,
2941,
19,
984,
14651,
654,
39,
3462,
18,
18281,
14432,
203,
5666,
288,
9890,
654,
39,
3462,
97,
628,
315,
16644,
2941,
19,
9890,
654,
39,
3462,
18,
18281,
14432,
203,
5666,
288,
734,
2311,
4216,
97,
628,
315,
6216,
17655,
19,
734,
2311,
4216,
18,
18281,
14432,
203,
565,
1958,
8828,
966,
288,
203,
3639,
2254,
5034,
4068,
31,
203,
3639,
2254,
5034,
2845,
41,
1460,
31,
203,
3639,
2254,
5034,
3119,
31,
203,
3639,
1758,
2845,
31,
203,
3639,
1758,
4516,
31,
203,
3639,
1731,
1898,
966,
31,
203,
565,
289,
203,
203,
377,
871,
4347,
5623,
12,
203,
3639,
1758,
628,
1345,
16,
203,
3639,
1758,
358,
1345,
16,
203,
3639,
1758,
5793,
16,
203,
3639,
2254,
5034,
628,
6275,
16,
203,
3639,
2254,
5034,
327,
6275,
203,
565,
11272,
203,
203,
203,
203,
565,
9606,
525,
27110,
10556,
12,
11890,
5034,
8363,
1670,
13,
288,
203,
3639,
2583,
12,
22097,
1670,
1545,
1203,
18,
5508,
16,
315,
40,
1212,
916,
2571,
3886,
30,
31076,
5879,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
203,
203,
565,
3885,
261,
203,
3639,
1758,
8843,
429,
341,
546,
16,
203,
3639,
1758,
302,
7370,
12053,
537,
3886,
203,
565,
5922,
1435,
3903,
8843,
429,
2618,
203,
565,
6798,
1435,
3903,
8843,
429,
2618,
203,
565,
262,
1071,
288,
203,
3639,
389,
59,
1584,
44,
67,
273,
341,
546,
31,
203,
3639,
389,
40,
2311,
67,
2203,
3373,
3412,
67,
16085,
67,
273,
302,
7370,
12053,
537,
3886,
31,
203,
565,
289,
203,
203,
565,
445,
6843,
12521,
12,
203,
3639,
1758,
628,
1345,
16,
203,
3639,
1758,
358,
1345,
16,
203,
3639,
2254,
5034,
628,
1345,
6275,
16,
203,
3639,
2254,
5034,
1131,
990,
6275,
16,
203,
3639,
1758,
8526,
3778,
6843,
26620,
16,
203,
3639,
1758,
8526,
3778,
6843,
10409,
16,
203,
3639,
1758,
8526,
3778,
3310,
774,
16,
203,
3639,
2254,
5034,
18558,
16,
203,
3639,
1426,
16,
203,
3639,
2254,
5034,
8363,
1670,
203,
565,
262,
3903,
8843,
429,
525,
27110,
10556,
12,
22097,
1670,
13,
1135,
261,
11890,
5034,
327,
6275,
13,
288,
203,
3639,
2583,
12,
14860,
10409,
18,
2469,
405,
374,
16,
315,
40,
1212,
916,
2571,
3886,
30,
15662,
7937,
55,
67,
13625,
8863,
203,
3639,
2583,
12,
14860,
10409,
18,
2469,
422,
6843,
26620,
18,
2469,
16,
315,
40,
1212,
916,
2571,
3886,
30,
15662,
7937,
67,
1880,
37,
1856,
654,
67,
4400,
67,
11793,
8863,
203,
3639,
2583,
12,
14860,
10409,
18,
2469,
422,
3310,
774,
18,
2469,
300,
404,
16,
315,
40,
1212,
916,
2571,
3886,
30,
15662,
7937,
67,
3033,
27543,
51,
67,
4400,
67,
11793,
8863,
203,
3639,
2583,
12,
1154,
990,
6275,
405,
374,
16,
315,
40,
1212,
916,
2571,
3886,
30,
14780,
67,
2192,
51,
5321,
67,
24968,
8863,
203,
203,
3639,
1758,
389,
2080,
1345,
273,
628,
1345,
31,
203,
3639,
1758,
389,
869,
1345,
273,
358,
1345,
31,
203,
3639,
2254,
5034,
389,
2080,
1345,
6275,
273,
628,
1345,
6275,
31,
203,
540,
203,
3639,
2254,
5034,
358,
1345,
7571,
13937,
273,
467,
654,
39,
3462,
24899,
869,
1345,
2934,
318,
14651,
13937,
951,
12,
3576,
18,
15330,
1769,
203,
540,
203,
3639,
389,
323,
1724,
12,
3576,
18,
15330,
16,
3310,
774,
63,
20,
6487,
389,
2080,
1345,
16,
389,
2080,
1345,
6275,
16,
389,
2080,
1345,
422,
389,
1584,
44,
67,
15140,
67,
1769,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
6843,
10409,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
9855,
87,
473,
404,
422,
374,
13,
288,
203,
7734,
1599,
2311,
4216,
12,
14860,
26620,
63,
77,
65,
2934,
87,
1165,
2171,
12,
9406,
774,
63,
77,
397,
404,
6487,
14860,
10409,
63,
77,
6487,
1408,
1769,
203,
7734,
1599,
2311,
4216,
12,
14860,
26620,
63,
77,
65,
2934,
87,
1165,
10257,
12,
9406,
774,
63,
77,
397,
404,
6487,
14860,
10409,
63,
77,
6487,
1408,
1769,
203,
5411,
289,
203,
5411,
18558,
273,
18558,
1671,
404,
31,
203,
3639,
289,
203,
203,
3639,
309,
24899,
869,
1345,
422,
389,
1584,
44,
67,
15140,
67,
13,
288,
203,
5411,
327,
6275,
273,
467,
59,
1584,
44,
24899,
59,
1584,
44,
67,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
5411,
467,
59,
1584,
44,
24899,
59,
1584,
44,
67,
2934,
1918,
9446,
12,
2463,
6275,
1769,
203,
5411,
1234,
18,
15330,
18,
13866,
12,
2463,
6275,
1769,
203,
5411,
327,
6275,
273,
467,
654,
39,
3462,
24899,
869,
1345,
2934,
2316,
13937,
951,
12,
3576,
18,
15330,
2934,
1717,
12,
869,
1345,
7571,
13937,
1769,
203,
3639,
289,
203,
203,
3639,
2583,
12,
2463,
6275,
1545,
1131,
990,
6275,
16,
315,
40,
1212,
916,
2571,
3886,
30,
2000,
3844,
353,
486,
7304,
8863,
203,
203,
3639,
3626,
4347,
5623,
12,
203,
5411,
389,
2080,
1345,
16,
203,
5411,
389,
869,
1345,
16,
203,
5411,
1234,
18,
15330,
16,
203,
5411,
389,
2080,
1345,
6275,
16,
203,
5411,
327,
6275,
203,
2
] |
// Dependency file: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
// pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'SafeMath: addition overflow');
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, 'SafeMath: subtraction overflow');
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, 'SafeMath: multiplication overflow');
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SafeMath: division by zero');
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SafeMath: modulo by zero');
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// Dependency file: @openzeppelin/contracts/cryptography/MerkleProof.sol
// pragma solidity >=0.6.0 <0.8.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// Dependency file: contracts/libraries/Upgradable.sol
// pragma solidity >=0.6.5 <0.8.0;
contract UpgradableProduct {
address public impl;
event ImplChanged(address indexed _oldImpl, address indexed _newImpl);
constructor() public {
impl = msg.sender;
}
modifier requireImpl() {
require(msg.sender == impl, 'FORBIDDEN');
_;
}
function upgradeImpl(address _newImpl) public requireImpl {
require(_newImpl != address(0), 'INVALID_ADDRESS');
require(_newImpl != impl, 'NO_CHANGE');
address lastImpl = impl;
impl = _newImpl;
emit ImplChanged(lastImpl, _newImpl);
}
}
contract UpgradableGovernance {
address public governor;
event GovernorChanged(address indexed _oldGovernor, address indexed _newGovernor);
constructor() public {
governor = msg.sender;
}
modifier requireGovernor() {
require(msg.sender == governor, 'FORBIDDEN');
_;
}
function upgradeGovernance(address _newGovernor) public requireGovernor {
require(_newGovernor != address(0), 'INVALID_ADDRESS');
require(_newGovernor != governor, 'NO_CHANGE');
address lastGovernor = governor;
governor = _newGovernor;
emit GovernorChanged(lastGovernor, _newGovernor);
}
}
// Dependency file: contracts/libraries/TransferHelper.sol
// pragma solidity >=0.6.5 <0.8.0;
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{ value: value }(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// Dependency file: contracts/libraries/WhiteList.sol
// pragma solidity >=0.6.5 <0.8.0;
pragma experimental ABIEncoderV2;
// import "contracts/libraries/Upgradable.sol";
contract WhiteList is UpgradableProduct {
event SetWhitelist(address indexed user, bool state);
mapping(address => bool) public whiteList;
/// This function reverts if the caller is not governance
///
/// @param _toWhitelist the account to mint tokens to.
/// @param _state the whitelist state.
function setWhitelist(address _toWhitelist, bool _state) external requireImpl {
whiteList[_toWhitelist] = _state;
emit SetWhitelist(_toWhitelist, _state);
}
/// @dev A modifier which checks if whitelisted for minting.
modifier onlyWhitelisted() {
require(whiteList[msg.sender], '!whitelisted');
_;
}
}
// Dependency file: contracts/libraries/ConfigNames.sol
// pragma solidity >=0.6.5 <0.8.0;
library ConfigNames {
bytes32 public constant FRYER_LTV = bytes32('FRYER_LTV');
bytes32 public constant FRYER_HARVEST_FEE = bytes32('FRYER_HARVEST_FEE');
bytes32 public constant FRYER_VAULT_PERCENTAGE = bytes32('FRYER_VAULT_PERCENTAGE');
bytes32 public constant FRYER_FLASH_FEE_PROPORTION = bytes32('FRYER_FLASH_FEE_PROPORTION');
bytes32 public constant PRIVATE = bytes32('PRIVATE');
bytes32 public constant STAKE = bytes32('STAKE');
}
// Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol
// pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Dependency file: @openzeppelin/contracts/utils/Context.sol
// pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// Dependency file: @openzeppelin/contracts/token/ERC20/ERC20.sol
// pragma solidity >=0.6.0 <0.8.0;
// import "@openzeppelin/contracts/utils/Context.sol";
// import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(amount, 'ERC20: transfer amount exceeds allowance')
);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, 'ERC20: decreased allowance below zero')
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), 'ERC20: transfer from the zero address');
require(recipient != address(0), 'ERC20: transfer to the zero address');
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, 'ERC20: transfer amount exceeds balance');
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), 'ERC20: mint to the zero address');
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), 'ERC20: burn from the zero address');
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, 'ERC20: burn amount exceeds balance');
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), 'ERC20: approve from the zero address');
require(spender != address(0), 'ERC20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// Dependency file: contracts/CheeseToken.sol
// pragma solidity >=0.6.5 <0.8.0;
// import '/Users/sg99022ml/Desktop/chfry-protocol-internal/node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol';
// import '/Users/sg99022ml/Desktop/chfry-protocol-internal/node_modules/@openzeppelin/contracts/token/ERC20/ERC20.sol';
// import '/Users/sg99022ml/Desktop/chfry-protocol-internal/node_modules/@openzeppelin/contracts/math/SafeMath.sol';
// import 'contracts/libraries/Upgradable.sol';
contract CheeseToken is ERC20, UpgradableProduct {
using SafeMath for uint256;
mapping(address => bool) public whiteList;
constructor(string memory _symbol, string memory _name) public ERC20(_name, _symbol) {
_mint(msg.sender, uint256(2328300).mul(1e18));
}
modifier onlyWhitelisted() {
require(whiteList[msg.sender], '!whitelisted');
_;
}
function setWhitelist(address _toWhitelist, bool _state) external requireImpl {
whiteList[_toWhitelist] = _state;
}
function mint(address account, uint256 amount) external virtual onlyWhitelisted {
require(totalSupply().add(amount) <= cap(), 'ERC20Capped: cap exceeded');
_mint(account, amount);
}
function cap() public pure virtual returns (uint256) {
return 9313200 * 1e18;
}
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(
amount,
'ERC20: burn amount exceeds allowance'
);
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
function burn(uint256 amount) external virtual {
_burn(_msgSender(), amount);
}
}
// Dependency file: @openzeppelin/contracts/utils/ReentrancyGuard.sol
// pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, 'ReentrancyGuard: reentrant call');
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// Dependency file: contracts/CheeseFactory.sol
// pragma solidity >=0.6.5 <0.8.0;
// import '/Users/sg99022ml/Desktop/chfry-protocol-internal/node_modules/@openzeppelin/contracts/math/SafeMath.sol';
// import 'contracts/libraries/Upgradable.sol';
// import 'contracts/CheeseToken.sol';
// import 'contracts/libraries/ConfigNames.sol';
// import '/Users/sg99022ml/Desktop/chfry-protocol-internal/node_modules/@openzeppelin/contracts/utils/ReentrancyGuard.sol';
//a1 = 75000, n = week, d= -390, week = [0,156]
//an=a1+(n-1)*d
//Sn=n*a1+(n(n-1)*d)/2
contract CheeseFactory is UpgradableProduct, ReentrancyGuard {
using SafeMath for uint256;
uint256 public constant MAX_WEEK = 156;
uint256 public constant d = 390 * 10**18;
uint256 public constant a1 = 75000 * 10**18;
uint256 public constant TOTAL_WEIGHT = 10000;
uint256 public startTimestamp;
uint256 public lastTimestamp;
uint256 public weekTimestamp;
uint256 public totalMintAmount;
CheeseToken public token;
bool public initialized;
struct Pool {
address pool;
uint256 weight;
uint256 minted;
}
mapping(bytes32 => Pool) public poolInfo;
constructor(address token_, uint256 weekTimestamp_) public {
weekTimestamp = weekTimestamp_;
token = CheeseToken(token_);
}
function setCheeseToken(address token_) external requireImpl {
token = CheeseToken(token_);
}
function setPool(bytes32 poolName_, address poolAddress_) external requireImpl {
require(poolName_ == ConfigNames.PRIVATE || poolName_ == ConfigNames.STAKE, 'name error');
Pool storage pool = poolInfo[poolName_];
pool.pool = poolAddress_;
}
modifier expectInitialized() {
require(initialized, 'not initialized.');
_;
}
function initialize(
address private_,
address stake_,
uint256 startTimestamp_
) external requireImpl {
require(!initialized, 'already initialized');
require(startTimestamp_ >= block.timestamp, '!startTime');
// weight
poolInfo[ConfigNames.PRIVATE] = Pool(private_, 1000, 0);
poolInfo[ConfigNames.STAKE] = Pool(stake_, 9000, 0);
initialized = true;
startTimestamp = startTimestamp_;
lastTimestamp = startTimestamp_;
}
function preMint() public view returns (uint256) {
if (block.timestamp <= startTimestamp) {
return uint256(0);
}
if (block.timestamp <= lastTimestamp) {
return uint256(0);
}
uint256 time = block.timestamp.sub(startTimestamp);
uint256 max_week_time = MAX_WEEK.mul(weekTimestamp);
// time lt 156week
if (time > max_week_time) {
time = max_week_time;
}
// gt 1week
if (time >= weekTimestamp) {
uint256 n = time.div(weekTimestamp);
//an =a1-(n)*d d<0
//=> a1+(n)*(-d)
uint256 an = a1.sub(n.mul(d));
// gt 1week time stamp
uint256 otherTimestamp = time.mod(weekTimestamp);
uint256 other = an.mul(otherTimestamp).div(weekTimestamp);
//Sn=n*a1+(n(n-1)*d)/2 d<0
// => n*a1-(n(n-1)*(-d))/2
// fist = n*a1
uint256 first = n.mul(a1);
// last = (n(n-1)*(-d))/2
uint256 last = n.mul(n.sub(1)).mul(d).div(2);
uint256 sn = first.sub(last);
return other.add(sn).sub(totalMintAmount);
} else {
return a1.mul(time).div(weekTimestamp).sub(totalMintAmount);
}
}
function _updateTotalAmount() internal returns (uint256) {
uint256 preMintAmount = preMint();
totalMintAmount = totalMintAmount.add(preMintAmount);
lastTimestamp = block.timestamp;
return preMintAmount;
}
function prePoolMint(bytes32 poolName_) public view returns (uint256) {
uint256 preMintAmount = preMint();
Pool memory pool = poolInfo[poolName_];
uint256 poolTotal = totalMintAmount.add(preMintAmount).mul(pool.weight).div(TOTAL_WEIGHT);
return poolTotal.sub(pool.minted);
}
function poolMint(bytes32 poolName_) external nonReentrant expectInitialized returns (uint256) {
Pool storage pool = poolInfo[poolName_];
require(msg.sender == pool.pool, 'Permission denied');
_updateTotalAmount();
uint256 poolTotal = totalMintAmount.mul(pool.weight).div(TOTAL_WEIGHT);
uint256 amount = poolTotal.sub(pool.minted);
if (amount > 0) {
token.mint(msg.sender, amount);
pool.minted = pool.minted.add(amount);
}
return amount;
}
}
// Root file: contracts/CheeseStakePool.sol
pragma solidity >=0.6.5 <0.8.0;
contract CheeseStakePool is UpgradableProduct, ReentrancyGuard {
event AddPoolToken(address indexed pool, uint256 indexed weight);
event UpdatePoolToken(address indexed pool, uint256 indexed weight);
event Stake(address indexed pool, address indexed user, uint256 indexed amount);
event Withdraw(address indexed pool, address indexed user, uint256 indexed amount);
event Claimed(address indexed pool, address indexed user, uint256 indexed amount);
event SetCheeseFactory(address indexed factory);
event SetCheeseToken(address indexed token);
event SettleFlashLoan(bytes32 indexed merkleRoot, uint256 indexed index, uint256 amount, uint256 settleBlockNumber);
using TransferHelper for address;
using SafeMath for uint256;
struct UserInfo {
uint256 amount;
uint256 debt;
uint256 reward;
uint256 totalIncome;
}
struct PoolInfo {
uint256 pid;
address token;
uint256 weight;
uint256 rewardPerShare;
uint256 reward;
uint256 lastBlockTimeStamp;
uint256 debt;
uint256 totalAmount;
}
struct MerkleDistributor {
bytes32 merkleRoot;
uint256 index;
uint256 amount;
uint256 settleBlocNumber;
}
CheeseToken public token;
CheeseFactory public cheeseFactory;
PoolInfo[] public poolInfos;
PoolInfo public flashloanPool;
uint256 public lastBlockTimeStamp;
uint256 public rewardPerShare;
uint256 public totalWeight;
MerkleDistributor[] public merkleDistributors;
mapping(address => uint256) public tokenOfPid;
mapping(address => bool) public tokenUsed;
mapping(uint256 => mapping(address => UserInfo)) public userInfos;
mapping(uint256 => mapping(address => bool)) claimedFlashLoanState;
constructor(address cheeseFactory_, address token_) public {
cheeseFactory = CheeseFactory(cheeseFactory_);
token = CheeseToken(token_);
_initFlashLoanPool(0);
}
function _initFlashLoanPool(uint256 flashloanPoolWeight) internal {
flashloanPool = PoolInfo(0, address(this), flashloanPoolWeight, 0, 0, block.timestamp, 0, 0);
totalWeight = totalWeight.add(flashloanPool.weight);
emit AddPoolToken(address(this), flashloanPool.weight);
}
function setCheeseFactory(address cheeseFactory_) external requireImpl {
cheeseFactory = CheeseFactory(cheeseFactory_);
emit SetCheeseFactory(cheeseFactory_);
}
function setCheeseToken(address token_) external requireImpl {
token = CheeseToken(token_);
emit SetCheeseToken(token_);
}
modifier verifyPid(uint256 pid) {
require(poolInfos.length > pid && poolInfos[pid].token != address(0), 'pool does not exist');
_;
}
modifier updateAllPoolRewardPerShare() {
if (totalWeight > 0 && block.timestamp > lastBlockTimeStamp) {
(uint256 _reward, uint256 _perShare) = currentAllPoolRewardShare();
rewardPerShare = _perShare;
lastBlockTimeStamp = block.timestamp;
require(_reward == cheeseFactory.poolMint(ConfigNames.STAKE), 'pool mint error');
}
_;
}
modifier updateSinglePoolReward(PoolInfo storage poolInfo) {
if (poolInfo.weight > 0) {
uint256 debt = poolInfo.weight.mul(rewardPerShare).div(1e18);
uint256 poolReward = debt.sub(poolInfo.debt);
poolInfo.reward = poolInfo.reward.add(poolReward);
poolInfo.debt = debt;
}
_;
}
modifier updateSinglePoolRewardPerShare(PoolInfo storage poolInfo) {
if (poolInfo.totalAmount > 0 && block.timestamp > poolInfo.lastBlockTimeStamp) {
(uint256 _reward, uint256 _perShare) = currentSinglePoolRewardShare(poolInfo.pid);
poolInfo.rewardPerShare = _perShare;
poolInfo.reward = poolInfo.reward.sub(_reward);
poolInfo.lastBlockTimeStamp = block.timestamp;
}
_;
}
modifier updateUserReward(PoolInfo storage poolInfo, address user) {
UserInfo storage userInfo = userInfos[poolInfo.pid][user];
if (userInfo.amount > 0) {
uint256 debt = userInfo.amount.mul(poolInfo.rewardPerShare).div(1e18);
uint256 userReward = debt.sub(userInfo.debt);
userInfo.reward = userInfo.reward.add(userReward);
userInfo.debt = debt;
}
_;
}
function getPoolInfo(uint256 pid)
external
view
virtual
verifyPid(pid)
returns (
uint256 _pid,
address _token,
uint256 _weight,
uint256 _rewardPerShare,
uint256 _reward,
uint256 _lastBlockTimeStamp,
uint256 _debt,
uint256 _totalAmount
)
{
PoolInfo memory pool = poolInfos[pid];
return (
pool.pid,
pool.token,
pool.weight,
pool.rewardPerShare,
pool.reward,
pool.lastBlockTimeStamp,
pool.debt,
pool.totalAmount
);
}
function getPoolInfos()
external
view
virtual
returns (
uint256 length,
uint256[] memory _pid,
address[] memory _token,
uint256[] memory _weight,
uint256[] memory _lastBlockTimeStamp,
uint256[] memory _totalAmount
)
{
length = poolInfos.length;
_pid = new uint256[](length);
_token = new address[](length);
_weight = new uint256[](length);
_lastBlockTimeStamp = new uint256[](length);
_totalAmount = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
PoolInfo memory pool = poolInfos[i];
_pid[i] = pool.pid;
_token[i] = pool.token;
_weight[i] = pool.weight;
_lastBlockTimeStamp[i] = pool.lastBlockTimeStamp;
_totalAmount[i] = pool.totalAmount;
}
return (length, _pid, _token, _weight, _lastBlockTimeStamp, _totalAmount);
}
function getUserInfo(uint256 pid, address userAddress)
external
view
virtual
returns (
uint256 _amount,
uint256 _debt,
uint256 _reward,
uint256 _totalIncome
)
{
UserInfo memory userInfo = userInfos[pid][userAddress];
return (userInfo.amount, userInfo.debt, userInfo.reward, userInfo.totalIncome);
}
function currentAllPoolRewardShare() public view virtual returns (uint256 _reward, uint256 _perShare) {
_reward = cheeseFactory.prePoolMint(ConfigNames.STAKE);
_perShare = rewardPerShare;
if (totalWeight > 0) {
_perShare = _perShare.add(_reward.mul(1e18).div(totalWeight));
}
return (_reward, _perShare);
}
function currentSinglePoolRewardShare(uint256 pid)
public
view
virtual
verifyPid(pid)
returns (uint256 _reward, uint256 _perShare)
{
PoolInfo memory poolInfo = poolInfos[pid];
_reward = poolInfo.reward;
_perShare = poolInfo.rewardPerShare;
if (poolInfo.totalAmount > 0) {
uint256 pendingShare = _reward.mul(1e18).div(poolInfo.totalAmount);
_perShare = _perShare.add(pendingShare);
}
return (_reward, _perShare);
}
function stake(uint256 pid, uint256 amount)
external
virtual
nonReentrant
verifyPid(pid)
updateAllPoolRewardPerShare
updateSinglePoolReward(poolInfos[pid])
updateSinglePoolRewardPerShare(poolInfos[pid])
updateUserReward(poolInfos[pid], msg.sender)
{
PoolInfo storage poolInfo = poolInfos[pid];
if (amount > 0) {
UserInfo storage userInfo = userInfos[pid][msg.sender];
userInfo.amount = userInfo.amount.add(amount);
userInfo.debt = userInfo.amount.mul(poolInfo.rewardPerShare).div(1e18);
poolInfo.totalAmount = poolInfo.totalAmount.add(amount);
address(poolInfo.token).safeTransferFrom(msg.sender, address(this), amount);
emit Stake(poolInfo.token, msg.sender, amount);
}
}
function withdraw(uint256 pid, uint256 amount)
external
virtual
nonReentrant
verifyPid(pid)
updateAllPoolRewardPerShare
updateSinglePoolReward(poolInfos[pid])
updateSinglePoolRewardPerShare(poolInfos[pid])
updateUserReward(poolInfos[pid], msg.sender)
{
PoolInfo storage poolInfo = poolInfos[pid];
if (amount > 0) {
UserInfo storage userInfo = userInfos[pid][msg.sender];
require(userInfo.amount >= amount, 'Insufficient balance');
userInfo.amount = userInfo.amount.sub(amount);
userInfo.debt = userInfo.amount.mul(poolInfo.rewardPerShare).div(1e18);
poolInfo.totalAmount = poolInfo.totalAmount.sub(amount);
address(poolInfo.token).safeTransfer(msg.sender, amount);
emit Withdraw(poolInfo.token, msg.sender, amount);
}
}
function claim(uint256 pid)
external
virtual
nonReentrant
verifyPid(pid)
updateAllPoolRewardPerShare
updateSinglePoolReward(poolInfos[pid])
updateSinglePoolRewardPerShare(poolInfos[pid])
updateUserReward(poolInfos[pid], msg.sender)
{
PoolInfo storage poolInfo = poolInfos[pid];
UserInfo storage userInfo = userInfos[pid][msg.sender];
if (userInfo.reward > 0) {
uint256 amount = userInfo.reward;
userInfo.reward = 0;
userInfo.totalIncome = userInfo.totalIncome.add(amount);
address(token).safeTransfer(msg.sender, amount);
emit Claimed(poolInfo.token, msg.sender, amount);
}
}
function calculateIncome(uint256 pid, address userAddress) external view virtual verifyPid(pid) returns (uint256) {
PoolInfo storage poolInfo = poolInfos[pid];
UserInfo storage userInfo = userInfos[pid][userAddress];
(uint256 _reward, uint256 _perShare) = currentAllPoolRewardShare();
uint256 poolPendingReward = poolInfo.weight.mul(_perShare).div(1e18).sub(poolInfo.debt);
_reward = poolInfo.reward.add(poolPendingReward);
_perShare = poolInfo.rewardPerShare;
if (block.timestamp > poolInfo.lastBlockTimeStamp && poolInfo.totalAmount > 0) {
uint256 poolPendingShare = _reward.mul(1e18).div(poolInfo.totalAmount);
_perShare = _perShare.add(poolPendingShare);
}
uint256 userReward = userInfo.amount.mul(_perShare).div(1e18).sub(userInfo.debt);
return userInfo.reward.add(userReward);
}
function isClaimedFlashLoan(uint256 index, address user) public view returns (bool) {
return claimedFlashLoanState[index][user];
}
function settleFlashLoan(
uint256 index,
uint256 amount,
uint256 settleBlockNumber,
bytes32 merkleRoot
) external requireImpl updateAllPoolRewardPerShare updateSinglePoolReward(flashloanPool) {
require(index == merkleDistributors.length, 'index already exists');
require(flashloanPool.reward >= amount, 'Insufficient reward funds');
require(block.number >= settleBlockNumber, '!blockNumber');
if (merkleDistributors.length > 0) {
MerkleDistributor memory md = merkleDistributors[merkleDistributors.length - 1];
require(md.settleBlocNumber < settleBlockNumber, '!settleBlocNumber');
}
flashloanPool.reward = flashloanPool.reward.sub(amount);
merkleDistributors.push(MerkleDistributor(merkleRoot, index, amount, settleBlockNumber));
emit SettleFlashLoan(merkleRoot, index, amount, settleBlockNumber);
}
function claimFlashLoan(
uint256 index,
uint256 amount,
bytes32[] calldata proof
) external {
address user = msg.sender;
require(merkleDistributors.length > index, 'Invalid index');
require(!isClaimedFlashLoan(index, user), 'Drop already claimed.');
MerkleDistributor storage merkleDistributor = merkleDistributors[index];
require(merkleDistributor.amount >= amount, 'Not sufficient');
bytes32 leaf = keccak256(abi.encodePacked(index, user, amount));
require(MerkleProof.verify(proof, merkleDistributor.merkleRoot, leaf), 'Invalid proof.');
merkleDistributor.amount = merkleDistributor.amount.sub(amount);
claimedFlashLoanState[index][user] = true;
address(token).safeTransfer(msg.sender, amount);
emit Claimed(address(this), user, amount);
}
function addPool(address tokenAddr, uint256 weight) external virtual requireImpl updateAllPoolRewardPerShare {
require(weight >= 0 && tokenAddr != address(0) && tokenUsed[tokenAddr] == false, 'Check the parameters');
uint256 pid = poolInfos.length;
uint256 debt = weight.mul(rewardPerShare).div(1e18);
poolInfos.push(PoolInfo(pid, tokenAddr, weight, 0, 0, block.timestamp, debt, 0));
tokenOfPid[tokenAddr] = pid;
tokenUsed[tokenAddr] = true;
totalWeight = totalWeight.add(weight);
emit AddPoolToken(tokenAddr, weight);
}
function _updatePool(PoolInfo storage poolInfo, uint256 weight) internal {
totalWeight = totalWeight.sub(poolInfo.weight);
poolInfo.weight = weight;
poolInfo.debt = poolInfo.weight.mul(rewardPerShare).div(1e18);
totalWeight = totalWeight.add(weight);
}
function updatePool(address tokenAddr, uint256 weight)
external
virtual
requireImpl
verifyPid(tokenOfPid[tokenAddr])
updateAllPoolRewardPerShare
updateSinglePoolReward(poolInfos[tokenOfPid[tokenAddr]])
updateSinglePoolRewardPerShare(poolInfos[tokenOfPid[tokenAddr]])
{
require(weight >= 0 && tokenAddr != address(0), 'Parameter error');
PoolInfo storage poolInfo = poolInfos[tokenOfPid[tokenAddr]];
require(poolInfo.token == tokenAddr, 'pool does not exist');
_updatePool(poolInfo, weight);
emit UpdatePoolToken(address(poolInfo.token), weight);
}
function updateFlashloanPool(uint256 weight)
external
virtual
requireImpl
updateAllPoolRewardPerShare
updateSinglePoolReward(flashloanPool)
{
require(weight >= 0, 'Parameter error');
_updatePool(flashloanPool, weight);
emit UpdatePoolToken(address(flashloanPool.token), weight);
}
} | * @dev Returns the integer division of two unsigned integers, reverting on division by zero. The result is rounded towards zero. Counterpart to Solidity's `/` operator. Note: this function uses a `revert` opcode (which leaves remaining gas untouched) while Solidity uses an invalid opcode to revert (consuming all remaining gas). Requirements: - The divisor cannot be zero./ | function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SafeMath: division by zero');
return a / b;
}
| 6,285,051 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
5206,
2860,
326,
3571,
16536,
434,
2795,
9088,
12321,
16,
15226,
310,
603,
16536,
635,
3634,
18,
1021,
563,
353,
16729,
23248,
3634,
18,
9354,
2680,
358,
348,
7953,
560,
1807,
1375,
19,
68,
3726,
18,
3609,
30,
333,
445,
4692,
279,
1375,
266,
1097,
68,
11396,
261,
12784,
15559,
4463,
16189,
640,
869,
19370,
13,
1323,
348,
7953,
560,
4692,
392,
2057,
11396,
358,
15226,
261,
17664,
310,
777,
4463,
16189,
2934,
29076,
30,
300,
1021,
15013,
2780,
506,
3634,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
3739,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
202,
202,
6528,
12,
70,
405,
374,
16,
296,
9890,
10477,
30,
16536,
635,
3634,
8284,
203,
202,
202,
2463,
279,
342,
324,
31,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
/**
* @title Tellor Transfer
* @dev Contais the methods related to transfers and ERC20. Tellor.sol and TellorGetters.sol
* reference this library for function's logic.
*/
library TellorTransfer {
using SafeMath for uint256;
event Approval(address indexed _owner, address indexed _spender, uint256 _value); //ERC20 Approval event
event Transfer(address indexed _from, address indexed _to, uint256 _value); //ERC20 Transfer Event
/*Functions*/
/**
* @dev Allows for a transfer of tokens to _to
* @param _to The address to send tokens to
* @param _amount The amount of tokens to send
* @return true if transfer is successful
*/
function transfer(TellorStorage.TellorStorageStruct storage self, address _to, uint256 _amount) public returns (bool success) {
doTransfer(self, msg.sender, _to, _amount);
return true;
}
/**
* @notice Send _amount tokens to _to from _from on the condition it
* is approved by _from
* @param _from The address holding the tokens being transferred
* @param _to The address of the recipient
* @param _amount The amount of tokens to be transferred
* @return True if the transfer was successful
*/
function transferFrom(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount)
public
returns (bool success)
{
require(self.allowed[_from][msg.sender] >= _amount, "Allowance is wrong");
self.allowed[_from][msg.sender] -= _amount;
doTransfer(self, _from, _to, _amount);
return true;
}
/**
* @dev This function approves a _spender an _amount of tokens to use
* @param _spender address
* @param _amount amount the spender is being approved for
* @return true if spender appproved successfully
*/
function approve(TellorStorage.TellorStorageStruct storage self, address _spender, uint256 _amount) public returns (bool) {
require(_spender != address(0), "Spender is 0-address");
self.allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/**
* @param _user address of party with the balance
* @param _spender address of spender of parties said balance
* @return Returns the remaining allowance of tokens granted to the _spender from the _user
*/
function allowance(TellorStorage.TellorStorageStruct storage self, address _user, address _spender) public view returns (uint256) {
return self.allowed[_user][_spender];
}
/**
* @dev Completes POWO transfers by updating the balances on the current block number
* @param _from address to transfer from
* @param _to addres to transfer to
* @param _amount to transfer
*/
function doTransfer(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public {
require(_amount > 0, "Tried to send non-positive amount");
require(_to != address(0), "Receiver is 0 address");
//allowedToTrade checks the stakeAmount is removed from balance if the _user is staked
require(allowedToTrade(self, _from, _amount), "Stake amount was not removed from balance");
uint256 previousBalance = balanceOfAt(self, _from, block.number);
updateBalanceAtNow(self.balances[_from], previousBalance - _amount);
previousBalance = balanceOfAt(self, _to, block.number);
require(previousBalance + _amount >= previousBalance, "Overflow happened"); // Check for overflow
updateBalanceAtNow(self.balances[_to], previousBalance + _amount);
emit Transfer(_from, _to, _amount);
}
/**
* @dev Gets balance of owner specified
* @param _user is the owner address used to look up the balance
* @return Returns the balance associated with the passed in _user
*/
function balanceOf(TellorStorage.TellorStorageStruct storage self, address _user) public view returns (uint256) {
return balanceOfAt(self, _user, block.number);
}
/**
* @dev Queries the balance of _user at a specific _blockNumber
* @param _user The address from which the balance will be retrieved
* @param _blockNumber The block number when the balance is queried
* @return The balance at _blockNumber specified
*/
function balanceOfAt(TellorStorage.TellorStorageStruct storage self, address _user, uint256 _blockNumber) public view returns (uint256) {
if ((self.balances[_user].length == 0) || (self.balances[_user][0].fromBlock > _blockNumber)) {
return 0;
} else {
return getBalanceAt(self.balances[_user], _blockNumber);
}
}
/**
* @dev Getter for balance for owner on the specified _block number
* @param checkpoints gets the mapping for the balances[owner]
* @param _block is the block number to search the balance on
* @return the balance at the checkpoint
*/
function getBalanceAt(TellorStorage.Checkpoint[] storage checkpoints, uint256 _block) public view returns (uint256) {
if (checkpoints.length == 0) return 0;
if (_block >= checkpoints[checkpoints.length - 1].fromBlock) return checkpoints[checkpoints.length - 1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint256 min = 0;
uint256 max = checkpoints.length - 1;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock <= _block) {
min = mid;
} else {
max = mid - 1;
}
}
return checkpoints[min].value;
}
/**
* @dev This function returns whether or not a given user is allowed to trade a given amount
* and removing the staked amount from their balance if they are staked
* @param _user address of user
* @param _amount to check if the user can spend
* @return true if they are allowed to spend the amount being checked
*/
function allowedToTrade(TellorStorage.TellorStorageStruct storage self, address _user, uint256 _amount) public view returns (bool) {
if (self.stakerDetails[_user].currentStatus > 0) {
//Removes the stakeAmount from balance if the _user is staked
if (balanceOf(self, _user).sub(self.uintVars[keccak256("stakeAmount")]).sub(_amount) >= 0) {
return true;
}
} else if (balanceOf(self, _user).sub(_amount) >= 0) {
return true;
}
return false;
}
/**
* @dev Updates balance for from and to on the current block number via doTransfer
* @param checkpoints gets the mapping for the balances[owner]
* @param _value is the new balance
*/
function updateBalanceAtNow(TellorStorage.Checkpoint[] storage checkpoints, uint256 _value) public {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
TellorStorage.Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
TellorStorage.Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1];
oldCheckPoint.value = uint128(_value);
}
}
}
//import "./SafeMath.sol";
/**
* @title Tellor Dispute
* @dev Contains the methods related to disputes. Tellor.sol references this library for function's logic.
*/
library TellorDispute {
using SafeMath for uint256;
using SafeMath for int256;
//emitted when a new dispute is initialized
event NewDispute(uint256 indexed _disputeId, uint256 indexed _requestId, uint256 _timestamp, address _miner);
//emitted when a new vote happens
event Voted(uint256 indexed _disputeID, bool _position, address indexed _voter);
//emitted upon dispute tally
event DisputeVoteTallied(uint256 indexed _disputeID, int256 _result, address indexed _reportedMiner, address _reportingParty, bool _active);
event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true
/*Functions*/
/**
* @dev Helps initialize a dispute by assigning it a disputeId
* when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the
* invalidated value information to POS voting
* @param _requestId being disputed
* @param _timestamp being disputed
* @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value
* requires 5 miners to submit a value.
*/
function beginDispute(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp, uint256 _minerIndex) public {
TellorStorage.Request storage _request = self.requestDetails[_requestId];
//require that no more than a day( (24 hours * 60 minutes)/10minutes=144 blocks) has gone by since the value was "mined"
require(now - _timestamp <= 1 days, "The value was mined more than a day ago");
require(_request.minedBlockNum[_timestamp] > 0, "Mined block is 0");
require(_minerIndex < 5, "Miner index is wrong");
//_miner is the miner being disputed. For every mined value 5 miners are saved in an array and the _minerIndex
//provided by the party initiating the dispute
address _miner = _request.minersByValue[_timestamp][_minerIndex];
bytes32 _hash = keccak256(abi.encodePacked(_miner, _requestId, _timestamp));
//Ensures that a dispute is not already open for the that miner, requestId and timestamp
require(self.disputeIdByDisputeHash[_hash] == 0, "Dispute is already open");
TellorTransfer.doTransfer(self, msg.sender, address(this), self.uintVars[keccak256("disputeFee")]);
//Increase the dispute count by 1
self.uintVars[keccak256("disputeCount")] = self.uintVars[keccak256("disputeCount")] + 1;
//Sets the new disputeCount as the disputeId
uint256 disputeId = self.uintVars[keccak256("disputeCount")];
//maps the dispute hash to the disputeId
self.disputeIdByDisputeHash[_hash] = disputeId;
//maps the dispute to the Dispute struct
self.disputesById[disputeId] = TellorStorage.Dispute({
hash: _hash,
isPropFork: false,
reportedMiner: _miner,
reportingParty: msg.sender,
proposedForkAddress: address(0),
executed: false,
disputeVotePassed: false,
tally: 0
});
//Saves all the dispute variables for the disputeId
self.disputesById[disputeId].disputeUintVars[keccak256("requestId")] = _requestId;
self.disputesById[disputeId].disputeUintVars[keccak256("timestamp")] = _timestamp;
self.disputesById[disputeId].disputeUintVars[keccak256("value")] = _request.valuesByTimestamp[_timestamp][_minerIndex];
self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 7 days;
self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number;
self.disputesById[disputeId].disputeUintVars[keccak256("minerSlot")] = _minerIndex;
self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = self.uintVars[keccak256("disputeFee")];
//Values are sorted as they come in and the official value is the median of the first five
//So the "official value" miner is always minerIndex==2. If the official value is being
//disputed, it sets its status to inDispute(currentStatus = 3) so that users are made aware it is under dispute
if (_minerIndex == 2) {
self.requestDetails[_requestId].inDispute[_timestamp] = true;
}
self.stakerDetails[_miner].currentStatus = 3;
emit NewDispute(disputeId, _requestId, _timestamp, _miner);
}
/**
* @dev Allows token holders to vote
* @param _disputeId is the dispute id
* @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute)
*/
function vote(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, bool _supportsDispute) public {
TellorStorage.Dispute storage disp = self.disputesById[_disputeId];
//Get the voteWeight or the balance of the user at the time/blockNumber the disupte began
uint256 voteWeight = TellorTransfer.balanceOfAt(self, msg.sender, disp.disputeUintVars[keccak256("blockNumber")]);
//Require that the msg.sender has not voted
require(disp.voted[msg.sender] != true, "Sender has already voted");
//Requre that the user had a balance >0 at time/blockNumber the disupte began
require(voteWeight > 0, "User balance is 0");
//ensures miners that are under dispute cannot vote
require(self.stakerDetails[msg.sender].currentStatus != 3, "Miner is under dispute");
//Update user voting status to true
disp.voted[msg.sender] = true;
//Update the number of votes for the dispute
disp.disputeUintVars[keccak256("numberOfVotes")] += 1;
//Update the quorum by adding the voteWeight
disp.disputeUintVars[keccak256("quorum")] += voteWeight;
//If the user supports the dispute increase the tally for the dispute by the voteWeight
//otherwise decrease it
if (_supportsDispute) {
disp.tally = disp.tally.add(int256(voteWeight));
} else {
disp.tally = disp.tally.sub(int256(voteWeight));
}
//Let the network know the user has voted on the dispute and their casted vote
emit Voted(_disputeId, _supportsDispute, msg.sender);
}
/**
* @dev tallies the votes.
* @param _disputeId is the dispute id
*/
function tallyVotes(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId) public {
TellorStorage.Dispute storage disp = self.disputesById[_disputeId];
TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]];
//Ensure this has not already been executed/tallied
require(disp.executed == false, "Dispute has been already executed");
//Ensure the time for voting has elapsed
require(now > disp.disputeUintVars[keccak256("minExecutionDate")], "Time for voting haven't elapsed");
//If the vote is not a proposed fork
if (disp.isPropFork == false) {
TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner];
//If the vote for disputing a value is succesful(disp.tally >0) then unstake the reported
// miner and transfer the stakeAmount and dispute fee to the reporting party
if (disp.tally > 0) {
//if reported miner stake has not been slashed yet, slash them and return the fee to reporting party
if (stakes.currentStatus == 3) {
//Changing the currentStatus and startDate unstakes the reported miner and allows for the
//transfer of the stakeAmount
stakes.currentStatus = 0;
stakes.startDate = now - (now % 86400);
//Decreases the stakerCount since the miner's stake is being slashed
self.uintVars[keccak256("stakerCount")]--;
updateDisputeFee(self);
//Transfers the StakeAmount from the reporded miner to the reporting party
TellorTransfer.doTransfer(self, disp.reportedMiner, disp.reportingParty, self.uintVars[keccak256("stakeAmount")]);
//Returns the dispute fee to the reportingParty
TellorTransfer.doTransfer(self, address(this), disp.reportingParty, disp.disputeUintVars[keccak256("fee")]);
//if reported miner stake was already slashed, return the fee to other reporting paties
} else{
TellorTransfer.doTransfer(self, address(this), disp.reportingParty, disp.disputeUintVars[keccak256("fee")]);
}
//Set the dispute state to passed/true
disp.disputeVotePassed = true;
//If the dispute was succeful(miner found guilty) then update the timestamp value to zero
//so that users don't use this datapoint
if (_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true) {
_request.finalValues[disp.disputeUintVars[keccak256("timestamp")]] = 0;
}
//If the vote for disputing a value is unsuccesful then update the miner status from being on
//dispute(currentStatus=3) to staked(currentStatus =1) and tranfer the dispute fee to the miner
} else {
//Update the miner's current status to staked(currentStatus = 1)
stakes.currentStatus = 1;
//tranfer the dispute fee to the miner
TellorTransfer.doTransfer(self, address(this), disp.reportedMiner, disp.disputeUintVars[keccak256("fee")]);
if (_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true) {
_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] = false;
}
}
//If the vote is for a proposed fork require a 20% quorum before executing the update to the new tellor contract address
} else {
if (disp.tally > 0) {
require(
disp.disputeUintVars[keccak256("quorum")] > ((self.uintVars[keccak256("total_supply")] * 20) / 100),
"Quorum is not reached"
);
self.addressVars[keccak256("tellorContract")] = disp.proposedForkAddress;
disp.disputeVotePassed = true;
emit NewTellorAddress(disp.proposedForkAddress);
}
}
//update the dispute status to executed
disp.executed = true;
emit DisputeVoteTallied(_disputeId, disp.tally, disp.reportedMiner, disp.reportingParty, disp.disputeVotePassed);
}
/**
* @dev Allows for a fork to be proposed
* @param _propNewTellorAddress address for new proposed Tellor
*/
function proposeFork(TellorStorage.TellorStorageStruct storage self, address _propNewTellorAddress) public {
bytes32 _hash = keccak256(abi.encodePacked(_propNewTellorAddress));
require(self.disputeIdByDisputeHash[_hash] == 0, "");
TellorTransfer.doTransfer(self, msg.sender, address(this), self.uintVars[keccak256("disputeFee")]); //This is the fork fee
self.uintVars[keccak256("disputeCount")]++;
uint256 disputeId = self.uintVars[keccak256("disputeCount")];
self.disputeIdByDisputeHash[_hash] = disputeId;
self.disputesById[disputeId] = TellorStorage.Dispute({
hash: _hash,
isPropFork: true,
reportedMiner: msg.sender,
reportingParty: msg.sender,
proposedForkAddress: _propNewTellorAddress,
executed: false,
disputeVotePassed: false,
tally: 0
});
self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number;
self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = self.uintVars[keccak256("disputeFee")];
self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 7 days;
}
/**
* @dev this function allows the dispute fee to fluctuate based on the number of miners on the system.
* The floor for the fee is 15e18.
*/
function updateDisputeFee(TellorStorage.TellorStorageStruct storage self) public {
//if the number of staked miners divided by the target count of staked miners is less than 1
if ((self.uintVars[keccak256("stakerCount")] * 1000) / self.uintVars[keccak256("targetMiners")] < 1000) {
//Set the dispute fee at stakeAmt * (1- stakerCount/targetMiners)
//or at the its minimum of 15e18
self.uintVars[keccak256("disputeFee")] = SafeMath.max(
15e18,
self.uintVars[keccak256("stakeAmount")].mul(
1000 - (self.uintVars[keccak256("stakerCount")] * 1000) / self.uintVars[keccak256("targetMiners")]
) /
1000
);
} else {
//otherwise set the dispute fee at 15e18 (the floor/minimum fee allowed)
self.uintVars[keccak256("disputeFee")] = 15e18;
}
}
}
/**
* itle Tellor Dispute
* @dev Contais the methods related to miners staking and unstaking. Tellor.sol
* references this library for function's logic.
*/
library TellorStake {
event NewStake(address indexed _sender); //Emits upon new staker
event StakeWithdrawn(address indexed _sender); //Emits when a staker is now no longer staked
event StakeWithdrawRequested(address indexed _sender); //Emits when a staker begins the 7 day withdraw period
/*Functions*/
/**
* @dev This function stakes the five initial miners, sets the supply and all the constant variables.
* This function is called by the constructor function on TellorMaster.sol
*/
function init(TellorStorage.TellorStorageStruct storage self) public {
require(self.uintVars[keccak256("decimals")] == 0, "Too many decimals");
//Give this contract 6000 Tellor Tributes so that it can stake the initial 6 miners
TellorTransfer.updateBalanceAtNow(self.balances[address(this)], 2**256 - 1 - 6000e18);
// //the initial 5 miner addresses are specfied below
// //changed payable[5] to 6
address payable[6] memory _initalMiners = [
address(0xE037EC8EC9ec423826750853899394dE7F024fee),
address(0xcdd8FA31AF8475574B8909F135d510579a8087d3),
address(0xb9dD5AfD86547Df817DA2d0Fb89334A6F8eDd891),
address(0x230570cD052f40E14C14a81038c6f3aa685d712B),
address(0x3233afA02644CCd048587F8ba6e99b3C00A34DcC),
address(0xe010aC6e0248790e08F42d5F697160DEDf97E024)
];
//Stake each of the 5 miners specified above
for (uint256 i = 0; i < 6; i++) {
//6th miner to allow for dispute
//Miner balance is set at 1000e18 at the block that this function is ran
TellorTransfer.updateBalanceAtNow(self.balances[_initalMiners[i]], 1000e18);
newStake(self, _initalMiners[i]);
}
//update the total suppply
self.uintVars[keccak256("total_supply")] += 6000e18; //6th miner to allow for dispute
//set Constants
self.uintVars[keccak256("decimals")] = 18;
self.uintVars[keccak256("targetMiners")] = 200;
self.uintVars[keccak256("stakeAmount")] = 1000e18;
self.uintVars[keccak256("disputeFee")] = 970e18;
self.uintVars[keccak256("timeTarget")] = 600;
self.uintVars[keccak256("timeOfLastNewValue")] = now - (now % self.uintVars[keccak256("timeTarget")]);
self.uintVars[keccak256("difficulty")] = 1;
}
/**
* @dev This function allows stakers to request to withdraw their stake (no longer stake)
* once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they
* can withdraw the deposit
*/
function requestStakingWithdraw(TellorStorage.TellorStorageStruct storage self) public {
TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender];
//Require that the miner is staked
require(stakes.currentStatus == 1, "Miner is not staked");
//Change the miner staked to locked to be withdrawStake
stakes.currentStatus = 2;
//Change the startDate to now since the lock up period begins now
//and the miner can only withdraw 7 days later from now(check the withdraw function)
stakes.startDate = now - (now % 86400);
//Reduce the staker count
self.uintVars[keccak256("stakerCount")] -= 1;
TellorDispute.updateDisputeFee(self);
emit StakeWithdrawRequested(msg.sender);
}
/**
* @dev This function allows users to withdraw their stake after a 7 day waiting period from request
*/
function withdrawStake(TellorStorage.TellorStorageStruct storage self) public {
TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender];
//Require the staker has locked for withdraw(currentStatus ==2) and that 7 days have
//passed by since they locked for withdraw
require(now - (now % 86400) - stakes.startDate >= 7 days, "7 days didn't pass");
require(stakes.currentStatus == 2, "Miner was not locked for withdrawal");
stakes.currentStatus = 0;
emit StakeWithdrawn(msg.sender);
}
/**
* @dev This function allows miners to deposit their stake.
*/
function depositStake(TellorStorage.TellorStorageStruct storage self) public {
newStake(self, msg.sender);
//self adjusting disputeFee
TellorDispute.updateDisputeFee(self);
}
/**
* @dev This function is used by the init function to succesfully stake the initial 5 miners.
* The function updates their status/state and status start date so they are locked it so they can't withdraw
* and updates the number of stakers in the system.
*/
function newStake(TellorStorage.TellorStorageStruct storage self, address staker) internal {
require(TellorTransfer.balanceOf(self, staker) >= self.uintVars[keccak256("stakeAmount")], "Balance is lower than stake amount");
//Ensure they can only stake if they are not currrently staked or if their stake time frame has ended
//and they are currently locked for witdhraw
require(self.stakerDetails[staker].currentStatus == 0 || self.stakerDetails[staker].currentStatus == 2, "Miner is in the wrong state");
self.uintVars[keccak256("stakerCount")] += 1;
self.stakerDetails[staker] = TellorStorage.StakeInfo({
currentStatus: 1, //this resets their stake start date to today
startDate: now - (now % 86400)
});
emit NewStake(staker);
}
}
//Slightly modified SafeMath library - includes a min and max function, removes useless div function
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function add(int256 a, int256 b) internal pure returns (int256 c) {
if (b > 0) {
c = a + b;
assert(c >= a);
} else {
c = a + b;
assert(c <= a);
}
}
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
function max(int256 a, int256 b) internal pure returns (uint256) {
return a > b ? uint256(a) : uint256(b);
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function sub(int256 a, int256 b) internal pure returns (int256 c) {
if (b > 0) {
c = a - b;
assert(c <= a);
} else {
c = a - b;
assert(c >= a);
}
}
}
/**
* @title Tellor Oracle Storage Library
* @dev Contains all the variables/structs used by Tellor
*/
library TellorStorage {
//Internal struct for use in proof-of-work submission
struct Details {
uint256 value;
address miner;
}
struct Dispute {
bytes32 hash; //unique hash of dispute: keccak256(_miner,_requestId,_timestamp)
int256 tally; //current tally of votes for - against measure
bool executed; //is the dispute settled
bool disputeVotePassed; //did the vote pass?
bool isPropFork; //true for fork proposal NEW
address reportedMiner; //miner who alledgedly submitted the 'bad value' will get disputeFee if dispute vote fails
address reportingParty; //miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes
address proposedForkAddress; //new fork address (if fork proposal)
mapping(bytes32 => uint256) disputeUintVars;
//Each of the variables below is saved in the mapping disputeUintVars for each disputeID
//e.g. TellorStorageStruct.DisputeById[disputeID].disputeUintVars[keccak256("requestId")]
//These are the variables saved in this mapping:
// uint keccak256("requestId");//apiID of disputed value
// uint keccak256("timestamp");//timestamp of distputed value
// uint keccak256("value"); //the value being disputed
// uint keccak256("minExecutionDate");//7 days from when dispute initialized
// uint keccak256("numberOfVotes");//the number of parties who have voted on the measure
// uint keccak256("blockNumber");// the blocknumber for which votes will be calculated from
// uint keccak256("minerSlot"); //index in dispute array
// uint keccak256("quorum"); //quorum for dispute vote NEW
// uint keccak256("fee"); //fee paid corresponding to dispute
mapping(address => bool) voted; //mapping of address to whether or not they voted
}
struct StakeInfo {
uint256 currentStatus; //0-not Staked, 1=Staked, 2=LockedForWithdraw 3= OnDispute
uint256 startDate; //stake start date
}
//Internal struct to allow balances to be queried by blocknumber for voting purposes
struct Checkpoint {
uint128 fromBlock; // fromBlock is the block number that the value was generated from
uint128 value; // value is the amount of tokens at a specific block number
}
struct Request {
string queryString; //id to string api
string dataSymbol; //short name for api request
bytes32 queryHash; //hash of api string and granularity e.g. keccak256(abi.encodePacked(_sapi,_granularity))
uint256[] requestTimestamps; //array of all newValueTimestamps requested
mapping(bytes32 => uint256) apiUintVars;
//Each of the variables below is saved in the mapping apiUintVars for each api request
//e.g. requestDetails[_requestId].apiUintVars[keccak256("totalTip")]
//These are the variables saved in this mapping:
// uint keccak256("granularity"); //multiplier for miners
// uint keccak256("requestQPosition"); //index in requestQ
// uint keccak256("totalTip");//bonus portion of payout
mapping(uint256 => uint256) minedBlockNum; //[apiId][minedTimestamp]=>block.number
//This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value
mapping(uint256 => uint256) finalValues;
mapping(uint256 => bool) inDispute; //checks if API id is in dispute or finalized.
mapping(uint256 => address[5]) minersByValue;
mapping(uint256 => uint256[5]) valuesByTimestamp;
}
struct TellorStorageStruct {
bytes32 currentChallenge; //current challenge to be solved
uint256[51] requestQ; //uint50 array of the top50 requests by payment amount
uint256[] newValueTimestamps; //array of all timestamps requested
Details[5] currentMiners; //This struct is for organizing the five mined values to find the median
mapping(bytes32 => address) addressVars;
//Address fields in the Tellor contract are saved the addressVars mapping
//e.g. addressVars[keccak256("tellorContract")] = address
//These are the variables saved in this mapping:
// address keccak256("tellorContract");//Tellor address
// address keccak256("_owner");//Tellor Owner address
// address keccak256("_deity");//Tellor Owner that can do things at will
mapping(bytes32 => uint256) uintVars;
//uint fields in the Tellor contract are saved the uintVars mapping
//e.g. uintVars[keccak256("decimals")] = uint
//These are the variables saved in this mapping:
// keccak256("decimals"); //18 decimal standard ERC20
// keccak256("disputeFee");//cost to dispute a mined value
// keccak256("disputeCount");//totalHistoricalDisputes
// keccak256("total_supply"); //total_supply of the token in circulation
// keccak256("stakeAmount");//stakeAmount for miners (we can cut gas if we just hardcode it in...or should it be variable?)
// keccak256("stakerCount"); //number of parties currently staked
// keccak256("timeOfLastNewValue"); // time of last challenge solved
// keccak256("difficulty"); // Difficulty of current block
// keccak256("currentTotalTips"); //value of highest api/timestamp PayoutPool
// keccak256("currentRequestId"); //API being mined--updates with the ApiOnQ Id
// keccak256("requestCount"); // total number of requests through the system
// keccak256("slotProgress");//Number of miners who have mined this value so far
// keccak256("miningReward");//Mining Reward in PoWo tokens given to all miners per value
// keccak256("timeTarget"); //The time between blocks (mined Oracle values)
//This is a boolean that tells you if a given challenge has been completed by a given miner
mapping(bytes32 => mapping(address => bool)) minersByChallenge;
mapping(uint256 => uint256) requestIdByTimestamp; //minedTimestamp to apiId
mapping(uint256 => uint256) requestIdByRequestQIndex; //link from payoutPoolIndex (position in payout pool array) to apiId
mapping(uint256 => Dispute) disputesById; //disputeId=> Dispute details
mapping(address => Checkpoint[]) balances; //balances of a party given blocks
mapping(address => mapping(address => uint256)) allowed; //allowance for a given party and approver
mapping(address => StakeInfo) stakerDetails; //mapping from a persons address to their staking info
mapping(uint256 => Request) requestDetails; //mapping of apiID to details
mapping(bytes32 => uint256) requestIdByQueryHash; // api bytes32 gets an id = to count of requests array
mapping(bytes32 => uint256) disputeIdByDisputeHash; //maps a hash to an ID for each dispute
}
}
//Functions for retrieving min and Max in 51 length array (requestQ)
//Taken partly from: https://github.com/modular-network/ethereum-libraries-array-utils/blob/master/contracts/Array256Lib.sol
library Utilities {
/**
* @dev Returns the minimum value in an array.
*/
function getMax(uint256[51] memory data) internal pure returns (uint256 max, uint256 maxIndex) {
max = data[1];
maxIndex;
for (uint256 i = 1; i < data.length; i++) {
if (data[i] > max) {
max = data[i];
maxIndex = i;
}
}
}
/**
* @dev Returns the minimum value in an array.
*/
function getMin(uint256[51] memory data) internal pure returns (uint256 min, uint256 minIndex) {
minIndex = data.length - 1;
min = data[minIndex];
for (uint256 i = data.length - 1; i > 0; i--) {
if (data[i] < min) {
min = data[i];
minIndex = i;
}
}
}
}
/**
* @title Tellor Getters Library
* @dev This is the getter library for all variables in the Tellor Tributes system. TellorGetters references this
* libary for the getters logic
*/
library TellorGettersLibrary {
using SafeMath for uint256;
event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true
/*Functions*/
//The next two functions are onlyOwner functions. For Tellor to be truly decentralized, we will need to transfer the Deity to the 0 address.
//Only needs to be in library
/**
* @dev This function allows us to set a new Deity (or remove it)
* @param _newDeity address of the new Deity of the tellor system
*/
function changeDeity(TellorStorage.TellorStorageStruct storage self, address _newDeity) internal {
require(self.addressVars[keccak256("_deity")] == msg.sender, "Sender is not deity");
self.addressVars[keccak256("_deity")] = _newDeity;
}
//Only needs to be in library
/**
* @dev This function allows the deity to upgrade the Tellor System
* @param _tellorContract address of new updated TellorCore contract
*/
function changeTellorContract(TellorStorage.TellorStorageStruct storage self, address _tellorContract) internal {
require(self.addressVars[keccak256("_deity")] == msg.sender, "Sender is not deity");
self.addressVars[keccak256("tellorContract")] = _tellorContract;
emit NewTellorAddress(_tellorContract);
}
/*Tellor Getters*/
/**
* @dev This function tells you if a given challenge has been completed by a given miner
* @param _challenge the challenge to search for
* @param _miner address that you want to know if they solved the challenge
* @return true if the _miner address provided solved the
*/
function didMine(TellorStorage.TellorStorageStruct storage self, bytes32 _challenge, address _miner) internal view returns (bool) {
return self.minersByChallenge[_challenge][_miner];
}
/**
* @dev Checks if an address voted in a dispute
* @param _disputeId to look up
* @param _address of voting party to look up
* @return bool of whether or not party voted
*/
function didVote(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, address _address) internal view returns (bool) {
return self.disputesById[_disputeId].voted[_address];
}
/**
* @dev allows Tellor to read data from the addressVars mapping
* @param _data is the keccak256("variable_name") of the variable that is being accessed.
* These are examples of how the variables are saved within other functions:
* addressVars[keccak256("_owner")]
* addressVars[keccak256("tellorContract")]
*/
function getAddressVars(TellorStorage.TellorStorageStruct storage self, bytes32 _data) internal view returns (address) {
return self.addressVars[_data];
}
/**
* @dev Gets all dispute variables
* @param _disputeId to look up
* @return bytes32 hash of dispute
* @return bool executed where true if it has been voted on
* @return bool disputeVotePassed
* @return bool isPropFork true if the dispute is a proposed fork
* @return address of reportedMiner
* @return address of reportingParty
* @return address of proposedForkAddress
* @return uint of requestId
* @return uint of timestamp
* @return uint of value
* @return uint of minExecutionDate
* @return uint of numberOfVotes
* @return uint of blocknumber
* @return uint of minerSlot
* @return uint of quorum
* @return uint of fee
* @return int count of the current tally
*/
function getAllDisputeVars(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId)
internal
view
returns (bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256)
{
TellorStorage.Dispute storage disp = self.disputesById[_disputeId];
return (
disp.hash,
disp.executed,
disp.disputeVotePassed,
disp.isPropFork,
disp.reportedMiner,
disp.reportingParty,
disp.proposedForkAddress,
[
disp.disputeUintVars[keccak256("requestId")],
disp.disputeUintVars[keccak256("timestamp")],
disp.disputeUintVars[keccak256("value")],
disp.disputeUintVars[keccak256("minExecutionDate")],
disp.disputeUintVars[keccak256("numberOfVotes")],
disp.disputeUintVars[keccak256("blockNumber")],
disp.disputeUintVars[keccak256("minerSlot")],
disp.disputeUintVars[keccak256("quorum")],
disp.disputeUintVars[keccak256("fee")]
],
disp.tally
);
}
/**
* @dev Getter function for variables for the requestId being currently mined(currentRequestId)
* @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request
*/
function getCurrentVariables(TellorStorage.TellorStorageStruct storage self)
internal
view
returns (bytes32, uint256, uint256, string memory, uint256, uint256)
{
return (
self.currentChallenge,
self.uintVars[keccak256("currentRequestId")],
self.uintVars[keccak256("difficulty")],
self.requestDetails[self.uintVars[keccak256("currentRequestId")]].queryString,
self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("granularity")],
self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("totalTip")]
);
}
/**
* @dev Checks if a given hash of miner,requestId has been disputed
* @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId));
* @return uint disputeId
*/
function getDisputeIdByDisputeHash(TellorStorage.TellorStorageStruct storage self, bytes32 _hash) internal view returns (uint256) {
return self.disputeIdByDisputeHash[_hash];
}
/**
* @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId
* @param _disputeId is the dispute id;
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the disputeUintVars under the Dispute struct
* @return uint value for the bytes32 data submitted
*/
function getDisputeUintVars(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, bytes32 _data)
internal
view
returns (uint256)
{
return self.disputesById[_disputeId].disputeUintVars[_data];
}
/**
* @dev Gets the a value for the latest timestamp available
* @return value for timestamp of last proof of work submited
* @return true if the is a timestamp for the lastNewValue
*/
function getLastNewValue(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256, bool) {
return (
retrieveData(
self,
self.requestIdByTimestamp[self.uintVars[keccak256("timeOfLastNewValue")]],
self.uintVars[keccak256("timeOfLastNewValue")]
),
true
);
}
/**
* @dev Gets the a value for the latest timestamp available
* @param _requestId being requested
* @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't
*/
function getLastNewValueById(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (uint256, bool) {
TellorStorage.Request storage _request = self.requestDetails[_requestId];
if (_request.requestTimestamps.length > 0) {
return (retrieveData(self, _requestId, _request.requestTimestamps[_request.requestTimestamps.length - 1]), true);
} else {
return (0, false);
}
}
/**
* @dev Gets blocknumber for mined timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up blocknumber
* @return uint of the blocknumber which the dispute was mined
*/
function getMinedBlockNum(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp)
internal
view
returns (uint256)
{
return self.requestDetails[_requestId].minedBlockNum[_timestamp];
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up miners for
* @return the 5 miners' addresses
*/
function getMinersByRequestIdAndTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp)
internal
view
returns (address[5] memory)
{
return self.requestDetails[_requestId].minersByValue[_timestamp];
}
/**
* @dev Get the name of the token
* @return string of the token name
*/
function getName(TellorStorage.TellorStorageStruct storage self) internal pure returns (string memory) {
return "Tellor Tributes";
}
/**
* @dev Counts the number of values that have been submited for the request
* if called for the currentRequest being mined it can tell you how many miners have submitted a value for that
* request so far
* @param _requestId the requestId to look up
* @return uint count of the number of values received for the requestId
*/
function getNewValueCountbyRequestId(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (uint256) {
return self.requestDetails[_requestId].requestTimestamps.length;
}
/**
* @dev Getter function for the specified requestQ index
* @param _index to look up in the requestQ array
* @return uint of reqeuestId
*/
function getRequestIdByRequestQIndex(TellorStorage.TellorStorageStruct storage self, uint256 _index) internal view returns (uint256) {
require(_index <= 50, "RequestQ index is above 50");
return self.requestIdByRequestQIndex[_index];
}
/**
* @dev Getter function for requestId based on timestamp
* @param _timestamp to check requestId
* @return uint of reqeuestId
*/
function getRequestIdByTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _timestamp) internal view returns (uint256) {
return self.requestIdByTimestamp[_timestamp];
}
/**
* @dev Getter function for requestId based on the qeuaryHash
* @param _queryHash hash(of string api and granularity) to check if a request already exists
* @return uint requestId
*/
function getRequestIdByQueryHash(TellorStorage.TellorStorageStruct storage self, bytes32 _queryHash) internal view returns (uint256) {
return self.requestIdByQueryHash[_queryHash];
}
/**
* @dev Getter function for the requestQ array
* @return the requestQ arrray
*/
function getRequestQ(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256[51] memory) {
return self.requestQ;
}
/**
* @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct
* for the requestId specified
* @param _requestId to look up
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the apiUintVars under the requestDetails struct
* @return uint value of the apiUintVars specified in _data for the requestId specified
*/
function getRequestUintVars(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, bytes32 _data)
internal
view
returns (uint256)
{
return self.requestDetails[_requestId].apiUintVars[_data];
}
/**
* @dev Gets the API struct variables that are not mappings
* @param _requestId to look up
* @return string of api to query
* @return string of symbol of api to query
* @return bytes32 hash of string
* @return bytes32 of the granularity(decimal places) requested
* @return uint of index in requestQ array
* @return uint of current payout/tip for this requestId
*/
function getRequestVars(TellorStorage.TellorStorageStruct storage self, uint256 _requestId)
internal
view
returns (string memory, string memory, bytes32, uint256, uint256, uint256)
{
TellorStorage.Request storage _request = self.requestDetails[_requestId];
return (
_request.queryString,
_request.dataSymbol,
_request.queryHash,
_request.apiUintVars[keccak256("granularity")],
_request.apiUintVars[keccak256("requestQPosition")],
_request.apiUintVars[keccak256("totalTip")]
);
}
/**
* @dev This function allows users to retireve all information about a staker
* @param _staker address of staker inquiring about
* @return uint current state of staker
* @return uint startDate of staking
*/
function getStakerInfo(TellorStorage.TellorStorageStruct storage self, address _staker) internal view returns (uint256, uint256) {
return (self.stakerDetails[_staker].currentStatus, self.stakerDetails[_staker].startDate);
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestampt to look up miners for
* @return address[5] array of 5 addresses ofminers that mined the requestId
*/
function getSubmissionsByTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp)
internal
view
returns (uint256[5] memory)
{
return self.requestDetails[_requestId].valuesByTimestamp[_timestamp];
}
/**
* @dev Get the symbol of the token
* @return string of the token symbol
*/
function getSymbol(TellorStorage.TellorStorageStruct storage self) internal pure returns (string memory) {
return "TT";
}
/**
* @dev Gets the timestamp for the value based on their index
* @param _requestID is the requestId to look up
* @param _index is the value index to look up
* @return uint timestamp
*/
function getTimestampbyRequestIDandIndex(TellorStorage.TellorStorageStruct storage self, uint256 _requestID, uint256 _index)
internal
view
returns (uint256)
{
return self.requestDetails[_requestID].requestTimestamps[_index];
}
/**
* @dev Getter for the variables saved under the TellorStorageStruct uintVars variable
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the uintVars under the TellorStorageStruct struct
* This is an example of how data is saved into the mapping within other functions:
* self.uintVars[keccak256("stakerCount")]
* @return uint of specified variable
*/
function getUintVar(TellorStorage.TellorStorageStruct storage self, bytes32 _data) internal view returns (uint256) {
return self.uintVars[_data];
}
/**
* @dev Getter function for next requestId on queue/request with highest payout at time the function is called
* @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string
*/
function getVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256, uint256, string memory) {
uint256 newRequestId = getTopRequestID(self);
return (
newRequestId,
self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")],
self.requestDetails[newRequestId].queryString
);
}
/**
* @dev Getter function for the request with highest payout. This function is used within the getVariablesOnDeck function
* @return uint _requestId of request with highest payout at the time the function is called
*/
function getTopRequestID(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256 _requestId) {
uint256 _max;
uint256 _index;
(_max, _index) = Utilities.getMax(self.requestQ);
_requestId = self.requestIdByRequestQIndex[_index];
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up miners for
* @return bool true if requestId/timestamp is under dispute
*/
function isInDispute(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (bool) {
return self.requestDetails[_requestId].inDispute[_timestamp];
}
/**
* @dev Retreive value from oracle based on requestId/timestamp
* @param _requestId being requested
* @param _timestamp to retreive data/value from
* @return uint value for requestId/timestamp submitted
*/
function retrieveData(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp)
internal
view
returns (uint256)
{
return self.requestDetails[_requestId].finalValues[_timestamp];
}
/**
* @dev Getter for the total_supply of oracle tokens
* @return uint total supply
*/
function totalSupply(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256) {
return self.uintVars[keccak256("total_supply")];
}
}
/**
* @title Tellor Oracle System Library
* @dev Contains the functions' logic for the Tellor contract where miners can submit the proof of work
* along with the value and smart contracts can requestData and tip miners.
*/
library TellorLibrary {
using SafeMath for uint256;
event TipAdded(address indexed _sender, uint256 indexed _requestId, uint256 _tip, uint256 _totalTips);
//Emits upon someone adding value to a pool; msg.sender, amount added, and timestamp incentivized to be mined
event DataRequested(
address indexed _sender,
string _query,
string _querySymbol,
uint256 _granularity,
uint256 indexed _requestId,
uint256 _totalTips
);
//emits when a new challenge is created (either on mined block or when a new request is pushed forward on waiting system)
event NewChallenge(
bytes32 _currentChallenge,
uint256 indexed _currentRequestId,
uint256 _difficulty,
uint256 _multiplier,
string _query,
uint256 _totalTips
);
//emits when a the payout of another request is higher after adding to the payoutPool or submitting a request
event NewRequestOnDeck(uint256 indexed _requestId, string _query, bytes32 _onDeckQueryHash, uint256 _onDeckTotalTips);
//Emits upon a successful Mine, indicates the blocktime at point of the mine and the value mined
event NewValue(uint256 indexed _requestId, uint256 _time, uint256 _value, uint256 _totalTips, bytes32 _currentChallenge);
//Emits upon each mine (5 total) and shows the miner, nonce, and value submitted
event NonceSubmitted(address indexed _miner, string _nonce, uint256 indexed _requestId, uint256 _value, bytes32 _currentChallenge);
event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner);
event OwnershipProposed(address indexed _previousOwner, address indexed _newOwner);
/*Functions*/
/*This is a cheat for demo purposes, will delete upon actual launch*/
/*function theLazyCoon(TellorStorage.TellorStorageStruct storage self,address _address, uint _amount) public {
self.uintVars[keccak256("total_supply")] += _amount;
TellorTransfer.updateBalanceAtNow(self.balances[_address],_amount);
} */
/**
* @dev Add tip to Request value from oracle
* @param _requestId being requested to be mined
* @param _tip amount the requester is willing to pay to be get on queue. Miners
* mine the onDeckQueryHash, or the api with the highest payout pool
*/
function addTip(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) public {
require(_requestId > 0, "RequestId is 0");
//If the tip > 0 transfer the tip to this contract
if (_tip > 0) {
TellorTransfer.doTransfer(self, msg.sender, address(this), _tip);
}
//Update the information for the request that should be mined next based on the tip submitted
updateOnDeck(self, _requestId, _tip);
emit TipAdded(msg.sender, _requestId, _tip, self.requestDetails[_requestId].apiUintVars[keccak256("totalTip")]);
}
/**
* @dev Request to retreive value from oracle based on timestamp. The tip is not required to be
* greater than 0 because there are no tokens in circulation for the initial(genesis) request
* @param _c_sapi string API being requested be mined
* @param _c_symbol is the short string symbol for the api request
* @param _granularity is the number of decimals miners should include on the submitted value
* @param _tip amount the requester is willing to pay to be get on queue. Miners
* mine the onDeckQueryHash, or the api with the highest payout pool
*/
function requestData(
TellorStorage.TellorStorageStruct storage self,
string memory _c_sapi,
string memory _c_symbol,
uint256 _granularity,
uint256 _tip
) public {
//Require at least one decimal place
require(_granularity > 0, "Too few decimal places");
//But no more than 18 decimal places
require(_granularity <= 1e18, "Too many decimal places");
//If it has been requested before then add the tip to it otherwise create the queryHash for it
string memory _sapi = _c_sapi;
string memory _symbol = _c_symbol;
require(bytes(_sapi).length > 0, "API string length is 0");
require(bytes(_symbol).length < 64, "API string symbol is greater than 64");
bytes32 _queryHash = keccak256(abi.encodePacked(_sapi, _granularity));
//If this is the first time the API and granularity combination has been requested then create the API and granularity hash
//otherwise the tip will be added to the requestId submitted
if (self.requestIdByQueryHash[_queryHash] == 0) {
self.uintVars[keccak256("requestCount")]++;
uint256 _requestId = self.uintVars[keccak256("requestCount")];
self.requestDetails[_requestId] = TellorStorage.Request({
queryString: _sapi,
dataSymbol: _symbol,
queryHash: _queryHash,
requestTimestamps: new uint256[](0)
});
self.requestDetails[_requestId].apiUintVars[keccak256("granularity")] = _granularity;
self.requestDetails[_requestId].apiUintVars[keccak256("requestQPosition")] = 0;
self.requestDetails[_requestId].apiUintVars[keccak256("totalTip")] = 0;
self.requestIdByQueryHash[_queryHash] = _requestId;
//If the tip > 0 it tranfers the tip to this contract
if (_tip > 0) {
TellorTransfer.doTransfer(self, msg.sender, address(this), _tip);
}
updateOnDeck(self, _requestId, _tip);
emit DataRequested(
msg.sender,
self.requestDetails[_requestId].queryString,
self.requestDetails[_requestId].dataSymbol,
_granularity,
_requestId,
_tip
);
//Add tip to existing request id since this is not the first time the api and granularity have been requested
} else {
addTip(self, self.requestIdByQueryHash[_queryHash], _tip);
}
}
/**
* @dev This fucntion is called by submitMiningSolution and adjusts the difficulty, sorts and stores the first
* 5 values received, pays the miners, the dev share and assigns a new challenge
* @param _nonce or solution for the PoW for the requestId
* @param _requestId for the current request being mined
*/
function newBlock(TellorStorage.TellorStorageStruct storage self, string memory _nonce, uint256 _requestId) internal {
TellorStorage.Request storage _request = self.requestDetails[_requestId];
// If the difference between the timeTarget and how long it takes to solve the challenge this updates the challenge
//difficulty up or donw by the difference between the target time and how long it took to solve the prevous challenge
//otherwise it sets it to 1
int256 _change = int256(SafeMath.min(1200, (now - self.uintVars[keccak256("timeOfLastNewValue")])));
_change = (int256(self.uintVars[keccak256("difficulty")]) * (int256(self.uintVars[keccak256("timeTarget")]) - _change)) / 4000;
if (_change < 2 && _change > -2) {
if (_change >= 0) {
_change = 1;
} else {
_change = -1;
}
}
if ((int256(self.uintVars[keccak256("difficulty")]) + _change) <= 0) {
self.uintVars[keccak256("difficulty")] = 1;
} else {
self.uintVars[keccak256("difficulty")] = uint256(int256(self.uintVars[keccak256("difficulty")]) + _change);
}
//Sets time of value submission rounded to 1 minute
uint256 _timeOfLastNewValue = now - (now % 1 minutes);
self.uintVars[keccak256("timeOfLastNewValue")] = _timeOfLastNewValue;
//The sorting algorithm that sorts the values of the first five values that come in
TellorStorage.Details[5] memory a = self.currentMiners;
uint256 i;
for (i = 1; i < 5; i++) {
uint256 temp = a[i].value;
address temp2 = a[i].miner;
uint256 j = i;
while (j > 0 && temp < a[j - 1].value) {
a[j].value = a[j - 1].value;
a[j].miner = a[j - 1].miner;
j--;
}
if (j < i) {
a[j].value = temp;
a[j].miner = temp2;
}
}
//Pay the miners
for (i = 0; i < 5; i++) {
TellorTransfer.doTransfer(self, address(this), a[i].miner, 5e18 + self.uintVars[keccak256("currentTotalTips")] / 5);
}
emit NewValue(
_requestId,
_timeOfLastNewValue,
a[2].value,
self.uintVars[keccak256("currentTotalTips")] - (self.uintVars[keccak256("currentTotalTips")] % 5),
self.currentChallenge
);
//update the total supply
self.uintVars[keccak256("total_supply")] += 275e17;
//pay the dev-share
TellorTransfer.doTransfer(self, address(this), self.addressVars[keccak256("_owner")], 25e17); //The ten there is the devshare
//Save the official(finalValue), timestamp of it, 5 miners and their submitted values for it, and its block number
_request.finalValues[_timeOfLastNewValue] = a[2].value;
_request.requestTimestamps.push(_timeOfLastNewValue);
//these are miners by timestamp
_request.minersByValue[_timeOfLastNewValue] = [a[0].miner, a[1].miner, a[2].miner, a[3].miner, a[4].miner];
_request.valuesByTimestamp[_timeOfLastNewValue] = [a[0].value, a[1].value, a[2].value, a[3].value, a[4].value];
_request.minedBlockNum[_timeOfLastNewValue] = block.number;
//map the timeOfLastValue to the requestId that was just mined
self.requestIdByTimestamp[_timeOfLastNewValue] = _requestId;
//add timeOfLastValue to the newValueTimestamps array
self.newValueTimestamps.push(_timeOfLastNewValue);
//re-start the count for the slot progress to zero before the new request mining starts
self.uintVars[keccak256("slotProgress")] = 0;
uint256 _topId = TellorGettersLibrary.getTopRequestID(self);
self.uintVars[keccak256("currentRequestId")] = _topId;
//if the currentRequestId is not zero(currentRequestId exists/something is being mined) select the requestId with the hightest payout
//else wait for a new tip to mine
if (_topId > 0) {
//Update the current request to be mined to the requestID with the highest payout
self.uintVars[keccak256("currentTotalTips")] = self.requestDetails[_topId].apiUintVars[keccak256("totalTip")];
//Remove the currentRequestId/onDeckRequestId from the requestQ array containing the rest of the 50 requests
self.requestQ[self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")]] = 0;
//unmap the currentRequestId/onDeckRequestId from the requestIdByRequestQIndex
self.requestIdByRequestQIndex[self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")]] = 0;
//Remove the requestQposition for the currentRequestId/onDeckRequestId since it will be mined next
self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")] = 0;
//Reset the requestId TotalTip to 0 for the currentRequestId/onDeckRequestId since it will be mined next
//and the tip is going to the current timestamp miners. The tip for the API needs to be reset to zero
self.requestDetails[_topId].apiUintVars[keccak256("totalTip")] = 0;
//gets the max tip in the in the requestQ[51] array and its index within the array??
uint256 newRequestId = TellorGettersLibrary.getTopRequestID(self);
//Issue the the next challenge
self.currentChallenge = keccak256(abi.encodePacked(_nonce, self.currentChallenge, blockhash(block.number - 1))); // Save hash for next proof
emit NewChallenge(
self.currentChallenge,
_topId,
self.uintVars[keccak256("difficulty")],
self.requestDetails[_topId].apiUintVars[keccak256("granularity")],
self.requestDetails[_topId].queryString,
self.uintVars[keccak256("currentTotalTips")]
);
emit NewRequestOnDeck(
newRequestId,
self.requestDetails[newRequestId].queryString,
self.requestDetails[newRequestId].queryHash,
self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")]
);
} else {
self.uintVars[keccak256("currentTotalTips")] = 0;
self.currentChallenge = "";
}
}
/**
* @dev Proof of work is called by the miner when they submit the solution (proof of work and value)
* @param _nonce uint submitted by miner
* @param _requestId the apiId being mined
* @param _value of api query
*/
function submitMiningSolution(TellorStorage.TellorStorageStruct storage self, string memory _nonce, uint256 _requestId, uint256 _value)
public
{
//requre miner is staked
require(self.stakerDetails[msg.sender].currentStatus == 1, "Miner status is not staker");
//Check the miner is submitting the pow for the current request Id
require(_requestId == self.uintVars[keccak256("currentRequestId")], "RequestId is wrong");
//Saving the challenge information as unique by using the msg.sender
require(
uint256(
sha256(abi.encodePacked(ripemd160(abi.encodePacked(keccak256(abi.encodePacked(self.currentChallenge, msg.sender, _nonce))))))
) %
self.uintVars[keccak256("difficulty")] ==
0,
"Challenge information is not saved"
);
//Make sure the miner does not submit a value more than once
require(self.minersByChallenge[self.currentChallenge][msg.sender] == false, "Miner already submitted the value");
//Save the miner and value received
self.currentMiners[self.uintVars[keccak256("slotProgress")]].value = _value;
self.currentMiners[self.uintVars[keccak256("slotProgress")]].miner = msg.sender;
//Add to the count how many values have been submitted, since only 5 are taken per request
self.uintVars[keccak256("slotProgress")]++;
//Update the miner status to true once they submit a value so they don't submit more than once
self.minersByChallenge[self.currentChallenge][msg.sender] = true;
emit NonceSubmitted(msg.sender, _nonce, _requestId, _value, self.currentChallenge);
//If 5 values have been received, adjust the difficulty otherwise sort the values until 5 are received
if (self.uintVars[keccak256("slotProgress")] == 5) {
newBlock(self, _nonce, _requestId);
}
}
/**
* @dev Allows the current owner to propose transfer control of the contract to a
* newOwner and the ownership is pending until the new owner calls the claimOwnership
* function
* @param _pendingOwner The address to transfer ownership to.
*/
function proposeOwnership(TellorStorage.TellorStorageStruct storage self, address payable _pendingOwner) internal {
require(msg.sender == self.addressVars[keccak256("_owner")], "Sender is not owner");
emit OwnershipProposed(self.addressVars[keccak256("_owner")], _pendingOwner);
self.addressVars[keccak256("pending_owner")] = _pendingOwner;
}
/**
* @dev Allows the new owner to claim control of the contract
*/
function claimOwnership(TellorStorage.TellorStorageStruct storage self) internal {
require(msg.sender == self.addressVars[keccak256("pending_owner")], "Sender is not pending owner");
emit OwnershipTransferred(self.addressVars[keccak256("_owner")], self.addressVars[keccak256("pending_owner")]);
self.addressVars[keccak256("_owner")] = self.addressVars[keccak256("pending_owner")];
}
/**
* @dev This function updates APIonQ and the requestQ when requestData or addTip are ran
* @param _requestId being requested
* @param _tip is the tip to add
*/
function updateOnDeck(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) internal {
TellorStorage.Request storage _request = self.requestDetails[_requestId];
uint256 onDeckRequestId = TellorGettersLibrary.getTopRequestID(self);
//If the tip >0 update the tip for the requestId
if (_tip > 0) {
_request.apiUintVars[keccak256("totalTip")] = _request.apiUintVars[keccak256("totalTip")].add(_tip);
}
//Set _payout for the submitted request
uint256 _payout = _request.apiUintVars[keccak256("totalTip")];
//If there is no current request being mined
//then set the currentRequestId to the requestid of the requestData or addtip requestId submitted,
// the totalTips to the payout/tip submitted, and issue a new mining challenge
if (self.uintVars[keccak256("currentRequestId")] == 0) {
_request.apiUintVars[keccak256("totalTip")] = 0;
self.uintVars[keccak256("currentRequestId")] = _requestId;
self.uintVars[keccak256("currentTotalTips")] = _payout;
self.currentChallenge = keccak256(abi.encodePacked(_payout, self.currentChallenge, blockhash(block.number - 1))); // Save hash for next proof
emit NewChallenge(
self.currentChallenge,
self.uintVars[keccak256("currentRequestId")],
self.uintVars[keccak256("difficulty")],
self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("granularity")],
self.requestDetails[self.uintVars[keccak256("currentRequestId")]].queryString,
self.uintVars[keccak256("currentTotalTips")]
);
} else {
//If there is no OnDeckRequestId
//then replace/add the requestId to be the OnDeckRequestId, queryHash and OnDeckTotalTips(current highest payout, aside from what
//is being currently mined)
if (_payout > self.requestDetails[onDeckRequestId].apiUintVars[keccak256("totalTip")] || (onDeckRequestId == 0)) {
//let everyone know the next on queue has been replaced
emit NewRequestOnDeck(_requestId, _request.queryString, _request.queryHash, _payout);
}
//if the request is not part of the requestQ[51] array
//then add to the requestQ[51] only if the _payout/tip is greater than the minimum(tip) in the requestQ[51] array
if (_request.apiUintVars[keccak256("requestQPosition")] == 0) {
uint256 _min;
uint256 _index;
(_min, _index) = Utilities.getMin(self.requestQ);
//we have to zero out the oldOne
//if the _payout is greater than the current minimum payout in the requestQ[51] or if the minimum is zero
//then add it to the requestQ array aand map its index information to the requestId and the apiUintvars
if (_payout > _min || _min == 0) {
self.requestQ[_index] = _payout;
self.requestDetails[self.requestIdByRequestQIndex[_index]].apiUintVars[keccak256("requestQPosition")] = 0;
self.requestIdByRequestQIndex[_index] = _requestId;
_request.apiUintVars[keccak256("requestQPosition")] = _index;
}
// else if the requestid is part of the requestQ[51] then update the tip for it
} else if (_tip > 0) {
self.requestQ[_request.apiUintVars[keccak256("requestQPosition")]] += _tip;
}
}
}
}
/**
* @title Tellor Oracle System
* @dev Oracle contract where miners can submit the proof of work along with the value.
* The logic for this contract is in TellorLibrary.sol, TellorDispute.sol, TellorStake.sol,
* and TellorTransfer.sol
*/
contract Tellor {
using SafeMath for uint256;
using TellorDispute for TellorStorage.TellorStorageStruct;
using TellorLibrary for TellorStorage.TellorStorageStruct;
using TellorStake for TellorStorage.TellorStorageStruct;
using TellorTransfer for TellorStorage.TellorStorageStruct;
TellorStorage.TellorStorageStruct tellor;
/*Functions*/
/*This is a cheat for demo purposes, will delete upon actual launch*/
/*function theLazyCoon(address _address, uint _amount) public {
tellor.theLazyCoon(_address,_amount);
}*/
/**
* @dev Helps initialize a dispute by assigning it a disputeId
* when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the
* invalidated value information to POS voting
* @param _requestId being disputed
* @param _timestamp being disputed
* @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value
* requires 5 miners to submit a value.
*/
function beginDispute(uint256 _requestId, uint256 _timestamp, uint256 _minerIndex) external {
tellor.beginDispute(_requestId, _timestamp, _minerIndex);
}
/**
* @dev Allows token holders to vote
* @param _disputeId is the dispute id
* @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute)
*/
function vote(uint256 _disputeId, bool _supportsDispute) external {
tellor.vote(_disputeId, _supportsDispute);
}
/**
* @dev tallies the votes.
* @param _disputeId is the dispute id
*/
function tallyVotes(uint256 _disputeId) external {
tellor.tallyVotes(_disputeId);
}
/**
* @dev Allows for a fork to be proposed
* @param _propNewTellorAddress address for new proposed Tellor
*/
function proposeFork(address _propNewTellorAddress) external {
tellor.proposeFork(_propNewTellorAddress);
}
/**
* @dev Add tip to Request value from oracle
* @param _requestId being requested to be mined
* @param _tip amount the requester is willing to pay to be get on queue. Miners
* mine the onDeckQueryHash, or the api with the highest payout pool
*/
function addTip(uint256 _requestId, uint256 _tip) external {
tellor.addTip(_requestId, _tip);
}
/**
* @dev Request to retreive value from oracle based on timestamp. The tip is not required to be
* greater than 0 because there are no tokens in circulation for the initial(genesis) request
* @param _c_sapi string API being requested be mined
* @param _c_symbol is the short string symbol for the api request
* @param _granularity is the number of decimals miners should include on the submitted value
* @param _tip amount the requester is willing to pay to be get on queue. Miners
* mine the onDeckQueryHash, or the api with the highest payout pool
*/
function requestData(string calldata _c_sapi, string calldata _c_symbol, uint256 _granularity, uint256 _tip) external {
tellor.requestData(_c_sapi, _c_symbol, _granularity, _tip);
}
/**
* @dev Proof of work is called by the miner when they submit the solution (proof of work and value)
* @param _nonce uint submitted by miner
* @param _requestId the apiId being mined
* @param _value of api query
*/
function submitMiningSolution(string calldata _nonce, uint256 _requestId, uint256 _value) external {
tellor.submitMiningSolution(_nonce, _requestId, _value);
}
/**
* @dev Allows the current owner to propose transfer control of the contract to a
* newOwner and the ownership is pending until the new owner calls the claimOwnership
* function
* @param _pendingOwner The address to transfer ownership to.
*/
function proposeOwnership(address payable _pendingOwner) external {
tellor.proposeOwnership(_pendingOwner);
}
/**
* @dev Allows the new owner to claim control of the contract
*/
function claimOwnership() external {
tellor.claimOwnership();
}
/**
* @dev This function allows miners to deposit their stake.
*/
function depositStake() external {
tellor.depositStake();
}
/**
* @dev This function allows stakers to request to withdraw their stake (no longer stake)
* once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they
* can withdraw the stake
*/
function requestStakingWithdraw() external {
tellor.requestStakingWithdraw();
}
/**
* @dev This function allows users to withdraw their stake after a 7 day waiting period from request
*/
function withdrawStake() external {
tellor.withdrawStake();
}
/**
* @dev This function approves a _spender an _amount of tokens to use
* @param _spender address
* @param _amount amount the spender is being approved for
* @return true if spender appproved successfully
*/
function approve(address _spender, uint256 _amount) external returns (bool) {
return tellor.approve(_spender, _amount);
}
/**
* @dev Allows for a transfer of tokens to _to
* @param _to The address to send tokens to
* @param _amount The amount of tokens to send
* @return true if transfer is successful
*/
function transfer(address _to, uint256 _amount) external returns (bool) {
return tellor.transfer(_to, _amount);
}
/**
* @dev Sends _amount tokens to _to from _from on the condition it
* is approved by _from
* @param _from The address holding the tokens being transferred
* @param _to The address of the recipient
* @param _amount The amount of tokens to be transferred
* @return True if the transfer was successful
*/
function transferFrom(address _from, address _to, uint256 _amount) external returns (bool) {
return tellor.transferFrom(_from, _to, _amount);
}
/**
* @dev Allows users to access the token's name
*/
function name() external pure returns (string memory) {
return "Tellor Tributes";
}
/**
* @dev Allows users to access the token's symbol
*/
function symbol() external pure returns (string memory) {
return "TRB";
}
/**
* @dev Allows users to access the number of decimals
*/
function decimals() external pure returns (uint8) {
return 18;
}
}
| * @dev Allows the current owner to propose transfer control of the contract to a newOwner and the ownership is pending until the new owner calls the claimOwnership function @param _pendingOwner The address to transfer ownership to./ | function proposeOwnership(TellorStorage.TellorStorageStruct storage self, address payable _pendingOwner) internal {
require(msg.sender == self.addressVars[keccak256("_owner")], "Sender is not owner");
emit OwnershipProposed(self.addressVars[keccak256("_owner")], _pendingOwner);
self.addressVars[keccak256("pending_owner")] = _pendingOwner;
}
| 12,861,505 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
5206,
25619,
326,
783,
3410,
358,
450,
4150,
7412,
3325,
434,
326,
6835,
358,
279,
394,
5541,
471,
326,
23178,
353,
4634,
3180,
326,
394,
3410,
4097,
326,
7516,
5460,
12565,
445,
632,
891,
389,
9561,
5541,
1021,
1758,
358,
7412,
23178,
358,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
450,
4150,
5460,
12565,
12,
21009,
280,
3245,
18,
21009,
280,
3245,
3823,
2502,
365,
16,
1758,
8843,
429,
389,
9561,
5541,
13,
2713,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
365,
18,
2867,
5555,
63,
79,
24410,
581,
5034,
2932,
67,
8443,
7923,
6487,
315,
12021,
353,
486,
3410,
8863,
203,
3639,
3626,
14223,
9646,
5310,
626,
7423,
12,
2890,
18,
2867,
5555,
63,
79,
24410,
581,
5034,
2932,
67,
8443,
7923,
6487,
389,
9561,
5541,
1769,
203,
3639,
365,
18,
2867,
5555,
63,
79,
24410,
581,
5034,
2932,
9561,
67,
8443,
7923,
65,
273,
389,
9561,
5541,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.15;
//import './lib/safeMath.sol';
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// import './ERC20.sol';
contract ERC20 {
uint256 public totalSupply;
function transferFrom(address from, address to, uint256 value) returns (bool);
function transfer(address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
function allowance(address owner, address spender) constant returns (uint256);
function balanceOf(address who) constant returns (uint256);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// import './helpers/BasicToken.sol';
contract BasicToken is ERC20 {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool) {
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
return false;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
uint256 _allowance = allowed[_from][msg.sender];
allowed[_from][msg.sender] = _allowance.sub(_value);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
Transfer(_from, _to, _value);
return true;
}
return false;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
// import './BiQToken.sol';
contract BiQToken is BasicToken {
using SafeMath for uint256;
string public name = "BurstIQ Token"; //name of the token
string public symbol = "BiQ"; // symbol of the token
uint8 public decimals = 18; // decimals
uint256 public totalSupply = 1000000000 * 10**18; // total supply of BiQ Tokens
// variables
uint256 public keyEmployeesAllocatedFund; // fund allocated to key employees
uint256 public advisorsAllocation; // fund allocated to advisors
uint256 public marketIncentivesAllocation; // fund allocated to Market
uint256 public vestingFounderAllocation; // funds allocated to founders that in under vesting period
uint256 public totalAllocatedTokens; // variable to keep track of funds allocated
uint256 public tokensAllocatedToCrowdFund; // funds allocated to crowdfund
uint256 public saftInvestorAllocation; // funds allocated to private presales and instituational investors
bool public isPublicTokenReleased = false; // flag to track the release the public token
// addresses
address public founderMultiSigAddress; // multi sign address of founders which hold
address public advisorAddress; // advisor address which hold advisorsAllocation funds
address public vestingFounderAddress; // address of founder that hold vestingFounderAllocation
address public crowdFundAddress; // address of crowdfund contract
// vesting period
uint256 public preAllocatedTokensVestingTime; // crowdfund start time + 6 months
//events
event ChangeFoundersWalletAddress(uint256 _blockTimeStamp, address indexed _foundersWalletAddress);
event TransferPreAllocatedFunds(uint256 _blockTimeStamp , address _to , uint256 _value);
event PublicTokenReleased(uint256 _blockTimeStamp);
//modifiers
modifier onlyCrowdFundAddress() {
require(msg.sender == crowdFundAddress);
_;
}
modifier nonZeroAddress(address _to) {
require(_to != 0x0);
_;
}
modifier onlyFounders() {
require(msg.sender == founderMultiSigAddress);
_;
}
modifier onlyVestingFounderAddress() {
require(msg.sender == vestingFounderAddress);
_;
}
modifier onlyAdvisorAddress() {
require(msg.sender == advisorAddress);
_;
}
modifier isPublicTokenNotReleased() {
require(isPublicTokenReleased == false);
_;
}
// creation of the token contract
function BiQToken (address _crowdFundAddress, address _founderMultiSigAddress, address _advisorAddress, address _vestingFounderAddress) {
crowdFundAddress = _crowdFundAddress;
founderMultiSigAddress = _founderMultiSigAddress;
vestingFounderAddress = _vestingFounderAddress;
advisorAddress = _advisorAddress;
// Token Distribution
vestingFounderAllocation = 18 * 10 ** 25 ; // 18 % allocation of totalSupply
keyEmployeesAllocatedFund = 2 * 10 ** 25 ; // 2 % allocation of totalSupply
advisorsAllocation = 5 * 10 ** 25 ; // 5 % allocation of totalSupply
tokensAllocatedToCrowdFund = 60 * 10 ** 25 ; // 60 % allocation of totalSupply
marketIncentivesAllocation = 5 * 10 ** 25 ; // 5 % allocation of totalSupply
saftInvestorAllocation = 10 * 10 ** 25 ; // 10 % alloaction of totalSupply
// Assigned balances to respective stakeholders
balances[founderMultiSigAddress] = keyEmployeesAllocatedFund + saftInvestorAllocation;
balances[crowdFundAddress] = tokensAllocatedToCrowdFund;
totalAllocatedTokens = balances[founderMultiSigAddress];
preAllocatedTokensVestingTime = now + 180 * 1 days; // it should be 6 months period for vesting
}
// function to keep track of the total token allocation
function changeTotalSupply(uint256 _amount) onlyCrowdFundAddress {
totalAllocatedTokens = totalAllocatedTokens.add(_amount);
tokensAllocatedToCrowdFund = tokensAllocatedToCrowdFund.sub(_amount);
}
// function to change founder multisig wallet address
function changeFounderMultiSigAddress(address _newFounderMultiSigAddress) onlyFounders nonZeroAddress(_newFounderMultiSigAddress) {
founderMultiSigAddress = _newFounderMultiSigAddress;
ChangeFoundersWalletAddress(now, founderMultiSigAddress);
}
// function for releasing the public tokens called once by the founder only
function releaseToken() onlyFounders isPublicTokenNotReleased {
isPublicTokenReleased = !isPublicTokenReleased;
PublicTokenReleased(now);
}
// function to transfer market Incentives fund
function transferMarketIncentivesFund(address _to, uint _value) onlyFounders nonZeroAddress(_to) returns (bool) {
if (marketIncentivesAllocation >= _value) {
marketIncentivesAllocation = marketIncentivesAllocation.sub(_value);
balances[_to] = balances[_to].add(_value);
totalAllocatedTokens = totalAllocatedTokens.add(_value);
TransferPreAllocatedFunds(now, _to, _value);
return true;
}
return false;
}
// fund transferred to vesting Founders address after 6 months
function getVestedFounderTokens() onlyVestingFounderAddress returns (bool) {
if (now >= preAllocatedTokensVestingTime && vestingFounderAllocation > 0) {
balances[vestingFounderAddress] = balances[vestingFounderAddress].add(vestingFounderAllocation);
totalAllocatedTokens = totalAllocatedTokens.add(vestingFounderAllocation);
vestingFounderAllocation = 0;
TransferPreAllocatedFunds(now, vestingFounderAddress, vestingFounderAllocation);
return true;
}
return false;
}
// fund transferred to vesting advisor address after 6 months
function getVestedAdvisorTokens() onlyAdvisorAddress returns (bool) {
if (now >= preAllocatedTokensVestingTime && advisorsAllocation > 0) {
balances[advisorAddress] = balances[advisorAddress].add(advisorsAllocation);
totalAllocatedTokens = totalAllocatedTokens.add(advisorsAllocation);
advisorsAllocation = 0;
TransferPreAllocatedFunds(now, advisorAddress, advisorsAllocation);
return true;
} else {
return false;
}
}
// overloaded transfer function to restrict the investor to transfer the token before the ICO sale ends
function transfer(address _to, uint256 _value) returns (bool) {
if (msg.sender == crowdFundAddress) {
return super.transfer(_to,_value);
} else {
if (isPublicTokenReleased) {
return super.transfer(_to,_value);
}
return false;
}
}
// overloaded transferFrom function to restrict the investor to transfer the token before the ICO sale ends
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
if (msg.sender == crowdFundAddress) {
return super.transferFrom(_from, _to, _value);
} else {
if (isPublicTokenReleased) {
return super.transferFrom(_from, _to, _value);
}
return false;
}
}
// fallback function to restrict direct sending of ether
function () {
revert();
}
}
contract BiQCrowdFund {
using SafeMath for uint256;
BiQToken public token; // Token contract reference
//variables
uint256 public crowdfundStartTime; // Starting time of CrowdFund
uint256 public crowdfundEndTime; // End time of Crowdfund
uint256 public totalWeiRaised = 0; // Counter to track the amount raised
uint256 public exchangeRate = 2307; // Calculated using priceOfEtherInUSD/priceOfBiQToken so 276.84/0.12
uint256 internal minAmount = 36.1219 * 10 ** 18; // Calculated using 10k USD / 276.84 USD
bool public isCrowdFundActive = false; // Flag to track the crowdfund active or not
bool internal isTokenDeployed = false; // Flag to track the token deployment -- only can be set once
bool internal hasCrowdFundStarted = false; // Flag to track if the crowdfund started
// addresses
address public founderMultiSigAddress; // Founders multisig address
address public remainingTokenHolder; // Address to hold the remaining tokens after crowdfund end
address public authorizerAddress; // Address of Authorizer who will authorize the investor
// mapping
mapping (address => uint256) auth; // KYC authentication
enum State { PreSale, CrowdFund }
//events
event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount);
event CrowdFundClosed(uint256 _blockTimeStamp);
event ChangeFoundersWalletAddress(uint256 _blockTimeStamp, address indexed _foundersWalletAddress);
//Modifiers
modifier tokenIsDeployed() {
require(isTokenDeployed == true);
_;
}
modifier nonZeroEth() {
require(msg.value > 0);
_;
}
modifier nonZeroAddress(address _to) {
require(_to != 0x0);
_;
}
modifier checkCrowdFundActive() {
require(isCrowdFundActive == true);
_;
}
modifier onlyFounders() {
require(msg.sender == founderMultiSigAddress);
_;
}
modifier onlyPublic() {
require(msg.sender != founderMultiSigAddress);
_;
}
modifier onlyAuthorizer() {
require(msg.sender == authorizerAddress);
_;
}
modifier inState(State state) {
require(getState() == state);
_;
}
// Constructor to initialize the local variables
function BiQCrowdFund (address _founderWalletAddress, address _remainingTokenHolder, address _authorizerAddress) {
founderMultiSigAddress = _founderWalletAddress;
remainingTokenHolder = _remainingTokenHolder;
authorizerAddress = _authorizerAddress;
}
// Function to change the founders multisig address
function setFounderMultiSigAddress(address _newFounderAddress) onlyFounders nonZeroAddress(_newFounderAddress) {
founderMultiSigAddress = _newFounderAddress;
ChangeFoundersWalletAddress(now, founderMultiSigAddress);
}
function setAuthorizerAddress(address _newAuthorizerAddress) onlyFounders nonZeroAddress(_newAuthorizerAddress) {
authorizerAddress = _newAuthorizerAddress;
}
function setRemainingTokenHolder(address _newRemainingTokenHolder) onlyFounders nonZeroAddress(_newRemainingTokenHolder) {
remainingTokenHolder = _newRemainingTokenHolder;
}
// Attach the token contract, can only be done once
function setTokenAddress(address _tokenAddress) onlyFounders nonZeroAddress(_tokenAddress) {
require(isTokenDeployed == false);
token = BiQToken(_tokenAddress);
isTokenDeployed = true;
}
// change the state of crowdfund
function changeCrowdfundState() tokenIsDeployed onlyFounders inState(State.CrowdFund) {
isCrowdFundActive = !isCrowdFundActive;
}
// for KYC/AML
function authorize(address _to, uint256 max_amount) onlyAuthorizer {
auth[_to] = max_amount * 1 ether;
}
// Buy token function call only in duration of crowdfund active
function buyTokens(address beneficiary) nonZeroEth tokenIsDeployed onlyPublic nonZeroAddress(beneficiary) payable returns(bool) {
// Only allow a certain amount for every investor
if (auth[beneficiary] < msg.value) {
revert();
}
auth[beneficiary] = auth[beneficiary].sub(msg.value);
if (getState() == State.PreSale) {
if (buyPreSaleTokens(beneficiary)) {
return true;
}
revert();
} else {
require(now < crowdfundEndTime && isCrowdFundActive);
fundTransfer(msg.value);
uint256 amount = getNoOfTokens(exchangeRate, msg.value);
if (token.transfer(beneficiary, amount)) {
token.changeTotalSupply(amount);
totalWeiRaised = totalWeiRaised.add(msg.value);
TokenPurchase(beneficiary, msg.value, amount);
return true;
}
revert();
}
}
// function to transfer the funds to founders account
function fundTransfer(uint256 weiAmount) internal {
founderMultiSigAddress.transfer(weiAmount);
}
///////////////////////////////////// Constant Functions /////////////////////////////////////
// function to get the current state of the crowdsale
function getState() public constant returns(State) {
if (!isCrowdFundActive && !hasCrowdFundStarted) {
return State.PreSale;
}
return State.CrowdFund;
}
// To get the authorized amount corresponding to an address
function getPreAuthorizedAmount(address _address) constant returns(uint256) {
return auth[_address];
}
// get the amount of tokens a user would receive for a specific amount of ether
function calculateTotalTokenPerContribution(uint256 _totalETHContribution) public constant returns(uint256) {
if (getState() == State.PreSale) {
return getTokensForPreSale(exchangeRate, _totalETHContribution * 1 ether).div(10 ** 18);
}
return getNoOfTokens(exchangeRate, _totalETHContribution);
}
// provides the bonus %
function currentBonus(uint256 _ethContribution) public constant returns (uint8) {
if (getState() == State.PreSale) {
return getPreSaleBonusRate(_ethContribution * 1 ether);
}
return getCurrentBonusRate();
}
///////////////////////////////////// Presale Functions /////////////////////////////////////
// function to buy the tokens at presale with minimum investment = 10k USD
function buyPreSaleTokens(address beneficiary) internal returns(bool) {
// check the minimum investment should be 10k USD
if (msg.value < minAmount) {
revert();
} else {
fundTransfer(msg.value);
uint256 amount = getTokensForPreSale(exchangeRate, msg.value);
if (token.transfer(beneficiary, amount)) {
token.changeTotalSupply(amount);
totalWeiRaised = totalWeiRaised.add(msg.value);
TokenPurchase(beneficiary, msg.value, amount);
return true;
}
return false;
}
}
// function calculate the total no of tokens with bonus multiplication in the duration of presale
function getTokensForPreSale(uint256 _exchangeRate, uint256 _amount) internal returns (uint256) {
uint256 noOfToken = _amount.mul(_exchangeRate);
uint256 preSaleTokenQuantity = ((100 + getPreSaleBonusRate(_amount)) * noOfToken ).div(100);
return preSaleTokenQuantity;
}
function getPreSaleBonusRate(uint256 _ethAmount) internal returns (uint8) {
if ( _ethAmount >= minAmount.mul(5) && _ethAmount < minAmount.mul(10)) {
return 30;
}
if (_ethAmount >= minAmount.mul(10)) {
return 35;
}
if (_ethAmount >= minAmount) {
return 25;
}
}
///////////////////////////////////// Crowdfund Functions /////////////////////////////////////
// Starts the crowdfund, can only be called once
function startCrowdfund(uint256 _exchangeRate) onlyFounders tokenIsDeployed inState(State.PreSale) {
if (_exchangeRate > 0 && !hasCrowdFundStarted) {
exchangeRate = _exchangeRate;
crowdfundStartTime = now;
crowdfundEndTime = crowdfundStartTime + 5 * 1 weeks; // end date is 5 weeks after the starting date
isCrowdFundActive = !isCrowdFundActive;
hasCrowdFundStarted = !hasCrowdFundStarted;
} else {
revert();
}
}
// function call after crowdFundEndTime.
// It transfers the remaining tokens to remainingTokenHolder address
function endCrowdfund() onlyFounders returns (bool) {
require(now > crowdfundEndTime);
uint256 remainingToken = token.balanceOf(this); // remaining tokens
if (remainingToken != 0 && token.transfer(remainingTokenHolder, remainingToken)) {
return true;
} else {
return false;
}
CrowdFundClosed(now);
}
// function to calculate the total no of tokens with bonus multiplication
function getNoOfTokens(uint256 _exchangeRate, uint256 _amount) internal returns (uint256) {
uint256 noOfToken = _amount.mul(_exchangeRate);
uint256 noOfTokenWithBonus = ((100 + getCurrentBonusRate()) * noOfToken).div(100);
return noOfTokenWithBonus;
}
// function provide the current bonus rate
function getCurrentBonusRate() internal returns (uint8) {
if (now > crowdfundStartTime + 4 weeks) {
return 0;
}
if (now > crowdfundStartTime + 3 weeks) {
return 5;
}
if (now > crowdfundStartTime + 2 weeks) {
return 10;
}
if (now > crowdfundStartTime + 1 weeks) {
return 15;
}
if (now > crowdfundStartTime) {
return 20;
}
}
// Crowdfund entry
// send ether to the contract address
// With at least 200 000 gas
function() public payable {
buyTokens(msg.sender);
}
} | End time of Crowdfund
| uint256 public crowdfundEndTime; | 931,188 | [
1,
4625,
348,
7953,
560,
30,
225,
4403,
813,
434,
385,
492,
2180,
1074,
203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
276,
492,
2180,
1074,
25255,
31,
13491,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
//labels contract owner only methods
import "@openzeppelin/contracts/access/Ownable.sol";
//interface of an ERC2981 compliant contract
import "../../ERC2981/IERC2981.sol";
//interface of a Rarible Royalties v2 compliant contract
import "../../Rarible/RoyaltiesV2.sol";
//abstract that considers royalty fees in multi classes
import "../../MultiClass/abstractions/MultiClassFees.sol";
/**
* @dev Abstract of cross compliant royalties in multi classes
*/
abstract contract MintpressChargable is
MultiClassFees,
RoyaltiesV2,
Ownable
{
/*
* bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
*/
bytes4 internal constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
/**
* @dev Sets a fee that will be collected during the exchange method
*/
function allocate(uint256 classId, address recipient, uint96 fee)
external virtual onlyOwner
{
_allocateFee(classId, recipient, fee);
}
/**
* @dev Removes a fee
*/
function deallocate(uint256 classId, address recipient)
external virtual onlyOwner
{
_deallocateFee(classId, recipient);
}
/**
* @dev Removes a fee
*/
function deallocateAll(uint256 classId)
external virtual onlyOwner
{
_deallocateFees(classId);
}
/**
* @dev implements Rari getRaribleV2Royalties()
*/
function getRaribleV2Royalties(uint256 tokenId)
external view virtual returns(LibPart.Part[] memory)
{
uint256 classId = classOf(tokenId);
uint256 size = _recipients[classId].length;
//this is how to set the size of an array in memory
LibPart.Part[] memory royalties = new LibPart.Part[](size);
for (uint i = 0; i < size; i++) {
address recipient = _recipients[classId][i];
royalties[i] = LibPart.Part(
payable(recipient),
_fee[classId][recipient]
);
}
return royalties;
}
/**
* @dev implements ERC2981 `royaltyInfo()`
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
virtual
returns(address receiver, uint256 royaltyAmount)
{
uint256 classId = classOf(_tokenId);
if (_recipients[classId].length == 0) {
return (address(0), 0);
}
address recipient = _recipients[classId][0];
return (
payable(recipient),
(_salePrice * _fee[classId][recipient]) / 10000
);
}
}
| * @dev implements Rari getRaribleV2Royalties()/this is how to set the size of an array in memory | function getRaribleV2Royalties(uint256 tokenId)
external view virtual returns(LibPart.Part[] memory)
{
uint256 classId = classOf(tokenId);
uint256 size = _recipients[classId].length;
LibPart.Part[] memory royalties = new LibPart.Part[](size);
for (uint i = 0; i < size; i++) {
address recipient = _recipients[classId][i];
royalties[i] = LibPart.Part(
payable(recipient),
_fee[classId][recipient]
);
}
return royalties;
}
| 13,068,471 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
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,
4170,
297,
1523,
58,
22,
54,
13372,
2390,
606,
12,
11890,
5034,
1147,
548,
13,
7010,
565,
3903,
1476,
5024,
1135,
12,
5664,
1988,
18,
1988,
8526,
3778,
13,
7010,
225,
288,
203,
565,
2254,
5034,
31181,
273,
667,
951,
12,
2316,
548,
1769,
203,
565,
2254,
5034,
963,
273,
389,
27925,
63,
1106,
548,
8009,
2469,
31,
203,
565,
10560,
1988,
18,
1988,
8526,
3778,
721,
93,
2390,
606,
273,
394,
10560,
1988,
18,
1988,
8526,
12,
1467,
1769,
203,
565,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
963,
31,
277,
27245,
288,
203,
1377,
1758,
8027,
273,
389,
27925,
63,
1106,
548,
6362,
77,
15533,
203,
1377,
721,
93,
2390,
606,
63,
77,
65,
273,
10560,
1988,
18,
1988,
12,
203,
3639,
8843,
429,
12,
20367,
3631,
7010,
3639,
389,
21386,
63,
1106,
548,
6362,
20367,
65,
203,
1377,
11272,
203,
565,
289,
203,
203,
565,
327,
721,
93,
2390,
606,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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-12-11
*/
// After ShibaDoge, we finally have ShibaFloki!
// tg: ShibaFlokiETH
// tw: ShibaFlokiETH
// web: shibaflokieth.com
// ~ 1 billion marketcap ~
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.7;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev 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);
}
}
}
}
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);
}
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
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 IUniswapV2Router02 {
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
contract ShibaFloki is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
mapping(address => bool) private _isSniper;
address[] private _confirmedSnipers;
address payable public _marketingAddress = payable(0x67ba2971465Ec970D986509a641c0Bd35d0Ac227);
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 100 * 10**9 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "Shiba Floki";
string private _symbol = "$ShibFloki";
uint8 private _decimals = 9;
uint256 public _taxFee = 0;
uint256 private _previousTaxFee = _taxFee;
uint256 public _marketingFee = 12;
uint256 private _previousmarketingFee = _marketingFee;
uint256 launchTime;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
bool tradingOpen = false;
uint256 public _maxTxAmount = 2 * 10**9 * 10**9;
// Liquify when 400m tokens are stored
uint256 private numTokensSellToLiquify = 400 * 10**6 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived
);
event TransferToMarketing(uint256 ethTransferred);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor () {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_marketingAddress] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function openTrading() external onlyOwner {
tradingOpen = true;
launchTime = block.timestamp;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setmarketingFeePercent(uint256 marketingFee) external onlyOwner() {
_marketingFee = marketingFee;
}
function setTaxFeePercent(uint256 taxFee) external onlyOwner {
_taxFee = taxFee;
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
_maxTxAmount = _tTotal.mul(maxTxPercent).div(
10**2
);
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
//to receive ETH from uniswapV2Router when swapping
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculatemarketingFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**2
);
}
function calculatemarketingFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_marketingFee).div(
10**2
);
}
function removeAllFee() private {
if(_taxFee == 0 && _marketingFee == 0) return;
_previousTaxFee = _taxFee;
_previousmarketingFee = _marketingFee;
_taxFee = 0;
_marketingFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_marketingFee = _previousmarketingFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address 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");
require(!_isSniper[to], 'You have no power here!');
require(!_isSniper[msg.sender], 'You have no power here!');
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
// buy
if (from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to]) {
require(tradingOpen, 'Trading not yet enabled.');
//antibot
if (block.timestamp == launchTime) {
_isSniper[to] = true;
_confirmedSnipers.push(to);
}
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToLiquify;
if (
overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToLiquify;
swapAndLiquify(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from,to,amount,takeFee);
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
uint256 marketingTokenBalance = contractTokenBalance;
// 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(marketingTokenBalance);
// Total eth that has been swapped
uint256 ethSwapped = address(this).balance.sub(initialBalance);
emit SwapAndLiquify(marketingTokenBalance, ethSwapped);
// The remaining eth balance is to be Transferred to the marketing wallet
uint256 marketingethToTransfer = ethSwapped;
// Transfer the eth to the marketing wallet
_marketingAddress.transfer(marketingethToTransfer);
emit TransferToMarketing(marketingethToTransfer);
}
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
);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function isRemovedSniper(address account) public view returns (bool) {
return _isSniper[account];
}
function _removeSniper(address account) external onlyOwner {
require(
account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D,
'We can not blacklist Uniswap'
);
require(!_isSniper[account], 'Account is already blacklisted');
_isSniper[account] = true;
_confirmedSnipers.push(account);
}
function _amnestySniper(address account) external onlyOwner {
require(_isSniper[account], 'Account is not blacklisted');
for (uint256 i = 0; i < _confirmedSnipers.length; i++) {
if (_confirmedSnipers[i] == account) {
_confirmedSnipers[i] = _confirmedSnipers[_confirmedSnipers.length - 1];
_isSniper[account] = false;
_confirmedSnipers.pop();
break;
}
}
}
} | is the token balance of this contract address over the min number of tokens that we need to initiate a swap? also, don't get caught in a circular liquidity event. also, don't swap & liquify if sender is uniswap pair. buyantibotif any account belongs to _isExcludedFromFee account then remove the fee | 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");
require(!_isSniper[to], 'You have no power here!');
require(!_isSniper[msg.sender], 'You have no power here!');
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to]) {
require(tradingOpen, 'Trading not yet enabled.');
if (block.timestamp == launchTime) {
_isSniper[to] = true;
_confirmedSnipers.push(to);
}
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToLiquify;
if (
overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToLiquify;
swapAndLiquify(contractTokenBalance);
}
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
}
| 1,127,397 | [
1,
4625,
348,
7953,
560,
30,
225,
353,
326,
1147,
11013,
434,
333,
6835,
1758,
1879,
326,
1131,
1300,
434,
2430,
716,
732,
1608,
358,
18711,
279,
7720,
35,
2546,
16,
2727,
1404,
336,
13537,
316,
279,
15302,
4501,
372,
24237,
871,
18,
2546,
16,
2727,
1404,
7720,
473,
4501,
372,
1164,
309,
5793,
353,
640,
291,
91,
438,
3082,
18,
30143,
970,
495,
352,
430,
1281,
2236,
11081,
358,
389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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3238,
288,
203,
3639,
2583,
12,
2080,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
5912,
3844,
1297,
506,
6802,
2353,
3634,
8863,
203,
3639,
2583,
12,
5,
67,
291,
10461,
77,
457,
63,
869,
6487,
296,
6225,
1240,
1158,
7212,
2674,
5124,
1769,
203,
3639,
2583,
12,
5,
67,
291,
10461,
77,
457,
63,
3576,
18,
15330,
6487,
296,
6225,
1240,
1158,
7212,
2674,
5124,
1769,
203,
3639,
309,
12,
2080,
480,
3410,
1435,
597,
358,
480,
3410,
10756,
203,
5411,
2583,
12,
8949,
1648,
389,
1896,
4188,
6275,
16,
315,
5912,
3844,
14399,
326,
943,
4188,
6275,
1199,
1769,
203,
203,
3639,
2254,
5034,
6835,
1345,
13937,
273,
11013,
951,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
309,
12,
16351,
1345,
13937,
1545,
389,
1896,
4188,
6275,
13,
203,
3639,
288,
203,
5411,
6835,
1345,
13937,
273,
389,
1896,
4188,
6275,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
2080,
422,
640,
291,
91,
438,
58,
22,
4154,
597,
358,
480,
1758,
12,
318,
291,
91,
438,
58,
22,
8259,
13,
597,
401,
67,
291,
16461,
1265,
14667,
63,
869,
5717,
288,
203,
5411,
2583,
12,
313,
14968,
3678,
16,
296,
1609,
7459,
486,
4671,
3696,
1093,
1769,
203,
203,
5411,
309,
261,
2629,
18,
5508,
422,
8037,
950,
13,
288,
203,
7734,
389,
291,
10461,
77,
457,
63,
869,
65,
273,
638,
31,
203,
7734,
389,
21606,
10461,
625,
414,
18,
6206,
12,
869,
1769,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
1426,
1879,
2930,
1345,
13937,
273,
6835,
1345,
13937,
1545,
818,
5157,
55,
1165,
774,
48,
18988,
1164,
31,
203,
3639,
309,
261,
203,
5411,
1879,
2930,
1345,
13937,
597,
401,
267,
12521,
1876,
48,
18988,
1164,
597,
628,
480,
640,
291,
91,
438,
58,
22,
4154,
597,
7720,
1876,
48,
18988,
1164,
1526,
203,
3639,
262,
288,
203,
5411,
6835,
1345,
13937,
273,
818,
5157,
55,
1165,
774,
48,
18988,
1164,
31,
203,
5411,
7720,
1876,
48,
18988,
1164,
12,
16351,
1345,
13937,
1769,
203,
3639,
289,
203,
203,
203,
3639,
309,
24899,
291,
16461,
1265,
14667,
63,
2080,
65,
747,
389,
291,
16461,
1265,
14667,
63,
869,
5717,
95,
203,
5411,
4862,
14667,
273,
629,
31,
203,
3639,
289,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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-10-29
*/
pragma solidity ^0.5.0;
//
//----------------------------------------
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Safe Math Library
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0);
c = a / b;
}
}
contract KoromaruInu is ERC20Interface, SafeMath {
string public name;
string public symbol;
uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it
uint256 public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor() public {
name = "Koromaru Inu";
symbol = "KORO";
decimals = 9;
_totalSupply = 100000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
function totalSupply() public view returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
} | * Constrctor function Initializes contract with initial supply tokens to the creator of the contract/ | constructor() public {
name = "Koromaru Inu";
symbol = "KORO";
decimals = 9;
_totalSupply = 100000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
| 2,143,487 | [
1,
4625,
348,
7953,
560,
30,
380,
735,
701,
30206,
445,
10188,
3128,
6835,
598,
2172,
14467,
2430,
358,
326,
11784,
434,
326,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,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3639,
389,
4963,
3088,
1283,
273,
2130,
12648,
2787,
9449,
31,
203,
203,
3639,
324,
26488,
63,
3576,
18,
15330,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
1234,
18,
15330,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x05F21089728C02C392bdcaEA1697DCF24d91559f/sources/contracts/VoteScatter.sol | * @dev See {IGovernor-castVoteWithReasonAndParamsBySig}./ | function castVoteWithReasonAndParamsBySig(
uint256 proposalId,
uint8 support,
string calldata reason,
bytes memory params,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override nftHolderOnly returns (uint256) {
address voter = ECDSA.recover(
_hashTypedDataV4(
keccak256(
abi.encode(
EXTENDED_BALLOT_TYPEHASH,
proposalId,
support,
keccak256(bytes(reason)),
keccak256(params)
)
)
),
v,
r,
s
);
return _castVote(proposalId, voter, support, reason, params);
}
| 1,942,427 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
5206,
2164,
288,
3047,
1643,
29561,
17,
4155,
19338,
1190,
8385,
1876,
1370,
858,
8267,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4812,
19338,
1190,
8385,
1876,
1370,
858,
8267,
12,
203,
3639,
2254,
5034,
14708,
548,
16,
203,
3639,
2254,
28,
2865,
16,
203,
3639,
533,
745,
892,
3971,
16,
203,
3639,
1731,
3778,
859,
16,
203,
3639,
2254,
28,
331,
16,
203,
3639,
1731,
1578,
436,
16,
203,
3639,
1731,
1578,
272,
203,
565,
262,
1071,
5024,
3849,
290,
1222,
6064,
3386,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
1758,
331,
20005,
273,
7773,
19748,
18,
266,
3165,
12,
203,
5411,
389,
2816,
11985,
751,
58,
24,
12,
203,
7734,
417,
24410,
581,
5034,
12,
203,
10792,
24126,
18,
3015,
12,
203,
13491,
11112,
22088,
67,
38,
1013,
1502,
56,
67,
2399,
15920,
16,
203,
13491,
14708,
548,
16,
203,
13491,
2865,
16,
203,
13491,
417,
24410,
581,
5034,
12,
3890,
12,
10579,
13,
3631,
203,
13491,
417,
24410,
581,
5034,
12,
2010,
13,
203,
10792,
262,
203,
7734,
262,
203,
5411,
262,
16,
203,
5411,
331,
16,
203,
5411,
436,
16,
203,
5411,
272,
203,
3639,
11272,
203,
203,
3639,
327,
389,
4155,
19338,
12,
685,
8016,
548,
16,
331,
20005,
16,
2865,
16,
3971,
16,
859,
1769,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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 GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev 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;
}
}
/**
* @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");
}
}
}
// Interface to represent a contract in pools that requires additional
// deposit and withdraw of LP tokens. One of the examples at the time of writing
// is Yearn vault, which takes yCRV which is already LP token and returns yyCRV
interface Stakeable {
function deposit(uint) external;
function withdraw(uint) external;
}
/**
* @dev A token holder contract that will allow a beneficiary to extract the
* tokens after a given release time.
*
* Useful for simple vesting schedules like "advisors get all of their tokens
* after 1 year".
*/
contract TokenTimelock {
using SafeERC20 for IERC20;
// ERC20 basic token contract being held
IERC20 private _token;
// beneficiary of tokens after they are released
address private _beneficiary;
// timestamp when token release is enabled
uint256 private _releaseTime;
constructor (IERC20 token, address beneficiary, uint256 releaseTime) public {
// solhint-disable-next-line not-rely-on-time
require(releaseTime > block.timestamp, "TokenTimelock: release time is before current time");
_token = token;
_beneficiary = beneficiary;
_releaseTime = releaseTime;
}
/**
* @return the token being held.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view returns (address) {
return _beneficiary;
}
/**
* @return the time when the tokens are released.
*/
function releaseTime() public view returns (uint256) {
return _releaseTime;
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function release() public virtual {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp >= _releaseTime, "TokenTimelock: current time is before release time");
uint256 amount = _token.balanceOf(address(this));
require(amount > 0, "TokenTimelock: no tokens to release");
_token.safeTransfer(_beneficiary, amount);
}
}
contract HolderTimelock is TokenTimelock {
constructor(
IERC20 _token,
address _beneficiary,
uint256 _releaseTime
)
public
TokenTimelock(_token, _beneficiary, _releaseTime)
//solhint-disable-next-line
{}
}
/**
* @dev A token holder contract that will allow a beneficiary to extract the
* tokens by portions based on a metric (TVL)
*
* This is ported from openzeppelin-ethereum-package
*
* Currently the holder contract is Ownable (while the owner is current beneficiary)
* still, this allows to check the method calls in blockchain to verify fair play.
* In the future it will be possible to use automated calculation, e.g. using
* https://github.com/ConcourseOpen/DeFi-Pulse-Adapters TVL calculation, then
* ownership would be transferred to the managing contract.
*/
contract HolderTVLLock is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 private constant RELEASE_PERCENT = 2;
uint256 private constant RELEASE_INTERVAL = 1 weeks;
// ERC20 basic token contract being held
IERC20 private _token;
// beneficiary of tokens after they are released
address private _beneficiary;
// timestamp when token release was made last time
uint256 private _lastReleaseTime;
// timestamp of first possible release time
uint256 private _firstReleaseTime;
// TVL metric for last release time
uint256 private _lastReleaseTVL;
// amount that already was released
uint256 private _released;
event TVLReleasePerformed(uint256 newTVL);
constructor (IERC20 token, address beneficiary, uint256 firstReleaseTime) public {
//as contract is deployed by Holyheld token, transfer ownership to dev
transferOwnership(beneficiary);
// solhint-disable-next-line not-rely-on-time
require(firstReleaseTime > block.timestamp, "release time before current time");
_token = token;
_beneficiary = beneficiary;
_firstReleaseTime = firstReleaseTime;
}
/**
* @return the token being held.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view returns (address) {
return _beneficiary;
}
/**
* @return the time when the tokens were released last time.
*/
function lastReleaseTime() public view returns (uint256) {
return _lastReleaseTime;
}
/**
* @return the TVL marked when the tokens were released last time.
*/
function lastReleaseTVL() public view returns (uint256) {
return _lastReleaseTVL;
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
* only owner can call this method as it will write new TVL metric value
* into the holder contract
*/
function release(uint256 _newTVL) public onlyOwner {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp >= _firstReleaseTime, "current time before release time");
require(block.timestamp > _lastReleaseTime + RELEASE_INTERVAL, "release interval is not passed");
require(_newTVL > _lastReleaseTVL, "only release if TVL is higher");
// calculate amount that is possible to release
uint256 balance = _token.balanceOf(address(this));
uint256 totalBalance = balance.add(_released);
uint256 amount = totalBalance.mul(RELEASE_PERCENT).div(100);
require(balance > amount, "available balance depleted");
_token.safeTransfer(_beneficiary, amount);
_lastReleaseTime = block.timestamp;
_lastReleaseTVL = _newTVL;
_released = _released.add(amount);
emit TVLReleasePerformed(_newTVL);
}
}
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract HolderVesting is Ownable {
// The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is
// therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore,
// it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a
// cliff period of a year and a duration of four years, are safe to use.
// solhint-disable not-rely-on-time
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 private constant RELEASE_INTERVAL = 1 weeks;
event TokensReleased(address token, uint256 amount);
event TokenVestingRevoked(address token);
// beneficiary of tokens after they are released
address private _beneficiary;
// ERC20 basic token contract being held
IERC20 private _token;
// Durations and timestamps are expressed in UNIX time, the same units as block.timestamp.
uint256 private _start;
uint256 private _duration;
// timestamp when token release was made last time
uint256 private _lastReleaseTime;
bool private _revocable;
uint256 private _released;
bool private _revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* beneficiary, gradually in a linear fashion until start + duration. By then all
* of the balance will have vested.
* @param beneficiary address of the beneficiary to whom vested tokens are transferred
* @param start the time (as Unix time) at which point vesting starts
* @param duration duration in seconds of the period in which the tokens will vest
* @param revocable whether the vesting is revocable or not
*/
constructor(IERC20 token, address beneficiary, uint256 start, uint256 duration, bool revocable) public {
require(beneficiary != address(0), "beneficiary is zero address");
require(duration > 0, "duration is 0");
// solhint-disable-next-line max-line-length
require(start.add(duration) > block.timestamp, "final time before current time");
_token = token;
_beneficiary = beneficiary;
//as contract is deployed by Holyheld token, transfer ownership to dev
transferOwnership(beneficiary);
_revocable = revocable;
_duration = duration;
_start = start;
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view returns (address) {
return _beneficiary;
}
/**
* @return the start time of the token vesting.
*/
function start() public view returns (uint256) {
return _start;
}
/**
* @return the duration of the token vesting.
*/
function duration() public view returns (uint256) {
return _duration;
}
/**
* @return true if the vesting is revocable.
*/
function revocable() public view returns (bool) {
return _revocable;
}
/**
* @return the amount of the token released.
*/
function released() public view returns (uint256) {
return _released;
}
/**
* @return true if the token is revoked.
*/
function revoked() public view returns (bool) {
return _revoked;
}
/**
* @return the time when the tokens were released last time.
*/
function lastReleaseTime() public view returns (uint256) {
return _lastReleaseTime;
}
/**
* @notice Transfers vested tokens to beneficiary.
*/
function release() public {
uint256 unreleased = _releasableAmount();
require(unreleased > 0, "no tokens are due");
require(block.timestamp > _lastReleaseTime + RELEASE_INTERVAL, "release interval is not passed");
_released = _released.add(unreleased);
_token.safeTransfer(_beneficiary, unreleased);
_lastReleaseTime = block.timestamp;
emit TokensReleased(address(_token), unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
*/
function revoke() public onlyOwner {
require(_revocable, "cannot revoke");
require(!_revoked, "vesting already revoked");
uint256 balance = _token.balanceOf(address(this));
uint256 unreleased = _releasableAmount();
uint256 refund = balance.sub(unreleased);
_revoked = true;
_token.safeTransfer(owner(), refund);
emit TokenVestingRevoked(address(_token));
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
*/
function _releasableAmount() private view returns (uint256) {
return _vestedAmount().sub(_released);
}
/**
* @dev Calculates the amount that has already vested.
*/
function _vestedAmount() private view returns (uint256) {
uint256 currentBalance = _token.balanceOf(address(this));
uint256 totalBalance = currentBalance.add(_released);
if (block.timestamp < _start) {
return 0;
} else if (block.timestamp >= _start.add(_duration) || _revoked) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(_start)).div(_duration);
}
}
}
/**
* @dev // HolyKnight is using LP to distribute Holyheld token
*
* it does not mint any HOLY tokens, they must be present on the
* contract's token balance. Balance is not intended to be refillable.
*
* Note that it's ownable and the owner wields tremendous power. The ownership
* will be transferred to a governance smart contract once HOLY is sufficiently
* distributed and the community can show to govern itself.
*
* Have fun reading it. Hopefully it's bug-free. God bless.
*/
contract HolyKnight 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 HOLYs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accHolyPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accHolyPerShare` (and `lastRewardCalcBlock`) 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.
// Thus every change in pool or allocation will result in recalculation of values
// (otherwise distribution remains constant btwn blocks and will be properly calculated)
uint256 stakedLPAmount;
}
// Info of each pool
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract
uint256 allocPoint; // How many allocation points assigned to this pool. HOLYs to distribute per block
uint256 lastRewardCalcBlock; // Last block number for which HOLYs distribution is already calculated for the pool
uint256 accHolyPerShare; // Accumulated HOLYs per share, times 1e12. See below
bool stakeable; // we should call deposit method on the LP tokens provided (used for e.g. vault staking)
address stakeableContract; // location where to deposit LP tokens if pool is stakeable
IERC20 stakedHoldableToken;
}
// The Holyheld token
HolyToken public holytoken;
// Dev address
address public devaddr;
// Treasury address
address public treasuryaddr;
// The block number when HOLY mining starts
uint256 public startBlock;
// The block number when HOLY mining targeted to end (if full allocation).
// used only for token distribution calculation, this is not a hard limit
uint256 public targetEndBlock;
// Total amount of tokens to distribute
uint256 public totalSupply;
// Reserved percent of HOLY tokens for current distribution (e.g. when pool allocation is intentionally not full)
uint256 public reservedPercent;
// HOLY tokens created per block, calculatable through updateHolyPerBlock()
// updated once in the constructor and owner calling setReserve (if needed)
uint256 public holyPerBlock;
// Info of each pool
PoolInfo[] public poolInfo;
// Total allocation points. Must be the sum of all allocation points in all pools
uint256 public totalAllocPoint = 0;
// Info of each user that stakes LP tokens
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Info of total amount of staked LP tokens by all users
mapping (address => uint256) public totalStaked;
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);
event Treasury(address indexed token, address treasury, uint256 amount);
constructor(
HolyToken _token,
address _devaddr,
address _treasuryaddr,
uint256 _totalsupply,
uint256 _reservedPercent,
uint256 _startBlock,
uint256 _targetEndBlock
) public {
holytoken = _token;
devaddr = _devaddr;
treasuryaddr = _treasuryaddr;
// as knight is deployed by Holyheld token, transfer ownership to dev
transferOwnership(_devaddr);
totalSupply = _totalsupply;
reservedPercent = _reservedPercent;
startBlock = _startBlock;
targetEndBlock = _targetEndBlock;
// calculate initial token number per block
updateHolyPerBlock();
}
// Reserve some percentage of HOLY token distribution
// (e.g. initially, 10% of tokens are reserved for future pools to be added)
function setReserve(uint256 _reservedPercent) public onlyOwner {
reservedPercent = _reservedPercent;
updateHolyPerBlock();
}
function updateHolyPerBlock() internal {
// safemath substraction cannot overflow
holyPerBlock = totalSupply.sub(totalSupply.mul(reservedPercent).div(100)).div(targetEndBlock.sub(startBlock));
massUpdatePools();
}
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 _stakeable, address _stakeableContract, IERC20 _stakedHoldableToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardCalcBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardCalcBlock: lastRewardCalcBlock,
accHolyPerShare: 0,
stakeable: _stakeable,
stakeableContract: _stakeableContract,
stakedHoldableToken: IERC20(_stakedHoldableToken)
}));
if(_stakeable)
{
_lpToken.approve(_stakeableContract, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
}
}
// Update the given pool's HOLY 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;
}
// View function to see pending HOLYs on frontend.
function pendingHoly(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accHolyPerShare = pool.accHolyPerShare;
uint256 lpSupply = totalStaked[address(pool.lpToken)];
if (block.number > pool.lastRewardCalcBlock && lpSupply != 0) {
uint256 multiplier = block.number.sub(pool.lastRewardCalcBlock);
uint256 tokenReward = multiplier.mul(holyPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accHolyPerShare = accHolyPerShare.add(tokenReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accHolyPerShare).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 when lpSupply changes
// For every deposit/withdraw/harvest pool recalculates accumulated token value
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardCalcBlock) {
return;
}
uint256 lpSupply = totalStaked[address(pool.lpToken)];
if (lpSupply == 0) {
pool.lastRewardCalcBlock = block.number;
return;
}
uint256 multiplier = block.number.sub(pool.lastRewardCalcBlock);
uint256 tokenRewardAccumulated = multiplier.mul(holyPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
// no minting is required, the contract already has token balance pre-allocated
// accumulated HOLY per share is stored multiplied by 10^12 to allow small 'fractional' values
pool.accHolyPerShare = pool.accHolyPerShare.add(tokenRewardAccumulated.mul(1e12).div(lpSupply));
pool.lastRewardCalcBlock = block.number;
}
// Deposit LP tokens to HolyKnight for HOLY 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.accHolyPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeTokenTransfer(msg.sender, pending); //pay the earned tokens when user deposits
}
}
// this condition would save some gas on harvest calls
if (_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accHolyPerShare).div(1e12);
totalStaked[address(pool.lpToken)] = totalStaked[address(pool.lpToken)].add(_amount);
if (pool.stakeable) {
uint256 prevbalance = pool.stakedHoldableToken.balanceOf(address(this));
Stakeable(pool.stakeableContract).deposit(_amount);
uint256 balancetoadd = pool.stakedHoldableToken.balanceOf(address(this)).sub(prevbalance);
user.stakedLPAmount = user.stakedLPAmount.add(balancetoadd);
// protect received tokens from moving to treasury
totalStaked[address(pool.stakedHoldableToken)] = totalStaked[address(pool.stakedHoldableToken)].add(balancetoadd);
}
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from HolyKnight.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accHolyPerShare).div(1e12).sub(user.rewardDebt);
safeTokenTransfer(msg.sender, pending);
if (pool.stakeable) {
// reclaim back original LP tokens and withdraw all of them, regardless of amount
Stakeable(pool.stakeableContract).withdraw(user.stakedLPAmount);
totalStaked[address(pool.stakedHoldableToken)] = totalStaked[address(pool.stakedHoldableToken)].sub(user.stakedLPAmount);
user.stakedLPAmount = 0;
// even if returned amount is less (fees, etc.), return all that is available
// (can be impacting treasury rewards if abused, but is not viable due to gas costs
// and treasury yields can be claimed periodically)
uint256 balance = pool.lpToken.balanceOf(address(this));
if (user.amount < balance) {
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
} else {
pool.lpToken.safeTransfer(address(msg.sender), balance);
}
totalStaked[address(pool.lpToken)] = totalStaked[address(pool.lpToken)].sub(user.amount);
user.amount = 0;
user.rewardDebt = 0;
} else {
require(user.amount >= _amount, "withdraw: not good");
pool.lpToken.safeTransfer(address(msg.sender), _amount);
totalStaked[address(pool.lpToken)] = totalStaked[address(pool.lpToken)].sub(_amount);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accHolyPerShare).div(1e12);
}
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw LP tokens without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (pool.stakeable) {
// reclaim back original LP tokens and withdraw all of them, regardless of amount
Stakeable(pool.stakeableContract).withdraw(user.stakedLPAmount);
totalStaked[address(pool.stakedHoldableToken)] = totalStaked[address(pool.stakedHoldableToken)].sub(user.stakedLPAmount);
user.stakedLPAmount = 0;
uint256 balance = pool.lpToken.balanceOf(address(this));
if (user.amount < balance) {
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
} else {
pool.lpToken.safeTransfer(address(msg.sender), balance);
}
} else {
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
}
totalStaked[address(pool.lpToken)] = totalStaked[address(pool.lpToken)].sub(user.amount);
user.amount = 0;
user.rewardDebt = 0;
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
}
// Safe holyheld token transfer function, just in case if rounding error causes pool to not have enough HOLYs.
function safeTokenTransfer(address _to, uint256 _amount) internal {
uint256 balance = holytoken.balanceOf(address(this));
if (_amount > balance) {
holytoken.transfer(_to, balance);
} else {
holytoken.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "forbidden");
devaddr = _devaddr;
}
// Update treasury address by the previous treasury.
function treasury(address _treasuryaddr) public {
require(msg.sender == treasuryaddr, "forbidden");
treasuryaddr = _treasuryaddr;
}
// Send yield on an LP token to the treasury
// have just address (and not pid) as agrument to be able to recover
// tokens that could be directly transferred and not present in pools
function putToTreasury(address _token) public onlyOwner {
uint256 availablebalance = getAvailableBalance(_token);
require(availablebalance > 0, "not enough tokens");
putToTreasuryAmount(_token, availablebalance);
}
// Send yield amount realized from holding LP tokens to the treasury
function putToTreasuryAmount(address _token, uint256 _amount) public onlyOwner {
require(_token != address(holytoken), "cannot transfer holy tokens");
uint256 availablebalance = getAvailableBalance(_token);
require(_amount <= availablebalance, "not enough tokens");
IERC20(_token).safeTransfer(treasuryaddr, _amount);
emit Treasury(_token, treasuryaddr, _amount);
}
// Get available token balance that can be put to treasury
// For pools with internal staking, all lpToken balance is contract's
// (bacause user tokens are converted to pool.stakedHoldableToken when depositing)
// HOLY tokens themselves and user lpTokens are protected by this check
function getAvailableBalance(address _token) internal view returns (uint256) {
uint256 availablebalance = IERC20(_token).balanceOf(address(this)) - totalStaked[_token];
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid]; //storage pointer used read-only
if (pool.stakeable && address(pool.lpToken) == _token)
{
availablebalance = IERC20(_token).balanceOf(address(this));
break;
}
}
return availablebalance;
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
/**
* @dev // Holyheld token is a ERC20 token for Holyheld.
*
* total amount is fixed at 100M HOLY tokens.
* HOLY token does not have mint functions.
* It will allocate upon creation the initial transfers
* of tokens. It is not ownable or having any other
* means of distribution other than transfers in its constructor.
*/
// HolyToken. Ownable, fixed-amount (non-mintable) with governance to be added
contract HolyToken is ERC20("Holyheld", "HOLY") {
// main developers (founders) multi-sig wallet
// 1 mln tokens
address public founder;
// Treasury
// accumulates LP yield
address public treasury;
// weekly vested supply, reclaimable by 2% in a week by founder (WeeklyVested contract)
// 9 mln
address public timeVestedSupply;
// TVL-growth vested supply, reclaimable by 2% in a week if TVL is a new ATH (TVLVested contract)
// 10 mln
address public growthVestedSupply;
// main supply, locked for 4 months (TimeVested contract)
// 56 mln
address public mainSupply;
// Pool supply (ruled by HolyKnight contract)
// 24 mln
address public poolSupply;
uint public constant AMOUNT_INITLIQUIDITY = 1000000 * 1e18;
uint public constant AMOUNT_OPERATIONS = 9000000 * 1e18;
uint public constant AMOUNT_TEAM = 10000000 * 1e18;
uint public constant DISTRIBUTION_SUPPLY = 24000000 * 1e18;
uint public constant DISTRIBUTION_RESERVE_PERCENT = 20;
uint public constant MAIN_SUPPLY = 56000000 * 1e18;
uint public constant MAIN_SUPPLY_VESTING_PERIOD = 127 days;
uint public constant VESTING_START = 1602115200; //8 Oct 2020
uint public constant VESTING_START_GROWTH = 1604188800; //1 Nov 2020
// parameters for HolyKnight construction
uint public constant START_LP_BLOCK = 10950946;
// used for tokens per block calculation to distribute in about 4 months
uint public constant END_LP_BLOCK = 11669960;
// Constructor code is only run when the contract
// is created
constructor(address _founder, address _treasuryaddr) public {
founder = _founder; //address that deployed contract becomes initial founder
treasury = _treasuryaddr; //treasury address is created beforehand
// Timelock contract will hold main supply for 4 months till Jan 2021
mainSupply = address(new HolderTimelock(this, founder, block.timestamp + MAIN_SUPPLY_VESTING_PERIOD));
// TVL metric based vesting
growthVestedSupply = address(new HolderTVLLock(this, founder, VESTING_START_GROWTH));
// Standard continuous vesting contract
timeVestedSupply = address(new HolderVesting(this, founder, VESTING_START, 365 days, false));
// HOLY token distribution though liquidity mining
poolSupply = address(new HolyKnight(this, founder, treasury, DISTRIBUTION_SUPPLY, DISTRIBUTION_RESERVE_PERCENT, START_LP_BLOCK, END_LP_BLOCK));
//allocate tokens to addresses upon creation, no further minting possible
_mint(founder, AMOUNT_INITLIQUIDITY);
_mint(timeVestedSupply, AMOUNT_OPERATIONS);
_mint(growthVestedSupply, AMOUNT_TEAM);
_mint(poolSupply, DISTRIBUTION_SUPPLY);
_mint(mainSupply, MAIN_SUPPLY);
}
} | Deposit LP tokens to HolyKnight for HOLY allocation. this condition would save some gas on harvest calls protect received tokens from moving to treasury | 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.accHolyPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accHolyPerShare).div(1e12);
totalStaked[address(pool.lpToken)] = totalStaked[address(pool.lpToken)].add(_amount);
if (pool.stakeable) {
uint256 prevbalance = pool.stakedHoldableToken.balanceOf(address(this));
Stakeable(pool.stakeableContract).deposit(_amount);
uint256 balancetoadd = pool.stakedHoldableToken.balanceOf(address(this)).sub(prevbalance);
user.stakedLPAmount = user.stakedLPAmount.add(balancetoadd);
totalStaked[address(pool.stakedHoldableToken)] = totalStaked[address(pool.stakedHoldableToken)].add(balancetoadd);
}
emit Deposit(msg.sender, _pid, _amount);
}
| 2,154,643 | [
1,
4625,
348,
7953,
560,
30,
225,
4019,
538,
305,
511,
52,
2430,
358,
670,
355,
93,
47,
18840,
364,
670,
1741,
61,
13481,
18,
333,
2269,
4102,
1923,
2690,
16189,
603,
17895,
26923,
4097,
17151,
5079,
2430,
628,
12499,
358,
9787,
345,
22498,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
443,
1724,
12,
11890,
5034,
389,
6610,
16,
2254,
5034,
389,
8949,
13,
1071,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
6610,
6362,
3576,
18,
15330,
15533,
203,
3639,
1089,
2864,
24899,
6610,
1769,
203,
3639,
309,
261,
1355,
18,
8949,
405,
374,
13,
288,
203,
5411,
2254,
5034,
4634,
273,
729,
18,
8949,
18,
16411,
12,
6011,
18,
8981,
44,
355,
93,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
2934,
1717,
12,
1355,
18,
266,
2913,
758,
23602,
1769,
203,
5411,
309,
12,
9561,
405,
374,
13,
288,
203,
5411,
289,
203,
3639,
289,
203,
3639,
309,
261,
67,
8949,
405,
374,
13,
288,
203,
5411,
2845,
18,
9953,
1345,
18,
4626,
5912,
1265,
12,
2867,
12,
3576,
18,
15330,
3631,
1758,
12,
2211,
3631,
389,
8949,
1769,
203,
5411,
729,
18,
8949,
273,
729,
18,
8949,
18,
1289,
24899,
8949,
1769,
203,
3639,
289,
203,
3639,
729,
18,
266,
2913,
758,
23602,
273,
729,
18,
8949,
18,
16411,
12,
6011,
18,
8981,
44,
355,
93,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
1769,
203,
203,
3639,
2078,
510,
9477,
63,
2867,
12,
6011,
18,
9953,
1345,
25887,
273,
2078,
510,
9477,
63,
2867,
12,
6011,
18,
9953,
1345,
13,
8009,
1289,
24899,
8949,
1769,
203,
3639,
309,
261,
6011,
18,
334,
911,
429,
13,
288,
203,
5411,
2254,
5034,
2807,
12296,
273,
2845,
18,
334,
9477,
20586,
429,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
5411,
934,
911,
429,
12,
6011,
18,
334,
911,
429,
8924,
2934,
323,
1724,
24899,
8949,
1769,
203,
5411,
2254,
5034,
324,
4316,
71,
11453,
1289,
273,
2845,
18,
334,
9477,
20586,
429,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
13,
2934,
1717,
12,
10001,
12296,
1769,
203,
5411,
729,
18,
334,
9477,
48,
4066,
4778,
273,
729,
18,
334,
9477,
48,
4066,
4778,
18,
1289,
12,
70,
4316,
71,
11453,
1289,
1769,
203,
5411,
2078,
510,
9477,
63,
2867,
12,
6011,
18,
334,
9477,
20586,
429,
1345,
25887,
273,
2078,
510,
9477,
63,
2867,
12,
6011,
18,
334,
9477,
20586,
429,
1345,
13,
8009,
1289,
12,
70,
4316,
71,
11453,
1289,
1769,
203,
3639,
289,
203,
203,
3639,
3626,
4019,
538,
305,
12,
3576,
18,
15330,
16,
389,
6610,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x1Cb26B29837E07018fFd692046B10Dc734446503/sources/contracts/interfaces/IFlashLoanReceiver.sol | * @title IFlashLoanReceiver interface @notice Interface for the Aave fee IFlashLoanReceiver. @author Aave @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract/ | interface IFlashLoanReceiver {
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external returns (bool);
function ADDRESSES_PROVIDER() external view returns (ILendingPoolAddressesProvider);
function LENDING_POOL() external view returns (ILendingPool);
pragma solidity ^0.6.6;
}
| 4,704,953 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
2649,
467,
11353,
1504,
304,
12952,
1560,
632,
20392,
6682,
364,
326,
432,
836,
14036,
467,
11353,
1504,
304,
12952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892,
7176,
16,
203,
565,
2254,
5034,
8526,
745,
892,
30980,
16,
203,
565,
2254,
5034,
8526,
745,
892,
23020,
5077,
87,
16,
203,
565,
1758,
26030,
16,
203,
565,
1731,
745,
892,
859,
203,
225,
262,
3903,
1135,
261,
6430,
1769,
203,
203,
225,
445,
11689,
7031,
1090,
55,
67,
26413,
1435,
3903,
1476,
1135,
261,
2627,
2846,
2864,
7148,
2249,
1769,
203,
203,
225,
445,
511,
12280,
67,
20339,
1435,
3903,
1476,
1135,
261,
2627,
2846,
2864,
1769,
203,
683,
9454,
18035,
560,
3602,
20,
18,
26,
18,
26,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Events contract for deployment on optimism
// Audit report available at https://www.tkd-coop.com/files/audit.pdf
//SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
//Control who can access various functions.
contract AccessControl {
address payable public creatorAddress;
mapping(address => bool) public admins;
modifier onlyCREATOR() {
require(msg.sender == creatorAddress, "1");
_;
}
modifier onlyADMINS() {
require(admins[msg.sender] == true);
_;
}
//Admins are contracts or addresses that have write access
function addAdmin(address _newAdmin) public onlyCREATOR {
if (admins[_newAdmin] == false) {
admins[_newAdmin] = true;
}
}
function removeAdmin(address _oldAdmin) public onlyCREATOR {
if (admins[_oldAdmin] == true) {
admins[_oldAdmin] = false;
}
}
// Constructor
// CHANGE CREATOR BACK BEFORE DEPLOYING
constructor() {
creatorAddress = msg.sender;
}
}
//Interface to TAC Contract
abstract contract ITAC {
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual returns (bool);
function balanceOf(address account) external view virtual returns (uint256);
}
//Interface to CoopData Contract
abstract contract ICoopData {
function recordEventMatch(
address _winner,
uint8 _winnerPoints,
address _loser,
uint8 _loserPoints,
address _referee
) public virtual;
}
contract OEvents is AccessControl {
/////////////////////////////////////////////////DATA STRUCTURES AND GLOBAL VARIABLES ///////////////////////////////////////////////////////////////////////
uint16 public numEvents = 0; //number of events created
uint256 public eventHostingCost = 100000000000000000000; //cost to host an event in Hwangs.
//Main data structure to hold info about an event
struct Event {
address promoter; //the person who holds the tournament
string eventName;
uint64 time;
uint64 eventId;
uint16 allowedMatches;
}
Event[] allEvents;
// Mapping storing which users are authorized to act as staff for which event.
// A user can only be authorized for one event at a time
mapping(address => uint64) public tournamentStaff;
address public TACContract = 0xABa8ace37f301E7a3A3FaD44682C8Ec8DC2BD18A;
address public CoopDataContract =
0xABa8ace37f301E7a3A3FaD44682C8Ec8DC2BD18A;
/////////////////////////////////////////////////////////CONTRACT CONTROL FUNCTIONS //////////////////////////////////////////////////
function changeParameters(
uint256 _eventHostingCost,
address _TACContract,
address _CoopDataContract
) external onlyCREATOR {
eventHostingCost = _eventHostingCost;
TACContract = _TACContract;
CoopDataContract = _CoopDataContract;
}
function getParameters() external view returns (uint256 _eventHostingCost) {
_eventHostingCost = eventHostingCost;
}
/////////////////////////////////////////////////////////EVENT FUNCTIONS //////////////////////////////////////////////////
function hostEvent(uint64 startTime, string memory eventName) public {
Event memory newEvent;
ITAC TAC = ITAC(TACContract);
require(
TAC.balanceOf(msg.sender) >= eventHostingCost,
"You need to have more TAC to open an event. "
);
TAC.transferFrom(msg.sender, creatorAddress, eventHostingCost);
newEvent.promoter = msg.sender;
newEvent.eventName = eventName;
newEvent.time = startTime;
newEvent.eventId = numEvents;
newEvent.allowedMatches = 0;
allEvents.push(newEvent);
numEvents += 1;
}
function getEvent(uint64 _eventId)
public
view
returns (
address promoter,
uint64 time,
uint64 eventId,
string memory eventName,
uint16 allowedMatches
)
{
Event memory eventToGet = allEvents[_eventId];
promoter = eventToGet.promoter;
time = eventToGet.time;
eventName = eventToGet.eventName;
eventId = eventToGet.eventId;
allowedMatches = eventToGet.allowedMatches;
}
function approveEvent(uint64 _eventId, uint16 _numMatches)
public
onlyADMINS
{
// Function to allow an event host to approve a specified number of matches.
allEvents[_eventId].allowedMatches = _numMatches;
}
//Function a tournament promoter can call to delegate staff to record matches.
function addStaff(uint64 _eventId, address _newStaff) public {
//Check that the tournament promoter is the caller
require(
msg.sender == allEvents[_eventId].promoter,
"Only the promoter can add staff"
);
tournamentStaff[_newStaff] = _eventId;
}
function recordEventMatch(
uint64 _eventId,
address _winner,
uint8 _winnerPoints,
address _loser,
uint8 _loserPoints,
address _referee
) public {
//Check that the tournament promoter is the caller
require(
(msg.sender == allEvents[_eventId].promoter ||
tournamentStaff[msg.sender] == _eventId),
"Only the promoter can record event matches"
);
//Check that the event has enough matches left.
require(
allEvents[_eventId].allowedMatches > 0,
"This event does not have any matches left"
);
//Make sure that the tournament isn't too old.
require(
allEvents[_eventId].time + 604800 > block.timestamp,
"This event is too old"
);
//Decrement the allowedMatches
allEvents[_eventId].allowedMatches =
allEvents[_eventId].allowedMatches -
1;
//Record the match.
ICoopData CoopData = ICoopData(CoopDataContract);
CoopData.recordEventMatch(
_winner,
_winnerPoints,
_loser,
_loserPoints,
_referee
);
}
}
| Check that the tournament promoter is the callerCheck that the event has enough matches left.Make sure that the tournament isn't too old.Decrement the allowedMatchesRecord the match. | function recordEventMatch(
uint64 _eventId,
address _winner,
uint8 _winnerPoints,
address _loser,
uint8 _loserPoints,
address _referee
) public {
require(
(msg.sender == allEvents[_eventId].promoter ||
tournamentStaff[msg.sender] == _eventId),
"Only the promoter can record event matches"
);
require(
allEvents[_eventId].allowedMatches > 0,
"This event does not have any matches left"
);
require(
allEvents[_eventId].time + 604800 > block.timestamp,
"This event is too old"
);
allEvents[_eventId].allowedMatches =
allEvents[_eventId].allowedMatches -
1;
ICoopData CoopData = ICoopData(CoopDataContract);
CoopData.recordEventMatch(
_winner,
_winnerPoints,
_loser,
_loserPoints,
_referee
);
}
| 12,782,506 | [
1,
4625,
348,
7953,
560,
30,
2073,
716,
326,
358,
30751,
3012,
20005,
353,
326,
4894,
1564,
716,
326,
871,
711,
7304,
1885,
2002,
18,
6464,
3071,
716,
326,
358,
30751,
5177,
1404,
4885,
1592,
18,
23326,
475,
326,
2935,
6869,
2115,
326,
845,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1409,
1133,
2060,
12,
203,
3639,
2254,
1105,
389,
2575,
548,
16,
203,
3639,
1758,
389,
91,
7872,
16,
203,
3639,
2254,
28,
389,
91,
7872,
5636,
16,
203,
3639,
1758,
389,
383,
550,
16,
203,
3639,
2254,
28,
389,
383,
550,
5636,
16,
203,
3639,
1758,
389,
266,
586,
1340,
203,
565,
262,
1071,
288,
203,
3639,
2583,
12,
203,
5411,
261,
3576,
18,
15330,
422,
777,
3783,
63,
67,
2575,
548,
8009,
17401,
20005,
747,
203,
7734,
358,
30751,
510,
7329,
63,
3576,
18,
15330,
65,
422,
389,
2575,
548,
3631,
203,
5411,
315,
3386,
326,
3012,
20005,
848,
1409,
871,
1885,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
777,
3783,
63,
67,
2575,
548,
8009,
8151,
6869,
405,
374,
16,
203,
5411,
315,
2503,
871,
1552,
486,
1240,
1281,
1885,
2002,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
777,
3783,
63,
67,
2575,
548,
8009,
957,
397,
1666,
3028,
17374,
405,
1203,
18,
5508,
16,
203,
5411,
315,
2503,
871,
353,
4885,
1592,
6,
203,
3639,
11272,
203,
3639,
777,
3783,
63,
67,
2575,
548,
8009,
8151,
6869,
273,
203,
5411,
777,
3783,
63,
67,
2575,
548,
8009,
8151,
6869,
300,
203,
5411,
404,
31,
203,
203,
3639,
467,
4249,
556,
751,
7695,
556,
751,
273,
467,
4249,
556,
751,
12,
4249,
556,
751,
8924,
1769,
203,
3639,
7695,
556,
751,
18,
3366,
1133,
2060,
12,
203,
5411,
389,
91,
7872,
16,
203,
5411,
389,
91,
7872,
5636,
16,
203,
5411,
389,
383,
550,
16,
203,
5411,
389,
383,
550,
5636,
16,
203,
5411,
389,
266,
586,
1340,
203,
3639,
11272,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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: 0x72Ffa36a1f742e27106D36323fafe96F136cdda0
//Contract name: IPCToken
//Balance: 0 Ether
//Verification Date: 1/26/2018
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks
*/
contract SafeMath {
function safeMul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
require(a == 0 || c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
require(a == b * c + a % b);
return c;
}
function safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c>=a && c>=b);
return c;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
uint256 public totalSupply;
function balanceOf(address _owner) public constant returns (uint256 _balance);
function allowance(address _owner, address _spender) public constant returns (uint256 _allowance);
function transfer(address _to, uint256 _value) public returns (bool _succes);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _succes);
function approve(address _spender, uint256 _value) public returns (bool _succes);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
*/
contract StandardToken is ERC20, SafeMath {
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
function balanceOf(address _owner) public constant returns (uint256){
return balanceOf[_owner];
}
function allowance(address _owner, address _spender) public constant returns (uint256){
return allowance[_owner][_spender];
}
/**
* Fix for the ERC20 short address attack
*
* http://vessenes.com/the-erc20-short-address-attack-explained/
*/
modifier onlyPayloadSize(uint size) {
require(!(msg.data.length < size + 4));
_;
}
/*
* Internal transfer with security checks,
* only can be called by this contract
*/
function safeTransfer(address _from, address _to, uint256 _value) internal {
// Prevent transfer to 0x0 address.
require(_to != 0x0);
// Prevent transfer to this contract
require(_to != address(this));
// Check if the sender has enough and subtract from the sender by using safeSub
balanceOf[_from] = safeSub(balanceOf[_from], _value);
// check for overflows and add the same value to the recipient by using safeAdd
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(_from, _to, _value);
}
/**
* @dev Send `_value` tokens to `_to` from your account
* @param _to address The address which you want to transfer to
* @param _value uint the amout of tokens to be transfered
*/
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
safeTransfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public returns (bool) {
uint256 _allowance = allowance[_from][msg.sender];
// Check (_value > _allowance) is already done in safeSub(_allowance, _value)
allowance[_from][msg.sender] = safeSub(_allowance, _value);
safeTransfer(_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) || (allowance[msg.sender][_spender] == 0));
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
}
/**
* Upgrade agent interface inspired by Lunyr.
*
* Upgrade agent transfers tokens to a new contract.
* Upgrade agent itself can be the token contract, or just a middle man contract
* doing the heavy lifting.
*/
contract UpgradeAgent {
uint256 public originalSupply;
/** Interface marker */
function isUpgradeAgent() public pure returns (bool) {
return true;
}
function upgradeFrom(address _from, uint256 _value) public;
}
/**
* A token upgrade mechanism where users can opt-in amount of tokens to the next
* smart contract revision.
*
* First envisioned by Golem and Lunyr projects.
*
*/
contract UpgradeableToken is StandardToken {
/**
* Contract / person who can set the upgrade path.
* This can be the same as team multisig wallet, as what it is with its default value.
*/
address public upgradeMaster;
/** The next contract where the tokens will be migrated. */
UpgradeAgent public upgradeAgent;
/** How many tokens we have upgraded by now. */
uint256 public totalUpgraded;
/**
* Upgrade states.
*
* - NotAllowed: The child contract has not reached a condition where the upgrade can bgun
* - WaitingForAgent: Token allows upgrade, but we don't have a new agent yet
* - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet
* - Upgrading: Upgrade agent is set and the balance holders can upgrade their tokens
*
*/
enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading}
/**
* Somebody has upgraded some of his tokens.
*/
event Upgrade(address indexed _from, address indexed _to, uint256 _value);
/**
* New upgrade agent available.
*/
event UpgradeAgentSet(address agent);
/**
* Do not allow construction without upgrade master set.
*/
function UpgradeableToken(address _upgradeMaster) public {
upgradeMaster = _upgradeMaster;
}
/**
* Allow the token holder to upgrade some of their tokens to a new contract.
*/
function upgrade(uint256 value) public {
UpgradeState state = getUpgradeState();
// bad state not allowed
require(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading);
// Validate input value.
require(value != 0);
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], value);
// Take tokens out from circulation
totalSupply = safeSub(totalSupply, value);
totalUpgraded = safeAdd(totalUpgraded, value);
// Upgrade agent reissues the tokens
upgradeAgent.upgradeFrom(msg.sender, value);
Upgrade(msg.sender, upgradeAgent, value);
}
/**
* Set an upgrade agent that handles
*/
function setUpgradeAgent(address agent) external {
require(canUpgrade());
require(agent != 0x0);
// Only a master can designate the next agent
require(msg.sender == upgradeMaster);
// Upgrade has already begun for an agent
require(getUpgradeState() != UpgradeState.Upgrading);
upgradeAgent = UpgradeAgent(agent);
// Bad interface
require(upgradeAgent.isUpgradeAgent());
// Make sure that token supplies match in source and target
require(upgradeAgent.originalSupply() == totalSupply);
UpgradeAgentSet(upgradeAgent);
}
/**
* Get the state of the token upgrade.
*/
function getUpgradeState() public constant returns (UpgradeState) {
if(!canUpgrade()) return UpgradeState.NotAllowed;
else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent;
else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade;
else return UpgradeState.Upgrading;
}
/**
* Change the upgrade master.
*
* This allows us to set a new owner for the upgrade mechanism.
*/
function setUpgradeMaster(address master) public {
require(master != 0x0);
require(msg.sender == upgradeMaster);
upgradeMaster = master;
}
/**
* Child contract can enable to provide the condition when the upgrade can begun.
*/
function canUpgrade() public pure returns (bool) {
return true;
}
}
/**
* @title Ownable
* @dev Ownable contract with two owner addresses
*/
contract Ownable {
address public ownerOne;
address public ownerTwo;
/**
* @dev The Ownable constructor sets one of the owners of the contract to the sender
* account.
*/
function Ownable() public {
ownerOne = msg.sender;
ownerTwo = msg.sender;
}
/**
* @dev Can only be called by the owners.
*/
modifier onlyOwner {
require(msg.sender == ownerOne || msg.sender == ownerTwo);
_;
}
/**
* @dev Allows the current owners to transfer control of the contract to a new owner.
* @param newOwner The address to transfer ownership to.
* @param replaceOwnerOne Replace 'ownerOne'?
* @param replaceOwnerTwo Replace 'ownerTwo'?
*/
function transferOwnership(address newOwner, bool replaceOwnerOne, bool replaceOwnerTwo) onlyOwner public {
require(newOwner != 0x0);
require(replaceOwnerOne || replaceOwnerTwo);
if(replaceOwnerOne) ownerOne = newOwner;
if(replaceOwnerTwo) ownerTwo = newOwner;
}
}
/**
* @title Pausable
* @dev Allows an emergency stop mechanism.
* See https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/lifecycle/Pausable.sol
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public returns (bool) {
paused = true;
Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public returns (bool) {
paused = false;
Unpause();
return true;
}
}
/**
* @title PausableToken
* @dev StandardToken with pausable transfers
*/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) whenNotPaused public returns (bool) {
super.transfer(_to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) whenNotPaused public returns (bool) {
super.transferFrom(_from, _to, _value);
return true;
}
}
/**
* @title PurchasableToken
* @dev Allows buying IPC token from this contract
*/
contract PurchasableToken is PausableToken {
event PurchaseUnlocked();
event PurchaseLocked();
event UpdatedExchangeRate(uint256 newPrice);
event Purchase(address buyer, uint256 etherAmount, uint256 tokenAmount);
bool public purchasable = false;
// minimum amount of ether you have to spend to buy some tokens
uint256 public minimumEtherAmount;
address public vendorWallet;
uint256 public exchangeRate; // 'exchangeRate' tokens = 1 ether
/** @dev modifier to allow token purchase only when purchase is unlocked and rate > 0 */
modifier isPurchasable {
require(purchasable && exchangeRate > 0 && minimumEtherAmount > 0);
_;
}
/** @dev called by the owner to lock purchase of ipc token */
function lockPurchase() onlyOwner public returns (bool) {
require(purchasable == true);
purchasable = false;
PurchaseLocked();
return true;
}
/** @dev called by the owner to release purchase of ipc token */
function unlockPurchase() onlyOwner public returns (bool) {
require(purchasable == false);
purchasable = true;
PurchaseUnlocked();
return true;
}
/** @dev called by the owner to set a new rate */
function setExchangeRate(uint256 newExchangeRate) onlyOwner public returns (bool) {
require(newExchangeRate > 0);
exchangeRate = newExchangeRate;
UpdatedExchangeRate(newExchangeRate);
return true;
}
/** @dev called by the owner to set the minimum ether amount to buy some token */
function setMinimumEtherAmount(uint256 newMinimumEtherAmount) onlyOwner public returns (bool) {
require(newMinimumEtherAmount > 0);
minimumEtherAmount = newMinimumEtherAmount;
return true;
}
/** @dev called by the owner to set a new vendor */
function setVendorWallet(address newVendorWallet) onlyOwner public returns (bool) {
require(newVendorWallet != 0x0);
vendorWallet = newVendorWallet;
return true;
}
/** @dev buy ipc token by sending at least 'minimumEtherAmount' */
function buyIPC() payable isPurchasable whenNotPaused public returns (uint256) {
require(msg.value >= minimumEtherAmount);
uint256 tokenAmount = safeMul(msg.value, exchangeRate);
tokenAmount = safeDiv(tokenAmount, 1 ether);
require(allowance[vendorWallet][this] >= tokenAmount);
balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender], tokenAmount);
balanceOf[vendorWallet] = safeSub(balanceOf[vendorWallet], tokenAmount);
Purchase(msg.sender, msg.value, tokenAmount);
return tokenAmount;
}
function () payable public {
buyIPC();
}
}
/**
* @title Withdrawable
* @dev Contract allows to withdraw ether and ERC20 token
*/
contract Withdrawable is Ownable {
/** @dev withdraw ERC20 token from this contract */
function withdrawToken(address beneficiary, address _token) onlyOwner public {
ERC20 token = ERC20(_token);
uint256 amount = token.balanceOf(this);
require(amount>0);
token.transfer(beneficiary, amount);
}
/** @dev called by the owner to transfer 'etherAmount' to 'beneficiary' */
function withdrawEther(address beneficiary, uint256 etherAmount) onlyOwner public {
beneficiary.transfer(etherAmount);
}
}
/**
* @title IPCToken
* @dev IPC Token contract
* @author Paysura - <[email protected]>
*/
contract IPCToken is UpgradeableToken, PurchasableToken, Withdrawable {
// Public variables of the token
string public name = "International PayReward Coin";
string public symbol = "IPC";
uint8 public decimals = 12;
// Distributions of the total supply
// 264 mio for crowdsale
uint256 public cr = 264000000 * (10 ** uint256(decimals));
// 110 mio reserved for community / reward program
uint256 public rew = 110000000 * (10 ** uint256(decimals));
// 66 mio for advisors and partners
uint256 public dev = 66000000 * (10 ** uint256(decimals));
// total supply of 440 mio
uint256 public totalSupply = cr + dev + rew;
event UpdatedTokenInformation(string newName, string newSymbol);
/**
* Constructor of ipc token
*
* @param addressOfCrBen beneficiary of crowdsale
* @param addressOfRew reserve for community / reward program
* @param addressOfDev reserve remaining amount of ipc for development, partners and advisors
*/
function IPCToken (
address addressOfCrBen,
address addressOfRew,
address addressOfDev
) public UpgradeableToken(msg.sender) {
// Assign the initial tokens to the addresses
balanceOf[addressOfCrBen] = cr;
balanceOf[addressOfRew] = rew;
balanceOf[addressOfDev] = dev;
}
/**
* Owner can update token information
*
* @param _name new token name
* @param _symbol new token symbol
*/
function setTokenInformation(string _name, string _symbol) onlyOwner public {
name = _name;
symbol = _symbol;
UpdatedTokenInformation(name, symbol);
}
}
| * @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./ 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 | function approve(address _spender, uint256 _value) public returns (bool) {
require((_value == 0) || (allowance[msg.sender][_spender] == 0));
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
| 6,414,464 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
5206,
432,
685,
537,
326,
2275,
1758,
358,
17571,
326,
1269,
3844,
434,
2430,
603,
12433,
6186,
434,
1234,
18,
15330,
18,
632,
891,
389,
87,
1302,
264,
1021,
1758,
1492,
903,
17571,
326,
284,
19156,
18,
632,
891,
389,
1132,
1021,
3844,
434,
2430,
358,
506,
26515,
18,
19,
2974,
2549,
326,
6617,
537,
3844,
1846,
1122,
1240,
358,
5459,
326,
6138,
68,
1699,
1359,
358,
3634,
635,
4440,
1375,
12908,
537,
24899,
87,
1302,
264,
16,
374,
22025,
309,
518,
353,
486,
1818,
374,
358,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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
6617,
537,
12,
2867,
389,
87,
1302,
264,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12443,
67,
1132,
422,
374,
13,
747,
261,
5965,
1359,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
65,
422,
374,
10019,
203,
3639,
1699,
1359,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
65,
273,
389,
1132,
31,
203,
3639,
1716,
685,
1125,
12,
3576,
18,
15330,
16,
389,
87,
1302,
264,
16,
389,
1132,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 2017-2020, bZeroX, LLC <https://bzx.network/>. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
import "./StakingState.sol";
import "./StakingConstants.sol";
import "../interfaces/IVestingToken.sol";
import "../../interfaces/IBZx.sol";
import "../../interfaces/IPriceFeeds.sol";
import "../utils/MathUtil.sol";
import "../farm/interfaces/IMasterChefSushi.sol";
import "../../interfaces/IStaking.sol";
contract StakingV1_1 is StakingState, StakingConstants {
using MathUtil for uint256;
modifier onlyEOA() {
require(msg.sender == tx.origin, "unauthorized");
_;
}
modifier checkPause() {
require(!isPaused, "paused");
_;
}
function getCurrentFeeTokens()
external
view
returns (address[] memory)
{
return currentFeeTokens;
}
// View function to see pending sushi rewards on frontend.
function pendingSushiRewards(address _user)
public
view
returns (uint256)
{
uint256 pendingSushi = IMasterChefSushi(SUSHI_MASTERCHEF)
.pendingSushi(BZRX_ETH_SUSHI_MASTERCHEF_PID, address(this));
return _pendingAltRewards(
SUSHI,
_user,
balanceOfByAsset(LPToken, _user),
pendingSushi.mul(1e12).div(_totalSupplyPerToken[LPToken])
);
}
function pendingAltRewards(address token, address _user)
external
view
returns (uint256)
{
uint256 userSupply = balanceOfByAsset(token, _user);
return _pendingAltRewards(token, _user, userSupply, 0);
}
function _pendingAltRewards(address token, address _user, uint256 userSupply, uint256 extraRewardsPerShare)
internal
view
returns (uint256)
{
uint256 _altRewardsPerShare = altRewardsPerShare[token].add(extraRewardsPerShare);
if (_altRewardsPerShare == 0)
return 0;
if (userSupply == 0)
return 0;
IStaking.AltRewardsUserInfo memory altRewardsUserInfo = userAltRewardsPerShare[_user][token];
return altRewardsUserInfo.pendingRewards.add(
(_altRewardsPerShare.sub(altRewardsUserInfo.rewardsPerShare)).mul(userSupply).div(1e12)
);
}
// Withdraw all from sushi masterchef
function exitSushi()
external
onlyOwner
{
IMasterChefSushi chef = IMasterChefSushi(SUSHI_MASTERCHEF);
uint256 balance = chef.userInfo(BZRX_ETH_SUSHI_MASTERCHEF_PID, address(this)).amount;
chef.withdraw(
BZRX_ETH_SUSHI_MASTERCHEF_PID,
balance
);
}
function _depositToSushiMasterchef(uint256 amount)
internal
{
uint256 sushiBalanceBefore = IERC20(SUSHI).balanceOf(address(this));
IMasterChefSushi(SUSHI_MASTERCHEF).deposit(
BZRX_ETH_SUSHI_MASTERCHEF_PID,
amount
);
uint256 sushiRewards = IERC20(SUSHI).balanceOf(address(this)) - sushiBalanceBefore;
if (sushiRewards != 0) {
_addAltRewards(SUSHI, sushiRewards);
}
}
function _withdrawFromSushiMasterchef(uint256 amount)
internal
{
uint256 sushiBalanceBefore = IERC20(SUSHI).balanceOf(address(this));
IMasterChefSushi(SUSHI_MASTERCHEF).withdraw(
BZRX_ETH_SUSHI_MASTERCHEF_PID,
amount
);
uint256 sushiRewards = IERC20(SUSHI).balanceOf(address(this)) - sushiBalanceBefore;
if (sushiRewards != 0) {
_addAltRewards(SUSHI, sushiRewards);
}
}
function stake(
address[] memory tokens,
uint256[] memory values
)
public
checkPause
updateRewards(msg.sender)
{
require(tokens.length == values.length, "count mismatch");
/*address currentDelegate = delegate[msg.sender];
if (currentDelegate == address(0)) {
currentDelegate = msg.sender;
delegate[msg.sender] = currentDelegate;
_delegatedSet.addAddress(msg.sender);
}*/
address token;
uint256 stakeAmount;
for (uint256 i = 0; i < tokens.length; i++) {
token = tokens[i];
require(token == BZRX || token == vBZRX || token == iBZRX || token == LPToken, "invalid token");
stakeAmount = values[i];
if (stakeAmount == 0) {
continue;
}
uint256 pendingBefore = (token == LPToken) ? pendingSushiRewards(msg.sender) : 0;
_balancesPerToken[token][msg.sender] = _balancesPerToken[token][msg.sender].add(stakeAmount);
_totalSupplyPerToken[token] = _totalSupplyPerToken[token].add(stakeAmount);
/*delegatedPerToken[currentDelegate][token] = delegatedPerToken[currentDelegate][token]
.add(stakeAmount);*/
IERC20(token).safeTransferFrom(msg.sender, address(this), stakeAmount);
// Deposit to sushi masterchef
if (token == LPToken) {
_depositToSushiMasterchef(
IERC20(LPToken).balanceOf(address(this))
);
userAltRewardsPerShare[msg.sender][SUSHI] = IStaking.AltRewardsUserInfo({
rewardsPerShare: altRewardsPerShare[SUSHI],
pendingRewards: pendingBefore
}
);
}
emit Stake(
msg.sender,
token,
msg.sender, //currentDelegate,
stakeAmount
);
}
}
function unstake(
address[] memory tokens,
uint256[] memory values
)
public
checkPause
updateRewards(msg.sender)
{
require(tokens.length == values.length, "count mismatch");
//address currentDelegate = delegate[msg.sender];
address token;
uint256 unstakeAmount;
uint256 stakedAmount;
for (uint256 i = 0; i < tokens.length; i++) {
token = tokens[i];
require(token == BZRX || token == vBZRX || token == iBZRX || token == LPToken || token == LPTokenOld, "invalid token");
unstakeAmount = values[i];
stakedAmount = _balancesPerToken[token][msg.sender];
if (unstakeAmount == 0 || stakedAmount == 0) {
continue;
}
if (unstakeAmount > stakedAmount) {
unstakeAmount = stakedAmount;
}
uint256 pendingBefore = (token == LPToken) ? pendingSushiRewards(msg.sender) : 0;
_balancesPerToken[token][msg.sender] = stakedAmount - unstakeAmount; // will not overflow
_totalSupplyPerToken[token] = _totalSupplyPerToken[token] - unstakeAmount; // will not overflow
/*delegatedPerToken[currentDelegate][token] = delegatedPerToken[currentDelegate][token]
.sub(unstakeAmount);*/
if (token == BZRX && IERC20(BZRX).balanceOf(address(this)) < unstakeAmount) {
// settle vested BZRX only if needed
IVestingToken(vBZRX).claim();
}
// Withdraw to sushi masterchef
if (token == LPToken) {
_withdrawFromSushiMasterchef(unstakeAmount);
userAltRewardsPerShare[msg.sender][SUSHI] = IStaking.AltRewardsUserInfo({
rewardsPerShare: altRewardsPerShare[SUSHI],
pendingRewards: pendingBefore
}
);
}
IERC20(token).safeTransfer(msg.sender, unstakeAmount);
emit Unstake(
msg.sender,
token,
msg.sender, //currentDelegate,
unstakeAmount
);
}
}
/*function changeDelegate(
address delegateToSet)
external
checkPause
{
if (delegateToSet == ZERO_ADDRESS) {
delegateToSet = msg.sender;
}
address currentDelegate = delegate[msg.sender];
if (delegateToSet != currentDelegate) {
if (currentDelegate != ZERO_ADDRESS) {
uint256 balance = _balancesPerToken[BZRX][msg.sender];
if (balance != 0) {
delegatedPerToken[currentDelegate][BZRX] = delegatedPerToken[currentDelegate][BZRX]
.sub(balance);
delegatedPerToken[delegateToSet][BZRX] = delegatedPerToken[delegateToSet][BZRX]
.add(balance);
}
balance = _balancesPerToken[vBZRX][msg.sender];
if (balance != 0) {
delegatedPerToken[currentDelegate][vBZRX] = delegatedPerToken[currentDelegate][vBZRX]
.sub(balance);
delegatedPerToken[delegateToSet][vBZRX] = delegatedPerToken[delegateToSet][vBZRX]
.add(balance);
}
balance = _balancesPerToken[iBZRX][msg.sender];
if (balance != 0) {
delegatedPerToken[currentDelegate][iBZRX] = delegatedPerToken[currentDelegate][iBZRX]
.sub(balance);
delegatedPerToken[delegateToSet][iBZRX] = delegatedPerToken[delegateToSet][iBZRX]
.add(balance);
}
balance = _balancesPerToken[LPToken][msg.sender];
if (balance != 0) {
delegatedPerToken[currentDelegate][LPToken] = delegatedPerToken[currentDelegate][LPToken]
.sub(balance);
delegatedPerToken[delegateToSet][LPToken] = delegatedPerToken[delegateToSet][LPToken]
.add(balance);
}
}
delegate[msg.sender] = delegateToSet;
_delegatedSet.addAddress(delegateToSet);
emit ChangeDelegate(
msg.sender,
currentDelegate,
delegateToSet
);
currentDelegate = delegateToSet;
}
}*/
function claim(
bool restake)
external
checkPause
updateRewards(msg.sender)
returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 sushiRewardsEarned)
{
return _claim(restake);
}
function claimBzrx()
external
checkPause
updateRewards(msg.sender)
returns (uint256 bzrxRewardsEarned)
{
bzrxRewardsEarned = _claimBzrx(false);
emit Claim(
msg.sender,
bzrxRewardsEarned,
0
);
}
function claim3Crv()
external
checkPause
updateRewards(msg.sender)
returns (uint256 stableCoinRewardsEarned)
{
stableCoinRewardsEarned = _claim3Crv();
emit Claim(
msg.sender,
0,
stableCoinRewardsEarned
);
}
function claimSushi()
external
checkPause
returns (uint256 sushiRewardsEarned)
{
sushiRewardsEarned = _claimSushi();
if(sushiRewardsEarned != 0){
emit ClaimAltRewards(msg.sender, SUSHI, sushiRewardsEarned);
}
}
function _claim(
bool restake)
internal
returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 sushiRewardsEarned)
{
bzrxRewardsEarned = _claimBzrx(restake);
stableCoinRewardsEarned = _claim3Crv();
sushiRewardsEarned = _claimSushi();
emit Claim(
msg.sender,
bzrxRewardsEarned,
stableCoinRewardsEarned
);
if(sushiRewardsEarned != 0){
emit ClaimAltRewards(msg.sender, SUSHI, sushiRewardsEarned);
}
}
function _claimBzrx(
bool restake)
internal
returns (uint256 bzrxRewardsEarned)
{
bzrxRewardsEarned = bzrxRewards[msg.sender];
if (bzrxRewardsEarned != 0) {
bzrxRewards[msg.sender] = 0;
if (restake) {
_restakeBZRX(
msg.sender,
bzrxRewardsEarned
);
} else {
if (IERC20(BZRX).balanceOf(address(this)) < bzrxRewardsEarned) {
// settle vested BZRX only if needed
IVestingToken(vBZRX).claim();
}
IERC20(BZRX).transfer(msg.sender, bzrxRewardsEarned);
}
}
}
function _claim3Crv()
internal
returns (uint256 stableCoinRewardsEarned)
{
stableCoinRewardsEarned = stableCoinRewards[msg.sender];
if (stableCoinRewardsEarned != 0) {
stableCoinRewards[msg.sender] = 0;
curve3Crv.transfer(msg.sender, stableCoinRewardsEarned);
}
}
function _claimSushi()
internal
returns (uint256)
{
address _user = msg.sender;
uint256 lptUserSupply = balanceOfByAsset(LPToken, _user);
if(lptUserSupply == 0){
return 0;
}
_depositToSushiMasterchef(
IERC20(LPToken).balanceOf(address(this))
);
uint256 pendingSushi = _pendingAltRewards(SUSHI, _user, lptUserSupply, 0);
userAltRewardsPerShare[_user][SUSHI] = IStaking.AltRewardsUserInfo({
rewardsPerShare: altRewardsPerShare[SUSHI],
pendingRewards: 0
}
);
if (pendingSushi != 0) {
IERC20(SUSHI).safeTransfer(_user, pendingSushi);
}
return pendingSushi;
}
function _restakeBZRX(
address account,
uint256 amount)
internal
{
//address currentDelegate = delegate[account];
_balancesPerToken[BZRX][account] = _balancesPerToken[BZRX][account]
.add(amount);
_totalSupplyPerToken[BZRX] = _totalSupplyPerToken[BZRX]
.add(amount);
/*delegatedPerToken[currentDelegate][BZRX] = delegatedPerToken[currentDelegate][BZRX]
.add(amount);*/
emit Stake(
account,
BZRX,
account, //currentDelegate,
amount
);
}
function exit()
public
// unstake() does a checkPause
{
address[] memory tokens = new address[](4);
uint256[] memory values = new uint256[](4);
tokens[0] = iBZRX;
tokens[1] = LPToken;
tokens[2] = vBZRX;
tokens[3] = BZRX;
values[0] = uint256(-1);
values[1] = uint256(-1);
values[2] = uint256(-1);
values[3] = uint256(-1);
unstake(tokens, values); // calls updateRewards
_claim(false);
}
/*function getDelegateVotes(
uint256 start,
uint256 count)
external
view
returns (DelegatedTokens[] memory delegateArr)
{
uint256 end = start.add(count).min256(_delegatedSet.length());
if (start >= end) {
return delegateArr;
}
count = end-start;
uint256 idx = count;
address user;
delegateArr = new DelegatedTokens[](idx);
for (uint256 i = --end; i >= start; i--) {
user = _delegatedSet.getAddress(i);
delegateArr[count-(idx--)] = DelegatedTokens({
user: user,
BZRX: delegatedPerToken[user][BZRX],
vBZRX: delegatedPerToken[user][vBZRX],
iBZRX: delegatedPerToken[user][iBZRX],
LPToken: delegatedPerToken[user][LPToken],
totalVotes: delegateBalanceOf(user)
});
if (i == 0) {
break;
}
}
if (idx != 0) {
count -= idx;
assembly {
mstore(delegateArr, count)
}
}
}*/
modifier updateRewards(address account) {
uint256 _bzrxPerTokenStored = bzrxPerTokenStored;
uint256 _stableCoinPerTokenStored = stableCoinPerTokenStored;
(uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting) = _earned(
account,
_bzrxPerTokenStored,
_stableCoinPerTokenStored
);
bzrxRewardsPerTokenPaid[account] = _bzrxPerTokenStored;
stableCoinRewardsPerTokenPaid[account] = _stableCoinPerTokenStored;
// vesting amounts get updated before sync
bzrxVesting[account] = bzrxRewardsVesting;
stableCoinVesting[account] = stableCoinRewardsVesting;
(bzrxRewards[account], stableCoinRewards[account]) = _syncVesting(
account,
bzrxRewardsEarned,
stableCoinRewardsEarned,
bzrxRewardsVesting,
stableCoinRewardsVesting
);
vestingLastSync[account] = block.timestamp;
_;
}
function earned(
address account)
external
view
returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting, uint256 sushiRewardsEarned)
{
(bzrxRewardsEarned, stableCoinRewardsEarned, bzrxRewardsVesting, stableCoinRewardsVesting) = _earned(
account,
bzrxPerTokenStored,
stableCoinPerTokenStored
);
(bzrxRewardsEarned, stableCoinRewardsEarned) = _syncVesting(
account,
bzrxRewardsEarned,
stableCoinRewardsEarned,
bzrxRewardsVesting,
stableCoinRewardsVesting
);
// discount vesting amounts for vesting time
uint256 multiplier = vestedBalanceForAmount(
1e36,
0,
block.timestamp
);
bzrxRewardsVesting = bzrxRewardsVesting
.sub(bzrxRewardsVesting
.mul(multiplier)
.div(1e36)
);
stableCoinRewardsVesting = stableCoinRewardsVesting
.sub(stableCoinRewardsVesting
.mul(multiplier)
.div(1e36)
);
uint256 pendingSushi = IMasterChefSushi(SUSHI_MASTERCHEF)
.pendingSushi(BZRX_ETH_SUSHI_MASTERCHEF_PID, address(this));
sushiRewardsEarned = _pendingAltRewards(
SUSHI,
account,
balanceOfByAsset(LPToken, account),
pendingSushi.mul(1e12).div(_totalSupplyPerToken[LPToken])
);
}
function _earned(
address account,
uint256 _bzrxPerToken,
uint256 _stableCoinPerToken)
internal
view
returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting)
{
uint256 bzrxPerTokenUnpaid = _bzrxPerToken.sub(bzrxRewardsPerTokenPaid[account]);
uint256 stableCoinPerTokenUnpaid = _stableCoinPerToken.sub(stableCoinRewardsPerTokenPaid[account]);
bzrxRewardsEarned = bzrxRewards[account];
stableCoinRewardsEarned = stableCoinRewards[account];
bzrxRewardsVesting = bzrxVesting[account];
stableCoinRewardsVesting = stableCoinVesting[account];
if (bzrxPerTokenUnpaid != 0 || stableCoinPerTokenUnpaid != 0) {
uint256 value;
uint256 multiplier;
uint256 lastSync;
(uint256 vestedBalance, uint256 vestingBalance) = balanceOfStored(account);
value = vestedBalance
.mul(bzrxPerTokenUnpaid);
value /= 1e36;
bzrxRewardsEarned = value
.add(bzrxRewardsEarned);
value = vestedBalance
.mul(stableCoinPerTokenUnpaid);
value /= 1e36;
stableCoinRewardsEarned = value
.add(stableCoinRewardsEarned);
if (vestingBalance != 0 && bzrxPerTokenUnpaid != 0) {
// add new vesting amount for BZRX
value = vestingBalance
.mul(bzrxPerTokenUnpaid);
value /= 1e36;
bzrxRewardsVesting = bzrxRewardsVesting
.add(value);
// true up earned amount to vBZRX vesting schedule
lastSync = vestingLastSync[account];
multiplier = vestedBalanceForAmount(
1e36,
0,
lastSync
);
value = value
.mul(multiplier);
value /= 1e36;
bzrxRewardsEarned = bzrxRewardsEarned
.add(value);
}
if (vestingBalance != 0 && stableCoinPerTokenUnpaid != 0) {
// add new vesting amount for 3crv
value = vestingBalance
.mul(stableCoinPerTokenUnpaid);
value /= 1e36;
stableCoinRewardsVesting = stableCoinRewardsVesting
.add(value);
// true up earned amount to vBZRX vesting schedule
if (lastSync == 0) {
lastSync = vestingLastSync[account];
multiplier = vestedBalanceForAmount(
1e36,
0,
lastSync
);
}
value = value
.mul(multiplier);
value /= 1e36;
stableCoinRewardsEarned = stableCoinRewardsEarned
.add(value);
}
}
}
function _syncVesting(
address account,
uint256 bzrxRewardsEarned,
uint256 stableCoinRewardsEarned,
uint256 bzrxRewardsVesting,
uint256 stableCoinRewardsVesting)
internal
view
returns (uint256, uint256)
{
uint256 lastVestingSync = vestingLastSync[account];
if (lastVestingSync != block.timestamp) {
uint256 rewardsVested;
uint256 multiplier = vestedBalanceForAmount(
1e36,
lastVestingSync,
block.timestamp
);
if (bzrxRewardsVesting != 0) {
rewardsVested = bzrxRewardsVesting
.mul(multiplier)
.div(1e36);
bzrxRewardsEarned += rewardsVested;
}
if (stableCoinRewardsVesting != 0) {
rewardsVested = stableCoinRewardsVesting
.mul(multiplier)
.div(1e36);
stableCoinRewardsEarned += rewardsVested;
}
uint256 vBZRXBalance = _balancesPerToken[vBZRX][account];
if (vBZRXBalance != 0) {
// add vested BZRX to rewards balance
rewardsVested = vBZRXBalance
.mul(multiplier)
.div(1e36);
bzrxRewardsEarned += rewardsVested;
}
}
return (bzrxRewardsEarned, stableCoinRewardsEarned);
}
// note: anyone can contribute rewards to the contract
function addDirectRewards(
address[] calldata accounts,
uint256[] calldata bzrxAmounts,
uint256[] calldata stableCoinAmounts)
external
checkPause
returns (uint256 bzrxTotal, uint256 stableCoinTotal)
{
require(accounts.length == bzrxAmounts.length && accounts.length == stableCoinAmounts.length, "count mismatch");
for (uint256 i = 0; i < accounts.length; i++) {
bzrxRewards[accounts[i]] = bzrxRewards[accounts[i]].add(bzrxAmounts[i]);
bzrxTotal = bzrxTotal.add(bzrxAmounts[i]);
stableCoinRewards[accounts[i]] = stableCoinRewards[accounts[i]].add(stableCoinAmounts[i]);
stableCoinTotal = stableCoinTotal.add(stableCoinAmounts[i]);
}
if (bzrxTotal != 0) {
IERC20(BZRX).transferFrom(msg.sender, address(this), bzrxTotal);
}
if (stableCoinTotal != 0) {
curve3Crv.transferFrom(msg.sender, address(this), stableCoinTotal);
}
}
// note: anyone can contribute rewards to the contract
function addRewards(
uint256 newBZRX,
uint256 newStableCoin)
external
checkPause
{
if (newBZRX != 0 || newStableCoin != 0) {
_addRewards(newBZRX, newStableCoin);
if (newBZRX != 0) {
IERC20(BZRX).transferFrom(msg.sender, address(this), newBZRX);
}
if (newStableCoin != 0) {
curve3Crv.transferFrom(msg.sender, address(this), newStableCoin);
}
}
}
function _addRewards(
uint256 newBZRX,
uint256 newStableCoin)
internal
{
(vBZRXWeightStored, iBZRXWeightStored, LPTokenWeightStored) = getVariableWeights();
uint256 totalTokens = totalSupplyStored();
require(totalTokens != 0, "nothing staked");
bzrxPerTokenStored = newBZRX
.mul(1e36)
.div(totalTokens)
.add(bzrxPerTokenStored);
stableCoinPerTokenStored = newStableCoin
.mul(1e36)
.div(totalTokens)
.add(stableCoinPerTokenStored);
lastRewardsAddTime = block.timestamp;
emit AddRewards(
msg.sender,
newBZRX,
newStableCoin
);
}
function addAltRewards(address token, uint256 amount) public {
if (amount != 0) {
_addAltRewards(token, amount);
IERC20(token).transferFrom(msg.sender, address(this), amount);
}
}
function _addAltRewards(address token, uint256 amount) internal {
address poolAddress = token == SUSHI ? LPToken : token;
uint256 totalSupply = _totalSupplyPerToken[poolAddress];
require(totalSupply != 0, "no deposits");
altRewardsPerShare[token] = altRewardsPerShare[token]
.add(amount.mul(1e12).div(totalSupply));
emit AddAltRewards(msg.sender, token, amount);
}
function getVariableWeights()
public
view
returns (uint256 vBZRXWeight, uint256 iBZRXWeight, uint256 LPTokenWeight)
{
uint256 totalVested = vestedBalanceForAmount(
_startingVBZRXBalance,
0,
block.timestamp
);
vBZRXWeight = SafeMath.mul(_startingVBZRXBalance - totalVested, 1e18) // overflow not possible
.div(_startingVBZRXBalance);
iBZRXWeight = _calcIBZRXWeight();
uint256 lpTokenSupply = _totalSupplyPerToken[LPToken];
if (lpTokenSupply != 0) {
// staked LP tokens are assumed to represent the total unstaked supply (circulated supply - staked BZRX)
uint256 normalizedLPTokenSupply = initialCirculatingSupply +
totalVested -
_totalSupplyPerToken[BZRX];
LPTokenWeight = normalizedLPTokenSupply
.mul(1e18)
.div(lpTokenSupply);
}
}
function _calcIBZRXWeight()
internal
view
returns (uint256)
{
return IERC20(BZRX).balanceOf(iBZRX)
.mul(1e50)
.div(IERC20(iBZRX).totalSupply());
}
function balanceOfByAsset(
address token,
address account)
public
view
returns (uint256 balance)
{
balance = _balancesPerToken[token][account];
}
function balanceOfByAssets(
address account)
external
view
returns (
uint256 bzrxBalance,
uint256 iBZRXBalance,
uint256 vBZRXBalance,
uint256 LPTokenBalance,
uint256 LPTokenBalanceOld
)
{
return (
balanceOfByAsset(BZRX, account),
balanceOfByAsset(iBZRX, account),
balanceOfByAsset(vBZRX, account),
balanceOfByAsset(LPToken, account),
balanceOfByAsset(LPTokenOld, account)
);
}
function balanceOfStored(
address account)
public
view
returns (uint256 vestedBalance, uint256 vestingBalance)
{
uint256 balance = _balancesPerToken[vBZRX][account];
if (balance != 0) {
vestingBalance = _balancesPerToken[vBZRX][account]
.mul(vBZRXWeightStored)
.div(1e18);
}
vestedBalance = _balancesPerToken[BZRX][account];
balance = _balancesPerToken[iBZRX][account];
if (balance != 0) {
vestedBalance = balance
.mul(iBZRXWeightStored)
.div(1e50)
.add(vestedBalance);
}
balance = _balancesPerToken[LPToken][account];
if (balance != 0) {
vestedBalance = balance
.mul(LPTokenWeightStored)
.div(1e18)
.add(vestedBalance);
}
}
function totalSupplyByAsset(
address token)
external
view
returns (uint256)
{
return _totalSupplyPerToken[token];
}
function totalSupplyStored()
public
view
returns (uint256 supply)
{
supply = _totalSupplyPerToken[vBZRX]
.mul(vBZRXWeightStored)
.div(1e18);
supply = _totalSupplyPerToken[BZRX]
.add(supply);
supply = _totalSupplyPerToken[iBZRX]
.mul(iBZRXWeightStored)
.div(1e50)
.add(supply);
supply = _totalSupplyPerToken[LPToken]
.mul(LPTokenWeightStored)
.div(1e18)
.add(supply);
}
function vestedBalanceForAmount(
uint256 tokenBalance,
uint256 lastUpdate,
uint256 vestingEndTime)
public
view
returns (uint256 vested)
{
vestingEndTime = vestingEndTime.min256(block.timestamp);
if (vestingEndTime > lastUpdate) {
if (vestingEndTime <= vestingCliffTimestamp ||
lastUpdate >= vestingEndTimestamp) {
// time cannot be before vesting starts
// OR all vested token has already been claimed
return 0;
}
if (lastUpdate < vestingCliffTimestamp) {
// vesting starts at the cliff timestamp
lastUpdate = vestingCliffTimestamp;
}
if (vestingEndTime > vestingEndTimestamp) {
// vesting ends at the end timestamp
vestingEndTime = vestingEndTimestamp;
}
uint256 timeSinceClaim = vestingEndTime.sub(lastUpdate);
vested = tokenBalance.mul(timeSinceClaim) / vestingDurationAfterCliff; // will never divide by 0
}
}
// Governance Logic //
function votingBalanceOf(
address account,
uint256 proposalId)
public
view
returns (uint256 totalVotes)
{
return _votingBalanceOf(account, _proposalState[proposalId]);
}
function votingBalanceOfNow(
address account)
public
view
returns (uint256 totalVotes)
{
return _votingBalanceOf(account, _getProposalState());
}
function _setProposalVals(
address account,
uint256 proposalId)
public
returns (uint256)
{
require(msg.sender == governor, "unauthorized");
require(_proposalState[proposalId].proposalTime == 0, "proposal exists");
ProposalState memory newProposal = _getProposalState();
_proposalState[proposalId] = newProposal;
return _votingBalanceOf(account, newProposal);
}
function _getProposalState()
internal
view
returns (ProposalState memory)
{
return ProposalState({
proposalTime: block.timestamp - 1,
iBZRXWeight: _calcIBZRXWeight(),
lpBZRXBalance: IERC20(BZRX).balanceOf(LPToken),
lpTotalSupply: IERC20(LPToken).totalSupply()
});
}
function _votingBalanceOf(
address account,
ProposalState memory proposal)
internal
view
returns (uint256 totalVotes)
{
uint256 _vestingLastSync = vestingLastSync[account];
if (proposal.proposalTime == 0 || _vestingLastSync > proposal.proposalTime - 1) {
return 0;
}
uint256 _vBZRXBalance = _balancesPerToken[vBZRX][account];
if (_vBZRXBalance != 0) {
// staked vBZRX is prorated based on total vested
totalVotes = _vBZRXBalance
.mul(_startingVBZRXBalance -
vestedBalanceForAmount( // overflow not possible
_startingVBZRXBalance,
0,
proposal.proposalTime
)
).div(_startingVBZRXBalance);
// user is attributed a staked balance of vested BZRX, from their last update to the present
totalVotes = vestedBalanceForAmount(
_vBZRXBalance,
_vestingLastSync,
proposal.proposalTime
).add(totalVotes);
}
totalVotes = _balancesPerToken[BZRX][account]
.add(bzrxRewards[account]) // unclaimed BZRX rewards count as votes
.add(totalVotes);
totalVotes = _balancesPerToken[iBZRX][account]
.mul(proposal.iBZRXWeight)
.div(1e50)
.add(totalVotes);
// LPToken votes are measured based on amount of underlying BZRX staked
totalVotes = proposal.lpBZRXBalance
.mul(_balancesPerToken[LPToken][account])
.div(proposal.lpTotalSupply)
.add(totalVotes);
}
// OnlyOwner functions
function togglePause(
bool _isPaused)
external
onlyOwner
{
isPaused = _isPaused;
}
function setFundsWallet(
address _fundsWallet)
external
onlyOwner
{
fundsWallet = _fundsWallet;
}
function setGovernor(
address _governor)
external
onlyOwner
{
governor = _governor;
}
function setFeeTokens(
address[] calldata tokens)
external
onlyOwner
{
currentFeeTokens = tokens;
}
function setRewardPercent(
uint256 _rewardPercent)
external
onlyOwner
{
require(_rewardPercent <= 1e20, "value too high");
rewardPercent = _rewardPercent;
}
function setMaxUniswapDisagreement(
uint256 _maxUniswapDisagreement)
external
onlyOwner
{
require(_maxUniswapDisagreement != 0, "invalid param");
maxUniswapDisagreement = _maxUniswapDisagreement;
}
function setMaxCurveDisagreement(
uint256 _maxCurveDisagreement)
external
onlyOwner
{
require(_maxCurveDisagreement != 0, "invalid param");
maxCurveDisagreement = _maxCurveDisagreement;
}
function setCallerRewardDivisor(
uint256 _callerRewardDivisor)
external
onlyOwner
{
require(_callerRewardDivisor != 0, "invalid param");
callerRewardDivisor = _callerRewardDivisor;
}
function setInitialAltRewardsPerShare()
external
onlyOwner
{
uint256 index = altRewardsRounds[SUSHI].length;
if(index == 0) {
return;
}
altRewardsPerShare[SUSHI] = altRewardsRounds[SUSHI][index - 1];
}
function setBalApproval(
address _spender,
uint256 _value)
external
onlyOwner
{
IERC20(0xba100000625a3754423978a60c9317c58a424e3D).approve(_spender, _value);
}
/* commenting to save on deployment gas next time
function setApprovals()
external
onlyOwner
{
IERC20(0xa30911e072A0C88D55B5D0A0984B66b0D04569d0).approve(0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd, uint256(-1));
}
*/
}
| delegatedPerToken[currentDelegate][token] = delegatedPerToken[currentDelegate][token] | .add(stakeAmount);*/
| 5,429,707 | [
1,
4625,
348,
7953,
560,
30,
30055,
2173,
1345,
63,
2972,
9586,
6362,
2316,
65,
273,
30055,
2173,
1345,
63,
2972,
9586,
6362,
2316,
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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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
7734,
263,
1289,
12,
334,
911,
6275,
1769,
5549,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 "zeppelin-solidity/contracts/ownership/Ownable.sol";
import "zeppelin-solidity/contracts/math/SafeMath.sol";
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
/// @title The external contract that is responsible for generating metadata for the kitties,
/// it has one function that will return the data as bytes.
contract ERC721Metadata {
/// @dev Given a token Id, returns a byte array that is supposed to be converted into string.
function getMetadata(uint256 _tokenId, string) public pure returns (bytes32[4] buffer, uint256 count) {
if (_tokenId == 1) {
buffer[0] = "Hello World! :D";
count = 15;
} else if (_tokenId == 2) {
buffer[0] = "I would definitely choose a medi";
buffer[1] = "um length string.";
count = 49;
} else if (_tokenId == 3) {
buffer[0] = "Lorem ipsum dolor sit amet, mi e";
buffer[1] = "st accumsan dapibus augue lorem,";
buffer[2] = " tristique vestibulum id, libero";
buffer[3] = " suscipit varius sapien aliquam.";
count = 128;
}
}
}
/// @title KittyCoinClub
/// @author Nathan Glover
/// @notice KittyCoinClub contract is the main input to the this DApp, it controls the supply of KittyCoins in circulation and other utilities perdinant to the contract a a whole
contract KittyCoinClub is Ownable, ERC721 {
/* Libraries */
using SafeMath for uint256;
/* Contract owner */
address owner;
/*
_______ _ _____ _ _ _
|__ __| | | | __ \ | | (_) |
| | ___ | | _____ _ __ | | | | ___| |_ __ _ _| |___
| |/ _ \| |/ / _ \ '_ \ | | | |/ _ \ __/ _` | | / __|
| | (_) | < __/ | | | | |__| | __/ || (_| | | \__ \
|_|\___/|_|\_\___|_| |_| |_____/ \___|\__\__,_|_|_|___/
*/
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "KittyCoinClub";
string public constant symbol = "KCC";
// uint8 public decimals = 0; // Amount of decimals for display purposes
// uint256 public totalSupply = 25600;
// uint16 public remainingKittyCoins = 25600 - 256; // there will only ever be 25,000 cats
// uint16 public remainingFounderCoins = 256; // there can only be a maximum of 256 founder coins
// The contract that will return kitty metadata
ERC721Metadata public erc721Metadata;
bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256("supportsInterface(bytes4)"));
bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256("name()")) ^
bytes4(keccak256("symbol()")) ^
bytes4(keccak256("totalSupply()")) ^
bytes4(keccak256("balanceOf(address)")) ^
bytes4(keccak256("ownerOf(uint256)")) ^
bytes4(keccak256("approve(address,uint256)")) ^
bytes4(keccak256("transfer(address,uint256)")) ^
bytes4(keccak256("transferFrom(address,address,uint256)")) ^
bytes4(keccak256("tokensOfOwner(address)")) ^
bytes4(keccak256("tokenMetadata(uint256,string)"));
/*
_____ _ _
/ ____| | | |
| (___ | |_ _ __ _ _ ___| |_ ___
\___ \| __| '__| | | |/ __| __/ __|
____) | |_| | | |_| | (__| |_\__ \
|_____/ \__|_| \__,_|\___|\__|___/
*/
struct KittyCoin {
uint256 kittyId;
uint256 donationId;
uint coinSeed;
}
struct Donation {
uint256 kittyId;
address trustAddress;
address fosterAddress;
uint256 trustAmount;
uint256 fosterAmount;
}
struct Kitty {
bool donationsEnabled;
address trustAddress;
address fosterAddress;
bytes5 kittyTraitSeed;
uint256 donationCap;
uint256 donationAmount;
}
struct Trust {
bool trustEnabled;
address trustAddress;
}
/*
_____ _
| __ \ | | /\
| | | | __ _| |_ __ _ / \ _ __ _ __ __ _ _ _ ___
| | | |/ _` | __/ _` | / /\ \ | '__| '__/ _` | | | / __|
| |__| | (_| | || (_| | / ____ \| | | | | (_| | |_| \__ \
|_____/ \__,_|\__\__,_| /_/ \_\_| |_| \__,_|\__, |___/
__/ |
|___/
*/
KittyCoin[] kittyCoins;
Donation[] public donations;
Kitty[] public kitties;
Trust[] public trusts;
/*
__ __ _
| \/ | (_)
| \ / | __ _ _ __ _ __ _ _ __ __ _ ___
| |\/| |/ _` | '_ \| '_ \| | '_ \ / _` / __|
| | | | (_| | |_) | |_) | | | | | (_| \__ \
|_| |_|\__,_| .__/| .__/|_|_| |_|\__, |___/
| | | | __/ |
|_| |_| |___/
*/
/// @dev A mapping from KittyCoin IDs to the address that owns them. All coins have
/// some valid owner address.
mapping (uint256 => address) public kittyCoinToOwner;
// @dev A mapping from owner address to count of KittyCoins that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) public kittyCoinCount;
/// @dev A mapping from KittyIDs to an address that has been approved to call
/// transferFrom(). Each Kitty can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public kittyCoinToApproved;
mapping (uint256 => address) public donationToDonator;
mapping (address => uint) public donationCount;
mapping (uint256 => address) public kittyToTrust;
mapping (address => uint) public kittyCount;
mapping (uint256 => address) public trustIdToAddress;
mapping (address => bool) public trusted;
mapping (address => uint256) public pendingWithdrawals; // ETH pending for address
/*
______ _
| ____| | |
| |____ _____ _ __ | |_ ___
| __\ \ / / _ \ '_ \| __/ __|
| |___\ V / __/ | | | |_\__ \
|______\_/ \___|_| |_|\__|___/
*/
event NewKittyCoin(address _owner, uint256 kittyCoinId, uint256 kittyId, uint256 donationId, uint coinSeed);
event NewDonation(uint256 donationId, uint256 kittyId, uint256 trustAmount, uint256 fosterAmount, uint256 totalDonationAmount);
event NewKitty(uint256 kittyId, address trustAddress, address fosterAddress, bytes5 traitSeed, uint256 donationCap);
event NewTrust(uint256 trustId);
event ChangedTrustAddress(uint256 trustId, address trustAddr);
/// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kittycoin
/// ownership is assigned.
event Transfer(address from, address to, uint256 tokenId);
/*
__ __ _ _ __ _
| \/ | | (_)/ _(_)
| \ / | ___ __| |_| |_ _ ___ _ __ ___
| |\/| |/ _ \ / _` | | _| |/ _ \ '__/ __|
| | | | (_) | (_| | | | | | __/ | \__ \
|_| |_|\___/ \__,_|_|_| |_|\___|_| |___/
*/
/// @notice Throws if called by any account that is a not a trust
modifier onlyTrust() {
require(trusted[msg.sender]);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/*
_____ _ _
/ ____| | | | |
| | ___ _ __ ___| |_ _ __ _ _ ___| |_ ___ _ __
| | / _ \| '_ \/ __| __| '__| | | |/ __| __/ _ \| '__|
| |___| (_) | | | \__ \ |_| | | |_| | (__| || (_) | |
\_____\___/|_| |_|___/\__|_| \__,_|\___|\__\___/|_|
*/
/// @notice Contructor for the KittCoinClub contract
constructor() payable public {
owner = msg.sender;
//assert((remainingKittyCoins + remainingFounderCoins) == totalSupply);
}
/*
_______ _
|__ __| | |
| | ___ | | _____ _ __
| |/ _ \| |/ / _ \ '_ \
| | (_) | < __/ | | |
|_|\___/|_|\_\___|_| |_|
*/
/// @dev Assigns ownership of a specific KittyCoin to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Since the number of kittycoins is capped to 2^32 we can't overflow this
kittyCoinCount[_to]++;
// transfer ownership
kittyCoinToOwner[_tokenId] = _to;
// When creating new kittens _from is 0x0, but we can't account that address.
if (_from != address(0)) {
kittyCoinCount[_from]--;
}
// Emit the transfer event.
emit Transfer(_from, _to, _tokenId);
}
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/// @dev Set the address of the sibling contract that tracks metadata.
function setMetadataAddress(address _contractAddress) public onlyOwner {
erc721Metadata = ERC721Metadata(_contractAddress);
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular KittyCoin.
/// @param _claimant the address we are validating against.
/// @param _tokenId kittencoin id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return kittyCoinToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular KittyCoin.
/// @param _claimant the address we are confirming kittycoin is approved for.
/// @param _tokenId kittycoin id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return kittyCoinToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting Kitties on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
kittyCoinToApproved[_tokenId] = _approved;
}
/// @notice Returns the number of KittyCoins owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return kittyCoinCount[_owner];
}
/// @notice Transfers a KittyCoin to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// KittyCoin Club specifically) or your KittyCoin may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the KittyCoin to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
external
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any kittycoins (except maybe very briefly
// at the start of the contract deploy).
require(_to != address(this));
// You can only send your own kittycoin.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific KittyCoin via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the KittyCoin that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
external
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
emit Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a KittyCoin owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the KittyCoin to be transfered.
/// @param _to The address that should take ownership of the KittyCoin. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the KittyCoin to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any kittycoins (except maybe very briefly
// at the start of the contract deploy).
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Returns the total number of KittyCoins currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return kittyCoins.length - 1;
}
/// @notice Returns the address currently assigned ownership of a given KittyCoin.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address _owner)
{
_owner = kittyCoinToOwner[_tokenId];
require(_owner != address(0));
}
/// @notice Returns a list of all KittyCoin IDs assigned to an address.
/// @param _owner The owner whose KittyCoins we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire KittyCoin array looking for coins belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalKittyCoins = kittyCoins.length - 1;
uint256 resultIndex = 0;
// We count on the fact that all cats have IDs starting at 1 and increasing
// sequentially up to the totalCat count.
uint256 kittyCoinId;
for (kittyCoinId = 1; kittyCoinId <= totalKittyCoins; kittyCoinId++) {
if (kittyCoinToOwner[kittyCoinId] == _owner) {
result[resultIndex] = kittyCoinId;
resultIndex++;
}
}
return result;
}
}
/// @dev Adapted from memcpy() by @arachnid (Nick Johnson <[email protected]>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _memcpy(
uint _dest,
uint _src,
uint _len
)
private
pure
{
// Copy word-length chunks while possible
for (; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
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))
}
}
/// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <[email protected]>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private pure returns (string) {
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
/// @notice Returns a URI pointing to a metadata package for this token conforming to
/// ERC-721 (https://github.com/ethereum/EIPs/issues/721)
/// @param _tokenId The ID number of the Kitty whose metadata should be returned.
function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) {
require(erc721Metadata != address(0));
bytes32[4] memory buffer;
uint256 count;
(buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport);
return _toString(buffer, count);
}
/*
__ __ _ _ _ _ _ _
\ \ / / | | | | | | | | | | |
\ \ /\ / /_ _| | | ___| |_ | |__| | ___| |_ __ ___ _ __ ___
\ \/ \/ / _` | | |/ _ \ __| | __ |/ _ \ | '_ \ / _ \ '__/ __|
\ /\ / (_| | | | __/ |_ | | | | __/ | |_) | __/ | \__ \
\/ \/ \__,_|_|_|\___|\__| |_| |_|\___|_| .__/ \___|_| |___/
| |
|_|
*/
/// @notice Allows the withdrawal of any owed currency to a sender
function withdraw() public {
uint256 amount = pendingWithdrawals[msg.sender];
pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(amount);
}
/*
_ _____ _ _
/\ | | / ____| | | | |
/ \ __ _ __ _ _ __ ___ __ _ __ _| |_ ___ | | __ ___| |_| |_ ___ _ __ ___
/ /\ \ / _` |/ _` | '__/ _ \/ _` |/ _` | __/ _ \ | | |_ |/ _ \ __| __/ _ \ '__/ __|
/ ____ \ (_| | (_| | | | __/ (_| | (_| | || __/ | |__| | __/ |_| || __/ | \__ \
/_/ \_\__, |\__, |_| \___|\__, |\__,_|\__\___| \_____|\___|\__|\__\___|_| |___/
__/ | __/ | __/ |
|___/ |___/ |___/
*/
/// @notice Retrieves an array containing all Donations.
/// @return an array of donations
function getDonations() external view returns(uint256[]) {
uint256[] memory result = new uint256[](donations.length);
uint256 counter = 0;
for (uint256 i = 0; i < donations.length; i++) {
result[counter] = i;
counter++;
}
return result;
}
/// @notice Retrieves an array containing all Kitties up for donation.
/// @return an array of kitties that are up for donation
function getKitties() external view returns(uint256[]) {
uint256[] memory result = new uint[](kitties.length);
uint256 counter = 0;
for (uint256 i = 0; i < kitties.length; i++) {
result[counter] = i;
counter++;
}
return result;
}
/*
_ ___ _ _ _____ _
| |/ (_) | | | / ____| (_)
| ' / _| |_| |_ _ _| | ___ _ _ __
| < | | __| __| | | | | / _ \| | '_ \
| . \| | |_| |_| |_| | |___| (_) | | | | |
|_|\_\_|\__|\__|\__, |\_____\___/|_|_| |_|
__/ |
|___/
*/
uint coinDigits = 16;
uint coinSeedModulus = 10 ** coinDigits;
/// @notice generate the KittyCoins safely
/// @param _kittyId identifier of the kitty who recieved the donation for this coin
/// @param _donationId donation identifier that is linked to this coin
/// @param _seed the generated seed
function _createKittyCoin(
uint256 _kittyId,
uint256 _donationId,
uint256 _seed,
address _owner
)
internal
returns (uint)
{
KittyCoin memory _kittyCoin = KittyCoin({
kittyId: _kittyId,
donationId: _donationId,
coinSeed: _seed
});
uint256 newKittyCoinId = kittyCoins.push(_kittyCoin) - 1;
// It's probably never going to happen, 4 billion kittycoins is A LOT, but
// let's just be 100% sure we never let this happen.
require(newKittyCoinId == uint256(uint32(newKittyCoinId)));
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newKittyCoinId);
// Send KittyCoin event
emit NewKittyCoin(
_owner,
newKittyCoinId,
uint256(_kittyCoin.kittyId),
uint256(_kittyCoin.donationId),
uint256(_kittyCoin.coinSeed)
);
return newKittyCoinId;
}
//TODO work out if changing this input parameter to a uint is bad
/// @notice Generates the random seed based on an input string
/// @param _kittyTraits input seed for the randomly generated coin
/// @return a random seed
function _generateRandomSeed(bytes5 _kittyTraits) private view returns (uint256) {
uint256 rand = uint256(keccak256(_kittyTraits));
return rand * coinSeedModulus;
}
/// @notice Generates a Kitty coin for a donation that has been made
/// @param _donationId donation to be used to generate the coin
/// @return _kittyCoinId of the new KittyCoin
function createRandomKittyCoin(uint256 _donationId) public returns(uint256) {
// Confirm that the owner doesn't have any kittycoins
require(kittyCoinCount[msg.sender] == 0);
uint256 kittyId = donations[_donationId].kittyId;
bytes5 kittyTraitSeed = kitties[kittyId].kittyTraitSeed;
// the seed for the kittycoin is generated based on the input string
uint256 randSeed = _generateRandomSeed(kittyTraitSeed);
// The cat is created by a private function
uint256 _kittyCoinId = _createKittyCoin(
kittyId,
_donationId,
randSeed,
msg.sender
);
return _kittyCoinId;
}
/*
_____ _ _
| __ \ | | (_)
| | | | ___ _ __ __ _| |_ _ ___ _ __
| | | |/ _ \| '_ \ / _` | __| |/ _ \| '_ \
| |__| | (_) | | | | (_| | |_| | (_) | | | |
|_____/ \___/|_| |_|\__,_|\__|_|\___/|_| |_|
*/
/// @notice Performs a donation based on the computed variables from the donator.
/// @param _kittyId The id of the kitty being donated to
/// @param _trustAmount The amount being donated to the trust
/// @param _fosterAmount The amount being donated to the foster carer
/// @param _trustAddress The wallet address of the trust
/// @param _fosterAddress The wallet address of the foster carer
function _donate(
uint256 _kittyId,
uint256 _trustAmount,
uint256 _fosterAmount,
address _trustAddress,
address _fosterAddress) internal
{
uint256 id = donations.push(Donation(
_kittyId,
_trustAddress,
_fosterAddress,
_trustAmount,
_fosterAmount
)) - 1;
// Complete the transaction
pendingWithdrawals[_trustAddress] = SafeMath.add(pendingWithdrawals[_trustAddress], _trustAmount);
pendingWithdrawals[_fosterAddress] = SafeMath.add(pendingWithdrawals[_fosterAddress], _fosterAmount);
donationToDonator[id] = msg.sender;
donationCount[msg.sender]++;
// Safe Maths sum total
uint256 totalAmount = SafeMath.add(_trustAmount, _fosterAmount);
// Add amount to a kitties donation limit
kitties[_kittyId].donationAmount = SafeMath.add(kitties[_kittyId].donationAmount, totalAmount);
emit NewDonation(
id,
_kittyId,
_trustAmount,
_fosterAmount,
totalAmount
);
}
/// @notice Performs a donation, If the foster carer has reached their limit for donations when the amount goes to the trust.
/// @param _kittyId The id of the kitty being donated to
/// @param _trustAmount Amount that should go to the trust
/// @param _fosterAmount Amount that should go to the foster carer
function makeDonation(uint256 _kittyId, uint256 _trustAmount, uint256 _fosterAmount) payable public {
require(msg.value > 0);
require(kitties[_kittyId].donationsEnabled);
require(SafeMath.add(_trustAmount, _fosterAmount) == msg.value);
// Safe Maths donation
uint256 donationTotal = msg.value;
uint256 fosterAmount = _fosterAmount;
uint256 donationLimit = SafeMath.sub(kitties[_kittyId].donationCap, kitties[_kittyId].donationAmount);
if (donationLimit <= 0) {
fosterAmount = 0;
}
if (fosterAmount >= donationLimit) {
uint256 fosterOverflow = SafeMath.sub(_fosterAmount, donationLimit);
fosterAmount = SafeMath.sub(_fosterAmount, fosterOverflow);
}
uint256 trustAmount = SafeMath.sub(donationTotal, fosterAmount);
// Validate the maths worked correctly
assert(msg.value == SafeMath.add(trustAmount, fosterAmount));
// Make the donation
_donate(
_kittyId,
trustAmount,
fosterAmount,
kitties[_kittyId].trustAddress,
kitties[_kittyId].fosterAddress
);
}
/// @notice Performs a donation, computing the ratio of the funds that should go to the trust and the foster carer. If the foster carer has reached their limit for donations when the amount goes to the trust.
/// @param _donator Donator address
/// @return an array of donation identifiers
function getDonationsByDonator(address _donator) external view returns(uint256[]) {
uint[] memory result = new uint[](donationCount[_donator]);
uint counter = 0;
for (uint i = 0; i < donations.length; i++) {
if (donationToDonator[i] == _donator) {
result[counter] = i;
counter++;
}
}
return result;
}
/// @notice Gets a donation object based on its id
/// @param _donationId The ID of the donation
/// @return Contents of the Donation struct
function getDonation(uint256 _donationId)
external
view
returns(
uint256 kittyId,
address trustAddress,
address fosterAddress,
uint256 trustAmount,
uint256 fosterAmount
) {
Donation storage donation = donations[_donationId];
kittyId = donation.kittyId;
trustAddress = donation.trustAddress;
fosterAddress = donation.fosterAddress;
trustAmount = uint256(donation.trustAmount);
fosterAmount = uint256(donation.fosterAmount);
}
/*
_ ___ _ _
| |/ (_) | | |
| ' / _| |_| |_ _ _
| < | | __| __| | | |
| . \| | |_| |_| |_| |
|_|\_\_|\__|\__|\__, |
__/ |
|___/
*/
/// @notice private function to create a new kitty which goes up for donation
/// @param _enabled Toggles the donation status on this kitty
/// @param _trustAddr The wallet address of the trust
/// @param _fosterAddr The wallet address of the foster carer
/// @param _traitSeed Unique traits for this kitty
/// @param _donationCap The maximum amount that the carer can receive
function _createKitty(
bool _enabled,
address _trustAddr,
address _fosterAddr,
bytes5 _traitSeed,
uint256 _donationCap
) internal
{
uint256 id = kitties.push(Kitty(
_enabled,
_trustAddr,
_fosterAddr,
_traitSeed,
_donationCap,
0 // Default donation start at 0
)) - 1;
kittyToTrust[id] = msg.sender;
kittyCount[msg.sender]++;
emit NewKitty(
id,
_trustAddr,
_fosterAddr,
_traitSeed,
_donationCap
);
}
/// @notice Creates a new kitty which goes up for donation
/// @param _fosterAddress The wallet address of the foster carer
/// @param _traitSeed Unique traits for this kitty
/// @param _donationCap The maximum amount that the carer can receive
function createKitty(address _fosterAddress, bytes5 _traitSeed, uint256 _donationCap) onlyTrust public {
require(_donationCap > 0);
_createKitty(
true,
msg.sender,
_fosterAddress,
_traitSeed,
_donationCap
);
}
/// @notice Returns all the relevant information about a specific kitty.
/// @param _kittyId The ID of the kitty of interest.
function getKitty(uint256 _kittyId)
external
view
returns (
bool isEnabled,
address trustAddress,
address fosterAddress,
bytes5 traitSeed,
uint256 donationCap,
uint256 donationAmount
) {
Kitty storage kitty = kitties[_kittyId];
isEnabled = kitty.donationsEnabled;
trustAddress = kitty.trustAddress;
fosterAddress = kitty.fosterAddress;
traitSeed = bytes5(kitty.kittyTraitSeed);
donationCap = uint256(kitty.donationCap);
donationAmount = uint256(kitty.donationAmount);
}
/*
_______ _
|__ __| | |
| |_ __ _ _ ___| |_
| | '__| | | / __| __|
| | | | |_| \__ \ |_
|_|_| \__,_|___/\__|
*/
/// @notice Private trust creation that is handled internally
/// @param _enabled Is the trust enabled
/// @param _trustAddr The address to link this trust to
function _createTrust(bool _enabled, address _trustAddr) internal {
uint256 id = trusts.push(Trust(_enabled, _trustAddr)) - 1;
trustIdToAddress[id] = _trustAddr;
trusted[_trustAddr] = _enabled;
emit NewTrust(id);
}
/// @notice Allows the contract owner to add a new trust
/// @param _trustAddr The address to link this trust to
function createTrust(address _trustAddr) onlyOwner public {
_createTrust(true, _trustAddr);
}
/// @notice Allows the contract owner to enable and disable trusts
/// @param _id The id of the trust that should be toggled
/// @param _enabled A boolean true or false, where true is to enable and false is to disable the trust
function toggleTrust(uint256 _id, bool _enabled) onlyOwner public {
trusts[_id].trustEnabled = _enabled;
trusted[trusts[_id].trustAddress] = _enabled;
}
/// @notice Allows a trust to change their address
/// @param _newTrustAddr The new trust address to be set
function changeTrustAddress(uint256 _id, address _newTrustAddr) onlyTrust public {
require(trusts[_id].trustAddress == msg.sender);
trusts[_id].trustAddress = _newTrustAddr;
trustIdToAddress[_id] = _newTrustAddr;
//TODO replace this logic with something better
trusted[_newTrustAddr] = true;
trusted[msg.sender] = false;
emit ChangedTrustAddress(_id, _newTrustAddr);
}
/// @notice Checks if a given address belongs to a trust
/// @param _address is the address that needs to be checked
/// @return a boolean defining if a given address belongs to a trust
function isTrustAddress(address _address) public view returns (bool) {
return trusted[_address];
}
} | @notice Grant another address the right to transfer a specific KittyCoin via transferFrom(). This is the preferred flow for transfering NFTs to contracts. @param _to The address to be granted transfer approval. Pass address(0) to clear all approvals. @param _tokenId The ID of the KittyCoin that can be transferred if this call succeeds. @dev Required for ERC-721 compliance. Only an owner can grant transfer approval. Register the approval (replacing any previous approval). Emit approval event. | function approve(
address _to,
uint256 _tokenId
)
external
{
require(_owns(msg.sender, _tokenId));
_approve(_tokenId, _to);
emit Approval(msg.sender, _to, _tokenId);
}
| 982,427 | [
1,
4625,
348,
7953,
560,
30,
225,
632,
20392,
19689,
4042,
1758,
326,
2145,
358,
7412,
279,
2923,
1475,
305,
4098,
27055,
3970,
225,
7412,
1265,
7675,
1220,
353,
326,
9119,
4693,
364,
7412,
310,
423,
4464,
87,
358,
20092,
18,
632,
891,
389,
869,
1021,
1758,
358,
506,
17578,
7412,
23556,
18,
10311,
1758,
12,
20,
13,
358,
225,
2424,
777,
6617,
4524,
18,
632,
891,
389,
2316,
548,
1021,
1599,
434,
326,
1475,
305,
4098,
27055,
716,
848,
506,
906,
4193,
309,
333,
745,
21933,
18,
632,
5206,
10647,
364,
4232,
39,
17,
27,
5340,
29443,
18,
5098,
392,
3410,
848,
7936,
7412,
23556,
18,
5433,
326,
23556,
261,
26745,
5330,
1281,
2416,
23556,
2934,
16008,
23556,
871,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
6617,
537,
12,
203,
3639,
1758,
389,
869,
16,
203,
3639,
2254,
5034,
389,
2316,
548,
203,
565,
262,
203,
3639,
3903,
203,
565,
288,
203,
3639,
2583,
24899,
995,
87,
12,
3576,
18,
15330,
16,
389,
2316,
548,
10019,
203,
203,
3639,
389,
12908,
537,
24899,
2316,
548,
16,
389,
869,
1769,
203,
203,
3639,
3626,
1716,
685,
1125,
12,
3576,
18,
15330,
16,
389,
869,
16,
389,
2316,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xcA905F6466C253f8195b9940C819Ba32d273447d/sources/contracts/SettingsInternal.sol | * Check if Custom URL*/ | function isPicsum() internal view returns (bool) {
return getSettings().use_picsum;
}
| 860,362 | [
1,
4625,
348,
7953,
560,
30,
380,
2073,
309,
6082,
1976,
5549,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
29962,
335,
1364,
1435,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
18283,
7675,
1202,
67,
20003,
1364,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.2;
// File: @daostack/infra/contracts/votingMachines/IntVoteInterface.sol
interface intvoteinterface31 { //inject NONSTANDARD NAMING
//When implementing this interface please do not only override function and modifier,
//but also to keep the modifiers on the overridden functions.
modifier ONLYPROPOSALOWNER70(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING
modifier VOTABLE14(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING
event NEWPROPOSAL82( //inject NONSTANDARD NAMING
bytes32 indexed _proposalId,
address indexed _organization,
uint256 _numOfChoices,
address _proposer,
bytes32 _paramsHash
);
event EXECUTEPROPOSAL67(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
uint256 _decision,
uint256 _totalReputation
);
event VOTEPROPOSAL81( //inject NONSTANDARD NAMING
bytes32 indexed _proposalId,
address indexed _organization,
address indexed _voter,
uint256 _vote,
uint256 _reputation
);
event CANCELPROPOSAL59(bytes32 indexed _proposalId, address indexed _organization ); //inject NONSTANDARD NAMING
event CANCELVOTING5(bytes32 indexed _proposalId, address indexed _organization, address indexed _voter); //inject NONSTANDARD NAMING
function PROPOSE48( //inject NONSTANDARD NAMING
uint256 _numOfChoices,
bytes32 _proposalParameters,
address _proposer,
address _organization
) external returns(bytes32);
function VOTE79( //inject NONSTANDARD NAMING
bytes32 _proposalId,
uint256 _vote,
uint256 _rep,
address _voter
)
external
returns(bool);
function CANCELVOTE62(bytes32 _proposalId) external; //inject NONSTANDARD NAMING
function GETNUMBEROFCHOICES23(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING
function ISVOTABLE72(bytes32 _proposalId) external view returns(bool); //inject NONSTANDARD NAMING
function VOTESTATUS55(bytes32 _proposalId, uint256 _choice) external view returns(uint256); //inject NONSTANDARD NAMING
function ISABSTAINALLOW86() external pure returns(bool); //inject NONSTANDARD NAMING
function GETALLOWEDRANGEOFCHOICES7() external pure returns(uint256 min, uint256 max); //inject NONSTANDARD NAMING
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
interface ierc2016 { //inject NONSTANDARD NAMING
function TRANSFER74(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE55(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM94(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TOTALSUPPLY28() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF62(address who) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE21(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
event TRANSFER49(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL97(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: @daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol
interface votingmachinecallbacksinterface79 { //inject NONSTANDARD NAMING
function MINTREPUTATION65(uint256 _amount, address _beneficiary, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING
function BURNREPUTATION8(uint256 _amount, address _owner, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING
function STAKINGTOKENTRANSFER23(ierc2016 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) //inject NONSTANDARD NAMING
external
returns(bool);
function GETTOTALREPUTATIONSUPPLY93(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING
function REPUTATIONOF100(address _owner, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING
function BALANCEOFSTAKINGTOKEN17(ierc2016 _stakingToken, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
contract ownable56 { //inject NONSTANDARD NAMING
address private _owner;
event OWNERSHIPTRANSFERRED0(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = msg.sender;
emit OWNERSHIPTRANSFERRED0(address(0), _owner);
}
function OWNER8() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER65() { //inject NONSTANDARD NAMING
require(ISOWNER85());
_;
}
function ISOWNER85() public view returns (bool) { //inject NONSTANDARD NAMING
return msg.sender == _owner;
}
function RENOUNCEOWNERSHIP94() public ONLYOWNER65 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED0(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP25(address newOwner) public ONLYOWNER65 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP15(newOwner);
}
function _TRANSFEROWNERSHIP15(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0));
emit OWNERSHIPTRANSFERRED0(_owner, newOwner);
_owner = newOwner;
}
}
// File: @daostack/infra/contracts/Reputation.sol
contract reputation51 is ownable56 { //inject NONSTANDARD NAMING
uint8 public decimals = 18; //Number of decimals of the smallest unit
// Event indicating minting of reputation to an address.
event MINT64(address indexed _to, uint256 _amount); //inject NONSTANDARD NAMING
// Event indicating burning of reputation for an address.
event BURN4(address indexed _from, uint256 _amount); //inject NONSTANDARD NAMING
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of reputation at a specific block number
uint128 value;
}
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// Tracks the history of the `totalSupply` of the reputation
Checkpoint[] totalSupplyHistory;
constructor(
) public
{
}
function TOTALSUPPLY28() public view returns (uint256) { //inject NONSTANDARD NAMING
return TOTALSUPPLYAT94(block.number);
}
// Query balance and totalSupply in History
function BALANCEOF62(address _owner) public view returns (uint256 balance) { //inject NONSTANDARD NAMING
return BALANCEOFAT72(_owner, block.number);
}
function BALANCEOFAT72(address _owner, uint256 _blockNumber) //inject NONSTANDARD NAMING
public view returns (uint256)
{
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
return 0;
// This will return the expected balance during normal situations
} else {
return GETVALUEAT9(balances[_owner], _blockNumber);
}
}
function TOTALSUPPLYAT94(uint256 _blockNumber) public view returns(uint256) { //inject NONSTANDARD NAMING
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
return 0;
// This will return the expected totalSupply during normal situations
} else {
return GETVALUEAT9(totalSupplyHistory, _blockNumber);
}
}
function MINT38(address _user, uint256 _amount) public ONLYOWNER65 returns (bool) { //inject NONSTANDARD NAMING
uint256 curTotalSupply = TOTALSUPPLY28();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint256 previousBalanceTo = BALANCEOF62(_user);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
UPDATEVALUEATNOW85(totalSupplyHistory, curTotalSupply + _amount);
UPDATEVALUEATNOW85(balances[_user], previousBalanceTo + _amount);
emit MINT64(_user, _amount);
return true;
}
function BURN49(address _user, uint256 _amount) public ONLYOWNER65 returns (bool) { //inject NONSTANDARD NAMING
uint256 curTotalSupply = TOTALSUPPLY28();
uint256 amountBurned = _amount;
uint256 previousBalanceFrom = BALANCEOF62(_user);
if (previousBalanceFrom < amountBurned) {
amountBurned = previousBalanceFrom;
}
UPDATEVALUEATNOW85(totalSupplyHistory, curTotalSupply - amountBurned);
UPDATEVALUEATNOW85(balances[_user], previousBalanceFrom - amountBurned);
emit BURN4(_user, amountBurned);
return true;
}
// Internal helper functions to query and set a value in a snapshot array
function GETVALUEAT9(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) { //inject NONSTANDARD NAMING
if (checkpoints.length == 0) {
return 0;
}
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock) {
return checkpoints[checkpoints.length-1].value;
}
if (_block < checkpoints[0].fromBlock) {
return 0;
}
// Binary search of the value in the array
uint256 min = 0;
uint256 max = checkpoints.length-1;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
function UPDATEVALUEATNOW85(Checkpoint[] storage checkpoints, uint256 _value) internal { //inject NONSTANDARD NAMING
require(uint128(_value) == _value); //check value is in the 128 bits bounderies
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
}
// File: /Users/oren/daostack/daostack2/daostack/node_modules/openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
// File: /Users/oren/daostack/daostack2/daostack/node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol
library safemath4 { //inject NONSTANDARD NAMING
function MUL16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV25(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function SUB37(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function ADD40(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MOD29(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
// File: /Users/oren/daostack/daostack2/daostack/node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
contract erc2045 is ierc2016 { //inject NONSTANDARD NAMING
using safemath4 for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function TOTALSUPPLY28() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF62(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[owner];
}
function ALLOWANCE21(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowed[owner][spender];
}
function TRANSFER74(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER44(msg.sender, to, value);
return true;
}
function APPROVE55(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit APPROVAL97(msg.sender, spender, value);
return true;
}
function TRANSFERFROM94(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_allowed[from][msg.sender] = _allowed[from][msg.sender].SUB37(value);
_TRANSFER44(from, to, value);
emit APPROVAL97(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
function INCREASEALLOWANCE67(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].ADD40(addedValue);
emit APPROVAL97(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function DECREASEALLOWANCE11(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].SUB37(subtractedValue);
emit APPROVAL97(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _TRANSFER44(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
require(to != address(0));
_balances[from] = _balances[from].SUB37(value);
_balances[to] = _balances[to].ADD40(value);
emit TRANSFER49(from, to, value);
}
function _MINT14(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.ADD40(value);
_balances[account] = _balances[account].ADD40(value);
emit TRANSFER49(address(0), account, value);
}
function _BURN11(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.SUB37(value);
_balances[account] = _balances[account].SUB37(value);
emit TRANSFER49(account, address(0), value);
}
function _BURNFROM86(address account, uint256 value) internal { //inject NONSTANDARD NAMING
_allowed[account][msg.sender] = _allowed[account][msg.sender].SUB37(value);
_BURN11(account, value);
emit APPROVAL97(account, msg.sender, _allowed[account][msg.sender]);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol
contract erc20burnable16 is erc2045 { //inject NONSTANDARD NAMING
function BURN49(uint256 value) public { //inject NONSTANDARD NAMING
_BURN11(msg.sender, value);
}
function BURNFROM98(address from, uint256 value) public { //inject NONSTANDARD NAMING
_BURNFROM86(from, value);
}
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/controller/DAOToken.sol
contract daotoken36 is erc2045, erc20burnable16, ownable56 { //inject NONSTANDARD NAMING
string public name;
string public symbol;
// solhint-disable-next-line const-name-snakecase
uint8 public constant decimals61 = 18; //inject NONSTANDARD NAMING
uint256 public cap;
constructor(string memory _name, string memory _symbol, uint256 _cap)
public {
name = _name;
symbol = _symbol;
cap = _cap;
}
function MINT38(address _to, uint256 _amount) public ONLYOWNER65 returns (bool) { //inject NONSTANDARD NAMING
if (cap > 0)
require(TOTALSUPPLY28().ADD40(_amount) <= cap);
_MINT14(_to, _amount);
return true;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
library address8 { //inject NONSTANDARD NAMING
function ISCONTRACT13(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/libs/SafeERC20.sol
pragma solidity ^0.5.2;
library safeerc2019 { //inject NONSTANDARD NAMING
using address8 for address;
bytes4 constant private transfer_selector2 = bytes4(keccak256(bytes("transfer(address,uint256)"))); //inject NONSTANDARD NAMING
bytes4 constant private transferfrom_selector45 = bytes4(keccak256(bytes("transferFrom(address,address,uint256)"))); //inject NONSTANDARD NAMING
bytes4 constant private approve_selector67 = bytes4(keccak256(bytes("approve(address,uint256)"))); //inject NONSTANDARD NAMING
function SAFETRANSFER100(address _erc20Addr, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING
// Must be a contract addr first!
require(_erc20Addr.ISCONTRACT13());
(bool success, bytes memory returnValue) =
// solhint-disable-next-line avoid-low-level-calls
_erc20Addr.call(abi.encodeWithSelector(transfer_selector2, _to, _value));
// call return false when something wrong
require(success);
//check return value
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function SAFETRANSFERFROM10(address _erc20Addr, address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING
// Must be a contract addr first!
require(_erc20Addr.ISCONTRACT13());
(bool success, bytes memory returnValue) =
// solhint-disable-next-line avoid-low-level-calls
_erc20Addr.call(abi.encodeWithSelector(transferfrom_selector45, _from, _to, _value));
// call return false when something wrong
require(success);
//check return value
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function SAFEAPPROVE78(address _erc20Addr, address _spender, uint256 _value) internal { //inject NONSTANDARD NAMING
// Must be a contract addr first!
require(_erc20Addr.ISCONTRACT13());
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero.
require((_value == 0) || (ierc2016(_erc20Addr).ALLOWANCE21(msg.sender, _spender) == 0));
(bool success, bytes memory returnValue) =
// solhint-disable-next-line avoid-low-level-calls
_erc20Addr.call(abi.encodeWithSelector(approve_selector67, _spender, _value));
// call return false when something wrong
require(success);
//check return value
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/controller/Avatar.sol
contract avatar70 is ownable56 { //inject NONSTANDARD NAMING
using safeerc2019 for address;
string public orgName;
daotoken36 public nativeToken;
reputation51 public nativeReputation;
event GENERICCALL1(address indexed _contract, bytes _params, bool _success); //inject NONSTANDARD NAMING
event SENDETHER8(uint256 _amountInWei, address indexed _to); //inject NONSTANDARD NAMING
event EXTERNALTOKENTRANSFER37(address indexed _externalToken, address indexed _to, uint256 _value); //inject NONSTANDARD NAMING
event EXTERNALTOKENTRANSFERFROM36(address indexed _externalToken, address _from, address _to, uint256 _value); //inject NONSTANDARD NAMING
event EXTERNALTOKENAPPROVAL0(address indexed _externalToken, address _spender, uint256 _value); //inject NONSTANDARD NAMING
event RECEIVEETHER12(address indexed _sender, uint256 _value); //inject NONSTANDARD NAMING
constructor(string memory _orgName, daotoken36 _nativeToken, reputation51 _nativeReputation) public {
orgName = _orgName;
nativeToken = _nativeToken;
nativeReputation = _nativeReputation;
}
function() external payable {
emit RECEIVEETHER12(msg.sender, msg.value);
}
function GENERICCALL24(address _contract, bytes memory _data) //inject NONSTANDARD NAMING
public
ONLYOWNER65
returns(bool success, bytes memory returnValue) {
// solhint-disable-next-line avoid-low-level-calls
(success, returnValue) = _contract.call(_data);
emit GENERICCALL1(_contract, _data, success);
}
function SENDETHER91(uint256 _amountInWei, address payable _to) public ONLYOWNER65 returns(bool) { //inject NONSTANDARD NAMING
_to.transfer(_amountInWei);
emit SENDETHER8(_amountInWei, _to);
return true;
}
function EXTERNALTOKENTRANSFER67(ierc2016 _externalToken, address _to, uint256 _value) //inject NONSTANDARD NAMING
public ONLYOWNER65 returns(bool)
{
address(_externalToken).SAFETRANSFER100(_to, _value);
emit EXTERNALTOKENTRANSFER37(address(_externalToken), _to, _value);
return true;
}
function EXTERNALTOKENTRANSFERFROM68( //inject NONSTANDARD NAMING
ierc2016 _externalToken,
address _from,
address _to,
uint256 _value
)
public ONLYOWNER65 returns(bool)
{
address(_externalToken).SAFETRANSFERFROM10(_from, _to, _value);
emit EXTERNALTOKENTRANSFERFROM36(address(_externalToken), _from, _to, _value);
return true;
}
function EXTERNALTOKENAPPROVAL13(ierc2016 _externalToken, address _spender, uint256 _value) //inject NONSTANDARD NAMING
public ONLYOWNER65 returns(bool)
{
address(_externalToken).SAFEAPPROVE78(_spender, _value);
emit EXTERNALTOKENAPPROVAL0(address(_externalToken), _spender, _value);
return true;
}
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/universalSchemes/UniversalSchemeInterface.sol
contract universalschemeinterface23 { //inject NONSTANDARD NAMING
function UPDATEPARAMETERS61(bytes32 _hashedParameters) public; //inject NONSTANDARD NAMING
function GETPARAMETERSFROMCONTROLLER72(avatar70 _avatar) internal view returns(bytes32); //inject NONSTANDARD NAMING
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/globalConstraints/GlobalConstraintInterface.sol
contract globalconstraintinterface55 { //inject NONSTANDARD NAMING
enum CallPhase { Pre, Post, PreAndPost }
function PRE44( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING
function POST41( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING
function WHEN71() public returns(CallPhase); //inject NONSTANDARD NAMING
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/controller/ControllerInterface.sol
interface controllerinterface59 { //inject NONSTANDARD NAMING
function MINTREPUTATION65(uint256 _amount, address _to, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function BURNREPUTATION8(uint256 _amount, address _from, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function MINTTOKENS53(uint256 _amount, address _beneficiary, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function REGISTERSCHEME80(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function UNREGISTERSCHEME15(address _scheme, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function UNREGISTERSELF18(address _avatar) external returns(bool); //inject NONSTANDARD NAMING
function ADDGLOBALCONSTRAINT70(address _globalConstraint, bytes32 _params, address _avatar) //inject NONSTANDARD NAMING
external returns(bool);
function REMOVEGLOBALCONSTRAINT6 (address _globalConstraint, address _avatar) //inject NONSTANDARD NAMING
external returns(bool);
function UPGRADECONTROLLER96(address _newController, avatar70 _avatar) //inject NONSTANDARD NAMING
external returns(bool);
function GENERICCALL24(address _contract, bytes calldata _data, avatar70 _avatar) //inject NONSTANDARD NAMING
external
returns(bool, bytes memory);
function SENDETHER91(uint256 _amountInWei, address payable _to, avatar70 _avatar) //inject NONSTANDARD NAMING
external returns(bool);
function EXTERNALTOKENTRANSFER67(ierc2016 _externalToken, address _to, uint256 _value, avatar70 _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function EXTERNALTOKENTRANSFERFROM68( //inject NONSTANDARD NAMING
ierc2016 _externalToken,
address _from,
address _to,
uint256 _value,
avatar70 _avatar)
external
returns(bool);
function EXTERNALTOKENAPPROVAL13(ierc2016 _externalToken, address _spender, uint256 _value, avatar70 _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function GETNATIVEREPUTATION64(address _avatar) //inject NONSTANDARD NAMING
external
view
returns(address);
function ISSCHEMEREGISTERED53( address _scheme, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING
function GETSCHEMEPARAMETERS80(address _scheme, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING
function GETGLOBALCONSTRAINTPARAMETERS50(address _globalConstraint, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING
function GETSCHEMEPERMISSIONS72(address _scheme, address _avatar) external view returns(bytes4); //inject NONSTANDARD NAMING
function GLOBALCONSTRAINTSCOUNT61(address _avatar) external view returns(uint, uint); //inject NONSTANDARD NAMING
function ISGLOBALCONSTRAINTREGISTERED65(address _globalConstraint, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/universalSchemes/UniversalScheme.sol
contract universalscheme48 is ownable56, universalschemeinterface23 { //inject NONSTANDARD NAMING
bytes32 public hashedParameters; // For other parameters.
function UPDATEPARAMETERS61( //inject NONSTANDARD NAMING
bytes32 _hashedParameters
)
public
ONLYOWNER65
{
hashedParameters = _hashedParameters;
}
function GETPARAMETERSFROMCONTROLLER72(avatar70 _avatar) internal view returns(bytes32) { //inject NONSTANDARD NAMING
require(controllerinterface59(_avatar.OWNER8()).ISSCHEMEREGISTERED53(address(this), address(_avatar)),
"scheme is not registered");
return controllerinterface59(_avatar.OWNER8()).GETSCHEMEPARAMETERS80(address(this), address(_avatar));
}
}
// File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol
library ecdsa86 { //inject NONSTANDARD NAMING
function RECOVER59(bytes32 hash, bytes memory signature) internal pure returns (address) { //inject NONSTANDARD NAMING
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (signature.length != 65) {
return (address(0));
}
// 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.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
function TOETHSIGNEDMESSAGEHASH91(bytes32 hash) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/libs/RealMath.sol
library realmath32 { //inject NONSTANDARD NAMING
uint256 constant private real_bits92 = 256; //inject NONSTANDARD NAMING
uint256 constant private real_fbits8 = 40; //inject NONSTANDARD NAMING
uint256 constant private real_one87 = uint256(1) << real_fbits8; //inject NONSTANDARD NAMING
function POW66(uint256 realBase, uint256 exponent) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 tempRealBase = realBase;
uint256 tempExponent = exponent;
// Start with the 0th power
uint256 realResult = real_one87;
while (tempExponent != 0) {
// While there are still bits set
if ((tempExponent & 0x1) == 0x1) {
// If the low bit is set, multiply in the (many-times-squared) base
realResult = MUL16(realResult, tempRealBase);
}
// Shift off the low bit
tempExponent = tempExponent >> 1;
// Do the squaring
tempRealBase = MUL16(tempRealBase, tempRealBase);
}
// Return the final result.
return uint216(realResult / real_one87);
}
function FRACTION6(uint216 numerator, uint216 denominator) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV25(uint256(numerator) * real_one87, uint256(denominator) * real_one87);
}
function MUL16(uint256 realA, uint256 realB) private pure returns (uint256) { //inject NONSTANDARD NAMING
// When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format.
// So we just have to clip off the extra REAL_FBITS fractional bits.
return uint256((uint256(realA) * uint256(realB)) >> real_fbits8);
}
function DIV25(uint256 realNumerator, uint256 realDenominator) private pure returns (uint256) { //inject NONSTANDARD NAMING
// We use the reverse of the multiplication trick: convert numerator from
// x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point.
return uint256((uint256(realNumerator) * real_one87) / uint256(realDenominator));
}
}
// File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol
// File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/votingMachines/ProposalExecuteInterface.sol
interface proposalexecuteinterface9 { //inject NONSTANDARD NAMING
function EXECUTEPROPOSAL85(bytes32 _proposalId, int _decision) external returns(bool); //inject NONSTANDARD NAMING
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
// File: openzeppelin-solidity/contracts/math/Math.sol
library math46 { //inject NONSTANDARD NAMING
function MAX19(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a >= b ? a : b;
}
function MIN92(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a < b ? a : b;
}
function AVERAGE32(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/votingMachines/GenesisProtocolLogic.sol
contract genesisprotocollogic61 is intvoteinterface31 { //inject NONSTANDARD NAMING
using safemath4 for uint;
using math46 for uint;
using realmath32 for uint216;
using realmath32 for uint256;
using address8 for address;
enum ProposalState { None, ExpiredInQueue, Executed, Queued, PreBoosted, Boosted, QuietEndingPeriod}
enum ExecutionState { None, QueueBarCrossed, QueueTimeOut, PreBoostedBarCrossed, BoostedTimeOut, BoostedBarCrossed}
//Organization's parameters
struct Parameters {
uint256 queuedVoteRequiredPercentage; // the absolute vote percentages bar.
uint256 queuedVotePeriodLimit; //the time limit for a proposal to be in an absolute voting mode.
uint256 boostedVotePeriodLimit; //the time limit for a proposal to be in boost mode.
uint256 preBoostedVotePeriodLimit; //the time limit for a proposal
//to be in an preparation state (stable) before boosted.
uint256 thresholdConst; //constant for threshold calculation .
//threshold =thresholdConst ** (numberOfBoostedProposals)
uint256 limitExponentValue;// an upper limit for numberOfBoostedProposals
//in the threshold calculation to prevent overflow
uint256 quietEndingPeriod; //quite ending period
uint256 proposingRepReward;//proposer reputation reward.
uint256 votersReputationLossRatio;//Unsuccessful pre booster
//voters lose votersReputationLossRatio% of their reputation.
uint256 minimumDaoBounty;
uint256 daoBountyConst;//The DAO downstake for each proposal is calculate according to the formula
//(daoBountyConst * averageBoostDownstakes)/100 .
uint256 activationTime;//the point in time after which proposals can be created.
//if this address is set so only this address is allowed to vote of behalf of someone else.
address voteOnBehalf;
}
struct Voter {
uint256 vote; // YES(1) ,NO(2)
uint256 reputation; // amount of voter's reputation
bool preBoosted;
}
struct Staker {
uint256 vote; // YES(1) ,NO(2)
uint256 amount; // amount of staker's stake
uint256 amount4Bounty;// amount of staker's stake used for bounty reward calculation.
}
struct Proposal {
bytes32 organizationId; // the organization unique identifier the proposal is target to.
address callbacks; // should fulfill voting callbacks interface.
ProposalState state;
uint256 winningVote; //the winning vote.
address proposer;
//the proposal boosted period limit . it is updated for the case of quiteWindow mode.
uint256 currentBoostedVotePeriodLimit;
bytes32 paramsHash;
uint256 daoBountyRemain; //use for checking sum zero bounty claims.it is set at the proposing time.
uint256 daoBounty;
uint256 totalStakes;// Total number of tokens staked which can be redeemable by stakers.
uint256 confidenceThreshold;
//The percentage from upper stakes which the caller for the expiration was given.
uint256 expirationCallBountyPercentage;
uint[3] times; //times[0] - submittedTime
//times[1] - boostedPhaseTime
//times[2] -preBoostedPhaseTime;
// vote reputation
mapping(uint256 => uint256 ) votes;
// vote reputation
mapping(uint256 => uint256 ) preBoostedVotes;
// address voter
mapping(address => Voter ) voters;
// vote stakes
mapping(uint256 => uint256 ) stakes;
// address staker
mapping(address => Staker ) stakers;
}
event STAKE61(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
address indexed _staker,
uint256 _vote,
uint256 _amount
);
event REDEEM77(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event REDEEMDAOBOUNTY80(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event REDEEMREPUTATION31(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event STATECHANGE55(bytes32 indexed _proposalId, ProposalState _proposalState); //inject NONSTANDARD NAMING
event GPEXECUTEPROPOSAL49(bytes32 indexed _proposalId, ExecutionState _executionState); //inject NONSTANDARD NAMING
event EXPIRATIONCALLBOUNTY13(bytes32 indexed _proposalId, address indexed _beneficiary, uint256 _amount); //inject NONSTANDARD NAMING
mapping(bytes32=>Parameters) public parameters; // A mapping from hashes to parameters
mapping(bytes32=>Proposal) public proposals; // Mapping from the ID of the proposal to the proposal itself.
mapping(bytes32=>uint) public orgBoostedProposalsCnt;
//organizationId => organization
mapping(bytes32 => address ) public organizations;
//organizationId => averageBoostDownstakes
mapping(bytes32 => uint256 ) public averagesDownstakesOfBoosted;
uint256 constant public num_of_choices20 = 2; //inject NONSTANDARD NAMING
uint256 constant public no97 = 2; //inject NONSTANDARD NAMING
uint256 constant public yes52 = 1; //inject NONSTANDARD NAMING
uint256 public proposalsCnt; // Total number of proposals
ierc2016 public stakingToken;
address constant private gen_token_address24 = 0x543Ff227F64Aa17eA132Bf9886cAb5DB55DCAddf; //inject NONSTANDARD NAMING
uint256 constant private max_boosted_proposals66 = 4096; //inject NONSTANDARD NAMING
constructor(ierc2016 _stakingToken) public {
//The GEN token (staking token) address is hard coded in the contract by GEN_TOKEN_ADDRESS .
//This will work for a network which already hosted the GEN token on this address (e.g mainnet).
//If such contract address does not exist in the network (e.g ganache)
//the contract will use the _stakingToken param as the
//staking token address.
if (address(gen_token_address24).ISCONTRACT13()) {
stakingToken = ierc2016(gen_token_address24);
} else {
stakingToken = _stakingToken;
}
}
modifier VOTABLE14(bytes32 _proposalId) { //inject NONSTANDARD NAMING
require(_ISVOTABLE26(_proposalId));
_;
}
function PROPOSE48(uint256, bytes32 _paramsHash, address _proposer, address _organization) //inject NONSTANDARD NAMING
external
returns(bytes32)
{
// solhint-disable-next-line not-rely-on-time
require(now > parameters[_paramsHash].activationTime, "not active yet");
//Check parameters existence.
require(parameters[_paramsHash].queuedVoteRequiredPercentage >= 50);
// Generate a unique ID:
bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt));
proposalsCnt = proposalsCnt.ADD40(1);
// Open proposal:
Proposal memory proposal;
proposal.callbacks = msg.sender;
proposal.organizationId = keccak256(abi.encodePacked(msg.sender, _organization));
proposal.state = ProposalState.Queued;
// solhint-disable-next-line not-rely-on-time
proposal.times[0] = now;//submitted time
proposal.currentBoostedVotePeriodLimit = parameters[_paramsHash].boostedVotePeriodLimit;
proposal.proposer = _proposer;
proposal.winningVote = no97;
proposal.paramsHash = _paramsHash;
if (organizations[proposal.organizationId] == address(0)) {
if (_organization == address(0)) {
organizations[proposal.organizationId] = msg.sender;
} else {
organizations[proposal.organizationId] = _organization;
}
}
//calc dao bounty
uint256 daoBounty =
parameters[_paramsHash].daoBountyConst.MUL16(averagesDownstakesOfBoosted[proposal.organizationId]).DIV25(100);
if (daoBounty < parameters[_paramsHash].minimumDaoBounty) {
proposal.daoBountyRemain = parameters[_paramsHash].minimumDaoBounty;
} else {
proposal.daoBountyRemain = daoBounty;
}
proposal.totalStakes = proposal.daoBountyRemain;
proposals[proposalId] = proposal;
proposals[proposalId].stakes[no97] = proposal.daoBountyRemain;//dao downstake on the proposal
Staker storage staker = proposals[proposalId].stakers[organizations[proposal.organizationId]];
staker.vote = no97;
staker.amount = proposal.daoBountyRemain;
emit NEWPROPOSAL82(proposalId, organizations[proposal.organizationId], num_of_choices20, _proposer, _paramsHash);
return proposalId;
}
function EXECUTEBOOSTED98(bytes32 _proposalId) external returns(uint256 expirationCallBounty) { //inject NONSTANDARD NAMING
Proposal storage proposal = proposals[_proposalId];
require(proposal.state == ProposalState.Boosted);
require(_EXECUTE0(_proposalId), "proposal need to expire");
uint256 expirationCallBountyPercentage =
// solhint-disable-next-line not-rely-on-time
(uint(1).ADD40(now.SUB37(proposal.currentBoostedVotePeriodLimit.ADD40(proposal.times[1])).DIV25(15)));
if (expirationCallBountyPercentage > 100) {
expirationCallBountyPercentage = 100;
}
proposal.expirationCallBountyPercentage = expirationCallBountyPercentage;
expirationCallBounty = expirationCallBountyPercentage.MUL16(proposal.stakes[yes52]).DIV25(100);
require(stakingToken.TRANSFER74(msg.sender, expirationCallBounty), "transfer to msg.sender failed");
emit EXPIRATIONCALLBOUNTY13(_proposalId, msg.sender, expirationCallBounty);
}
function SETPARAMETERS19( //inject NONSTANDARD NAMING
uint[11] calldata _params, //use array here due to stack too deep issue.
address _voteOnBehalf
)
external
returns(bytes32)
{
require(_params[0] <= 100 && _params[0] >= 50, "50 <= queuedVoteRequiredPercentage <= 100");
require(_params[4] <= 16000 && _params[4] > 1000, "1000 < thresholdConst <= 16000");
require(_params[7] <= 100, "votersReputationLossRatio <= 100");
require(_params[2] >= _params[5], "boostedVotePeriodLimit >= quietEndingPeriod");
require(_params[8] > 0, "minimumDaoBounty should be > 0");
require(_params[9] > 0, "daoBountyConst should be > 0");
bytes32 paramsHash = GETPARAMETERSHASH35(_params, _voteOnBehalf);
//set a limit for power for a given alpha to prevent overflow
uint256 limitExponent = 172;//for alpha less or equal 2
uint256 j = 2;
for (uint256 i = 2000; i < 16000; i = i*2) {
if ((_params[4] > i) && (_params[4] <= i*2)) {
limitExponent = limitExponent/j;
break;
}
j++;
}
parameters[paramsHash] = Parameters({
queuedVoteRequiredPercentage: _params[0],
queuedVotePeriodLimit: _params[1],
boostedVotePeriodLimit: _params[2],
preBoostedVotePeriodLimit: _params[3],
thresholdConst:uint216(_params[4]).FRACTION6(uint216(1000)),
limitExponentValue:limitExponent,
quietEndingPeriod: _params[5],
proposingRepReward: _params[6],
votersReputationLossRatio:_params[7],
minimumDaoBounty:_params[8],
daoBountyConst:_params[9],
activationTime:_params[10],
voteOnBehalf:_voteOnBehalf
});
return paramsHash;
}
// solhint-disable-next-line function-max-lines,code-complexity
function REDEEM91(bytes32 _proposalId, address _beneficiary) public returns (uint[3] memory rewards) { //inject NONSTANDARD NAMING
Proposal storage proposal = proposals[_proposalId];
require((proposal.state == ProposalState.Executed)||(proposal.state == ProposalState.ExpiredInQueue),
"Proposal should be Executed or ExpiredInQueue");
Parameters memory params = parameters[proposal.paramsHash];
uint256 lostReputation;
if (proposal.winningVote == yes52) {
lostReputation = proposal.preBoostedVotes[no97];
} else {
lostReputation = proposal.preBoostedVotes[yes52];
}
lostReputation = (lostReputation.MUL16(params.votersReputationLossRatio))/100;
//as staker
Staker storage staker = proposal.stakers[_beneficiary];
if (staker.amount > 0) {
if (proposal.state == ProposalState.ExpiredInQueue) {
//Stakes of a proposal that expires in Queue are sent back to stakers
rewards[0] = staker.amount;
} else if (staker.vote == proposal.winningVote) {
uint256 totalWinningStakes = proposal.stakes[proposal.winningVote];
uint256 totalStakes = proposal.stakes[yes52].ADD40(proposal.stakes[no97]);
if (staker.vote == yes52) {
uint256 _totalStakes =
((totalStakes.MUL16(100 - proposal.expirationCallBountyPercentage))/100) - proposal.daoBounty;
rewards[0] = (staker.amount.MUL16(_totalStakes))/totalWinningStakes;
} else {
rewards[0] = (staker.amount.MUL16(totalStakes))/totalWinningStakes;
if (organizations[proposal.organizationId] == _beneficiary) {
//dao redeem it reward
rewards[0] = rewards[0].SUB37(proposal.daoBounty);
}
}
}
staker.amount = 0;
}
//as voter
Voter storage voter = proposal.voters[_beneficiary];
if ((voter.reputation != 0) && (voter.preBoosted)) {
if (proposal.state == ProposalState.ExpiredInQueue) {
//give back reputation for the voter
rewards[1] = ((voter.reputation.MUL16(params.votersReputationLossRatio))/100);
} else if (proposal.winningVote == voter.vote) {
uint256 preBoostedVotes = proposal.preBoostedVotes[yes52].ADD40(proposal.preBoostedVotes[no97]);
rewards[1] = ((voter.reputation.MUL16(params.votersReputationLossRatio))/100)
.ADD40((voter.reputation.MUL16(lostReputation))/preBoostedVotes);
}
voter.reputation = 0;
}
//as proposer
if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == yes52)&&(proposal.proposer != address(0))) {
rewards[2] = params.proposingRepReward;
proposal.proposer = address(0);
}
if (rewards[0] != 0) {
proposal.totalStakes = proposal.totalStakes.SUB37(rewards[0]);
require(stakingToken.TRANSFER74(_beneficiary, rewards[0]), "transfer to beneficiary failed");
emit REDEEM77(_proposalId, organizations[proposal.organizationId], _beneficiary, rewards[0]);
}
if (rewards[1].ADD40(rewards[2]) != 0) {
votingmachinecallbacksinterface79(proposal.callbacks)
.MINTREPUTATION65(rewards[1].ADD40(rewards[2]), _beneficiary, _proposalId);
emit REDEEMREPUTATION31(
_proposalId,
organizations[proposal.organizationId],
_beneficiary,
rewards[1].ADD40(rewards[2])
);
}
}
function REDEEMDAOBOUNTY7(bytes32 _proposalId, address _beneficiary) //inject NONSTANDARD NAMING
public
returns(uint256 redeemedAmount, uint256 potentialAmount) {
Proposal storage proposal = proposals[_proposalId];
require(proposal.state == ProposalState.Executed);
uint256 totalWinningStakes = proposal.stakes[proposal.winningVote];
Staker storage staker = proposal.stakers[_beneficiary];
if (
(staker.amount4Bounty > 0)&&
(staker.vote == proposal.winningVote)&&
(proposal.winningVote == yes52)&&
(totalWinningStakes != 0)) {
//as staker
potentialAmount = (staker.amount4Bounty * proposal.daoBounty)/totalWinningStakes;
}
if ((potentialAmount != 0)&&
(votingmachinecallbacksinterface79(proposal.callbacks)
.BALANCEOFSTAKINGTOKEN17(stakingToken, _proposalId) >= potentialAmount)) {
staker.amount4Bounty = 0;
proposal.daoBountyRemain = proposal.daoBountyRemain.SUB37(potentialAmount);
require(
votingmachinecallbacksinterface79(proposal.callbacks)
.STAKINGTOKENTRANSFER23(stakingToken, _beneficiary, potentialAmount, _proposalId));
redeemedAmount = potentialAmount;
emit REDEEMDAOBOUNTY80(_proposalId, organizations[proposal.organizationId], _beneficiary, redeemedAmount);
}
}
function SHOULDBOOST32(bytes32 _proposalId) public view returns(bool) { //inject NONSTANDARD NAMING
Proposal memory proposal = proposals[_proposalId];
return (_SCORE65(_proposalId) > THRESHOLD35(proposal.paramsHash, proposal.organizationId));
}
function THRESHOLD35(bytes32 _paramsHash, bytes32 _organizationId) public view returns(uint256) { //inject NONSTANDARD NAMING
uint256 power = orgBoostedProposalsCnt[_organizationId];
Parameters storage params = parameters[_paramsHash];
if (power > params.limitExponentValue) {
power = params.limitExponentValue;
}
return params.thresholdConst.POW66(power);
}
function GETPARAMETERSHASH35( //inject NONSTANDARD NAMING
uint[11] memory _params,//use array here due to stack too deep issue.
address _voteOnBehalf
)
public
pure
returns(bytes32)
{
//double call to keccak256 to avoid deep stack issue when call with too many params.
return keccak256(
abi.encodePacked(
keccak256(
abi.encodePacked(
_params[0],
_params[1],
_params[2],
_params[3],
_params[4],
_params[5],
_params[6],
_params[7],
_params[8],
_params[9],
_params[10])
),
_voteOnBehalf
));
}
// solhint-disable-next-line function-max-lines,code-complexity
function _EXECUTE0(bytes32 _proposalId) internal VOTABLE14(_proposalId) returns(bool) { //inject NONSTANDARD NAMING
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
Proposal memory tmpProposal = proposal;
uint256 totalReputation =
votingmachinecallbacksinterface79(proposal.callbacks).GETTOTALREPUTATIONSUPPLY93(_proposalId);
//first divide by 100 to prevent overflow
uint256 executionBar = (totalReputation/100) * params.queuedVoteRequiredPercentage;
ExecutionState executionState = ExecutionState.None;
uint256 averageDownstakesOfBoosted;
uint256 confidenceThreshold;
if (proposal.votes[proposal.winningVote] > executionBar) {
// someone crossed the absolute vote execution bar.
if (proposal.state == ProposalState.Queued) {
executionState = ExecutionState.QueueBarCrossed;
} else if (proposal.state == ProposalState.PreBoosted) {
executionState = ExecutionState.PreBoostedBarCrossed;
} else {
executionState = ExecutionState.BoostedBarCrossed;
}
proposal.state = ProposalState.Executed;
} else {
if (proposal.state == ProposalState.Queued) {
// solhint-disable-next-line not-rely-on-time
if ((now - proposal.times[0]) >= params.queuedVotePeriodLimit) {
proposal.state = ProposalState.ExpiredInQueue;
proposal.winningVote = no97;
executionState = ExecutionState.QueueTimeOut;
} else {
confidenceThreshold = THRESHOLD35(proposal.paramsHash, proposal.organizationId);
if (_SCORE65(_proposalId) > confidenceThreshold) {
//change proposal mode to PreBoosted mode.
proposal.state = ProposalState.PreBoosted;
// solhint-disable-next-line not-rely-on-time
proposal.times[2] = now;
proposal.confidenceThreshold = confidenceThreshold;
}
}
}
if (proposal.state == ProposalState.PreBoosted) {
confidenceThreshold = THRESHOLD35(proposal.paramsHash, proposal.organizationId);
// solhint-disable-next-line not-rely-on-time
if ((now - proposal.times[2]) >= params.preBoostedVotePeriodLimit) {
if ((_SCORE65(_proposalId) > confidenceThreshold) &&
(orgBoostedProposalsCnt[proposal.organizationId] < max_boosted_proposals66)) {
//change proposal mode to Boosted mode.
proposal.state = ProposalState.Boosted;
// solhint-disable-next-line not-rely-on-time
proposal.times[1] = now;
orgBoostedProposalsCnt[proposal.organizationId]++;
//add a value to average -> average = average + ((value - average) / nbValues)
averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId];
// solium-disable-next-line indentation
averagesDownstakesOfBoosted[proposal.organizationId] =
uint256(int256(averageDownstakesOfBoosted) +
((int256(proposal.stakes[no97])-int256(averageDownstakesOfBoosted))/
int256(orgBoostedProposalsCnt[proposal.organizationId])));
}
} else { //check the Confidence level is stable
uint256 proposalScore = _SCORE65(_proposalId);
if (proposalScore <= proposal.confidenceThreshold.MIN92(confidenceThreshold)) {
proposal.state = ProposalState.Queued;
} else if (proposal.confidenceThreshold > proposalScore) {
proposal.confidenceThreshold = confidenceThreshold;
}
}
}
}
if ((proposal.state == ProposalState.Boosted) ||
(proposal.state == ProposalState.QuietEndingPeriod)) {
// solhint-disable-next-line not-rely-on-time
if ((now - proposal.times[1]) >= proposal.currentBoostedVotePeriodLimit) {
proposal.state = ProposalState.Executed;
executionState = ExecutionState.BoostedTimeOut;
}
}
if (executionState != ExecutionState.None) {
if ((executionState == ExecutionState.BoostedTimeOut) ||
(executionState == ExecutionState.BoostedBarCrossed)) {
orgBoostedProposalsCnt[tmpProposal.organizationId] =
orgBoostedProposalsCnt[tmpProposal.organizationId].SUB37(1);
//remove a value from average = ((average * nbValues) - value) / (nbValues - 1);
uint256 boostedProposals = orgBoostedProposalsCnt[tmpProposal.organizationId];
if (boostedProposals == 0) {
averagesDownstakesOfBoosted[proposal.organizationId] = 0;
} else {
averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId];
averagesDownstakesOfBoosted[proposal.organizationId] =
(averageDownstakesOfBoosted.MUL16(boostedProposals+1).SUB37(proposal.stakes[no97]))/boostedProposals;
}
}
emit EXECUTEPROPOSAL67(
_proposalId,
organizations[proposal.organizationId],
proposal.winningVote,
totalReputation
);
emit GPEXECUTEPROPOSAL49(_proposalId, executionState);
proposalexecuteinterface9(proposal.callbacks).EXECUTEPROPOSAL85(_proposalId, int(proposal.winningVote));
proposal.daoBounty = proposal.daoBountyRemain;
}
if (tmpProposal.state != proposal.state) {
emit STATECHANGE55(_proposalId, proposal.state);
}
return (executionState != ExecutionState.None);
}
function _STAKE17(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _staker) internal returns(bool) { //inject NONSTANDARD NAMING
// 0 is not a valid vote.
require(_vote <= num_of_choices20 && _vote > 0, "wrong vote value");
require(_amount > 0, "staking amount should be >0");
if (_EXECUTE0(_proposalId)) {
return true;
}
Proposal storage proposal = proposals[_proposalId];
if ((proposal.state != ProposalState.PreBoosted) &&
(proposal.state != ProposalState.Queued)) {
return false;
}
// enable to increase stake only on the previous stake vote
Staker storage staker = proposal.stakers[_staker];
if ((staker.amount > 0) && (staker.vote != _vote)) {
return false;
}
uint256 amount = _amount;
require(stakingToken.TRANSFERFROM94(_staker, address(this), amount), "fail transfer from staker");
proposal.totalStakes = proposal.totalStakes.ADD40(amount); //update totalRedeemableStakes
staker.amount = staker.amount.ADD40(amount);
//This is to prevent average downstakes calculation overflow
//Note that any how GEN cap is 100000000 ether.
require(staker.amount <= 0x100000000000000000000000000000000, "staking amount is too high");
require(proposal.totalStakes <= 0x100000000000000000000000000000000, "total stakes is too high");
if (_vote == yes52) {
staker.amount4Bounty = staker.amount4Bounty.ADD40(amount);
}
staker.vote = _vote;
proposal.stakes[_vote] = amount.ADD40(proposal.stakes[_vote]);
emit STAKE61(_proposalId, organizations[proposal.organizationId], _staker, _vote, _amount);
return _EXECUTE0(_proposalId);
}
// solhint-disable-next-line function-max-lines,code-complexity
function INTERNALVOTE44(bytes32 _proposalId, address _voter, uint256 _vote, uint256 _rep) internal returns(bool) { //inject NONSTANDARD NAMING
require(_vote <= num_of_choices20 && _vote > 0, "0 < _vote <= 2");
if (_EXECUTE0(_proposalId)) {
return true;
}
Parameters memory params = parameters[proposals[_proposalId].paramsHash];
Proposal storage proposal = proposals[_proposalId];
// Check voter has enough reputation:
uint256 reputation = votingmachinecallbacksinterface79(proposal.callbacks).REPUTATIONOF100(_voter, _proposalId);
require(reputation > 0, "_voter must have reputation");
require(reputation >= _rep, "reputation >= _rep");
uint256 rep = _rep;
if (rep == 0) {
rep = reputation;
}
// If this voter has already voted, return false.
if (proposal.voters[_voter].reputation != 0) {
return false;
}
// The voting itself:
proposal.votes[_vote] = rep.ADD40(proposal.votes[_vote]);
//check if the current winningVote changed or there is a tie.
//for the case there is a tie the current winningVote set to NO.
if ((proposal.votes[_vote] > proposal.votes[proposal.winningVote]) ||
((proposal.votes[no97] == proposal.votes[proposal.winningVote]) &&
proposal.winningVote == yes52)) {
if (proposal.state == ProposalState.Boosted &&
// solhint-disable-next-line not-rely-on-time
((now - proposal.times[1]) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod))||
proposal.state == ProposalState.QuietEndingPeriod) {
//quietEndingPeriod
if (proposal.state != ProposalState.QuietEndingPeriod) {
proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod;
proposal.state = ProposalState.QuietEndingPeriod;
}
// solhint-disable-next-line not-rely-on-time
proposal.times[1] = now;
}
proposal.winningVote = _vote;
}
proposal.voters[_voter] = Voter({
reputation: rep,
vote: _vote,
preBoosted:((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued))
});
if ((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) {
proposal.preBoostedVotes[_vote] = rep.ADD40(proposal.preBoostedVotes[_vote]);
uint256 reputationDeposit = (params.votersReputationLossRatio.MUL16(rep))/100;
votingmachinecallbacksinterface79(proposal.callbacks).BURNREPUTATION8(reputationDeposit, _voter, _proposalId);
}
emit VOTEPROPOSAL81(_proposalId, organizations[proposal.organizationId], _voter, _vote, rep);
return _EXECUTE0(_proposalId);
}
function _SCORE65(bytes32 _proposalId) internal view returns(uint256) { //inject NONSTANDARD NAMING
Proposal storage proposal = proposals[_proposalId];
//proposal.stakes[NO] cannot be zero as the dao downstake > 0 for each proposal.
return proposal.stakes[yes52]/proposal.stakes[no97];
}
function _ISVOTABLE26(bytes32 _proposalId) internal view returns(bool) { //inject NONSTANDARD NAMING
ProposalState pState = proposals[_proposalId].state;
return ((pState == ProposalState.PreBoosted)||
(pState == ProposalState.Boosted)||
(pState == ProposalState.QuietEndingPeriod)||
(pState == ProposalState.Queued)
);
}
}
// File: @daostack/infra/contracts/votingMachines/GenesisProtocol.sol
contract genesisprotocol36 is intvoteinterface31, genesisprotocollogic61 { //inject NONSTANDARD NAMING
using ecdsa86 for bytes32;
// Digest describing the data the user signs according EIP 712.
// Needs to match what is passed to Metamask.
bytes32 public constant delegation_hash_eip71264 = //inject NONSTANDARD NAMING
keccak256(abi.encodePacked(
"address GenesisProtocolAddress",
"bytes32 ProposalId",
"uint256 Vote",
"uint256 AmountToStake",
"uint256 Nonce"
));
mapping(address=>uint256) public stakesNonce; //stakes Nonce
constructor(ierc2016 _stakingToken)
public
// solhint-disable-next-line no-empty-blocks
genesisprotocollogic61(_stakingToken) {
}
function STAKE3(bytes32 _proposalId, uint256 _vote, uint256 _amount) external returns(bool) { //inject NONSTANDARD NAMING
return _STAKE17(_proposalId, _vote, _amount, msg.sender);
}
function STAKEWITHSIGNATURE10( //inject NONSTANDARD NAMING
bytes32 _proposalId,
uint256 _vote,
uint256 _amount,
uint256 _nonce,
uint256 _signatureType,
bytes calldata _signature
)
external
returns(bool)
{
// Recreate the digest the user signed
bytes32 delegationDigest;
if (_signatureType == 2) {
delegationDigest = keccak256(
abi.encodePacked(
delegation_hash_eip71264, keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)
)
)
);
} else {
delegationDigest = keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)
).TOETHSIGNEDMESSAGEHASH91();
}
address staker = delegationDigest.RECOVER59(_signature);
//a garbage staker address due to wrong signature will revert due to lack of approval and funds.
require(staker != address(0), "staker address cannot be 0");
require(stakesNonce[staker] == _nonce);
stakesNonce[staker] = stakesNonce[staker].ADD40(1);
return _STAKE17(_proposalId, _vote, _amount, staker);
}
function VOTE79(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _voter) //inject NONSTANDARD NAMING
external
VOTABLE14(_proposalId)
returns(bool) {
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
address voter;
if (params.voteOnBehalf != address(0)) {
require(msg.sender == params.voteOnBehalf);
voter = _voter;
} else {
voter = msg.sender;
}
return INTERNALVOTE44(_proposalId, voter, _vote, _amount);
}
function CANCELVOTE62(bytes32 _proposalId) external VOTABLE14(_proposalId) { //inject NONSTANDARD NAMING
//this is not allowed
return;
}
function EXECUTE34(bytes32 _proposalId) external VOTABLE14(_proposalId) returns(bool) { //inject NONSTANDARD NAMING
return _EXECUTE0(_proposalId);
}
function GETNUMBEROFCHOICES23(bytes32) external view returns(uint256) { //inject NONSTANDARD NAMING
return num_of_choices20;
}
function GETPROPOSALTIMES43(bytes32 _proposalId) external view returns(uint[3] memory times) { //inject NONSTANDARD NAMING
return proposals[_proposalId].times;
}
function VOTEINFO83(bytes32 _proposalId, address _voter) external view returns(uint, uint) { //inject NONSTANDARD NAMING
Voter memory voter = proposals[_proposalId].voters[_voter];
return (voter.vote, voter.reputation);
}
function VOTESTATUS55(bytes32 _proposalId, uint256 _choice) external view returns(uint256) { //inject NONSTANDARD NAMING
return proposals[_proposalId].votes[_choice];
}
function ISVOTABLE72(bytes32 _proposalId) external view returns(bool) { //inject NONSTANDARD NAMING
return _ISVOTABLE26(_proposalId);
}
function PROPOSALSTATUS51(bytes32 _proposalId) external view returns(uint256, uint256, uint256, uint256) { //inject NONSTANDARD NAMING
return (
proposals[_proposalId].preBoostedVotes[yes52],
proposals[_proposalId].preBoostedVotes[no97],
proposals[_proposalId].stakes[yes52],
proposals[_proposalId].stakes[no97]
);
}
function GETPROPOSALORGANIZATION83(bytes32 _proposalId) external view returns(bytes32) { //inject NONSTANDARD NAMING
return (proposals[_proposalId].organizationId);
}
function GETSTAKER73(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) { //inject NONSTANDARD NAMING
return (proposals[_proposalId].stakers[_staker].vote, proposals[_proposalId].stakers[_staker].amount);
}
function VOTESTAKE72(bytes32 _proposalId, uint256 _vote) external view returns(uint256) { //inject NONSTANDARD NAMING
return proposals[_proposalId].stakes[_vote];
}
function WINNINGVOTE73(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING
return proposals[_proposalId].winningVote;
}
function STATE40(bytes32 _proposalId) external view returns(ProposalState) { //inject NONSTANDARD NAMING
return proposals[_proposalId].state;
}
function ISABSTAINALLOW86() external pure returns(bool) { //inject NONSTANDARD NAMING
return false;
}
function GETALLOWEDRANGEOFCHOICES7() external pure returns(uint256 min, uint256 max) { //inject NONSTANDARD NAMING
return (yes52, no97);
}
function SCORE19(bytes32 _proposalId) public view returns(uint256) { //inject NONSTANDARD NAMING
return _SCORE65(_proposalId);
}
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/votingMachines/VotingMachineCallbacks.sol
contract votingmachinecallbacks93 is votingmachinecallbacksinterface79 { //inject NONSTANDARD NAMING
struct ProposalInfo {
uint256 blockNumber; // the proposal's block number
avatar70 avatar; // the proposal's avatar
address votingMachine;
}
modifier ONLYVOTINGMACHINE57(bytes32 _proposalId) { //inject NONSTANDARD NAMING
require(msg.sender == proposalsInfo[_proposalId].votingMachine, "only VotingMachine");
_;
}
//proposalId -> ProposalInfo
mapping(bytes32 => ProposalInfo ) public proposalsInfo;
function MINTREPUTATION65(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING
external
ONLYVOTINGMACHINE57(_proposalId)
returns(bool)
{
avatar70 avatar = proposalsInfo[_proposalId].avatar;
if (avatar == avatar70(0)) {
return false;
}
return controllerinterface59(avatar.OWNER8()).MINTREPUTATION65(_amount, _beneficiary, address(avatar));
}
function BURNREPUTATION8(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING
external
ONLYVOTINGMACHINE57(_proposalId)
returns(bool)
{
avatar70 avatar = proposalsInfo[_proposalId].avatar;
if (avatar == avatar70(0)) {
return false;
}
return controllerinterface59(avatar.OWNER8()).BURNREPUTATION8(_amount, _beneficiary, address(avatar));
}
function STAKINGTOKENTRANSFER23( //inject NONSTANDARD NAMING
ierc2016 _stakingToken,
address _beneficiary,
uint256 _amount,
bytes32 _proposalId)
external
ONLYVOTINGMACHINE57(_proposalId)
returns(bool)
{
avatar70 avatar = proposalsInfo[_proposalId].avatar;
if (avatar == avatar70(0)) {
return false;
}
return controllerinterface59(avatar.OWNER8()).EXTERNALTOKENTRANSFER67(_stakingToken, _beneficiary, _amount, avatar);
}
function BALANCEOFSTAKINGTOKEN17(ierc2016 _stakingToken, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING
avatar70 avatar = proposalsInfo[_proposalId].avatar;
if (proposalsInfo[_proposalId].avatar == avatar70(0)) {
return 0;
}
return _stakingToken.BALANCEOF62(address(avatar));
}
function GETTOTALREPUTATIONSUPPLY93(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING
ProposalInfo memory proposal = proposalsInfo[_proposalId];
if (proposal.avatar == avatar70(0)) {
return 0;
}
return proposal.avatar.nativeReputation().TOTALSUPPLYAT94(proposal.blockNumber);
}
function REPUTATIONOF100(address _owner, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING
ProposalInfo memory proposal = proposalsInfo[_proposalId];
if (proposal.avatar == avatar70(0)) {
return 0;
}
return proposal.avatar.nativeReputation().BALANCEOFAT72(_owner, proposal.blockNumber);
}
}
// File: contracts/universalSchemes/GenericScheme.sol
contract genericscheme3 is universalscheme48, votingmachinecallbacks93, proposalexecuteinterface9 { //inject NONSTANDARD NAMING
event NEWCALLPROPOSAL18( //inject NONSTANDARD NAMING
address indexed _avatar,
bytes32 indexed _proposalId,
bytes _callData,
string _descriptionHash
);
event PROPOSALEXECUTED2( //inject NONSTANDARD NAMING
address indexed _avatar,
bytes32 indexed _proposalId,
bytes _genericCallReturnValue
);
event PROPOSALEXECUTEDBYVOTINGMACHINE53( //inject NONSTANDARD NAMING
address indexed _avatar,
bytes32 indexed _proposalId,
int256 _param
);
event PROPOSALDELETED34(address indexed _avatar, bytes32 indexed _proposalId); //inject NONSTANDARD NAMING
// Details of a voting proposal:
struct CallProposal {
bytes callData;
bool exist;
bool passed;
}
// A mapping from the organization (Avatar) address to the saved data of the organization:
mapping(address=>mapping(bytes32=>CallProposal)) public organizationsProposals;
struct Parameters {
intvoteinterface31 intVote;
bytes32 voteParams;
address contractToCall;
}
// A mapping from hashes to parameters (use to store a particular configuration on the controller)
mapping(bytes32=>Parameters) public parameters;
function EXECUTEPROPOSAL85(bytes32 _proposalId, int256 _decision) //inject NONSTANDARD NAMING
external
ONLYVOTINGMACHINE57(_proposalId)
returns(bool) {
avatar70 avatar = proposalsInfo[_proposalId].avatar;
CallProposal storage proposal = organizationsProposals[address(avatar)][_proposalId];
require(proposal.exist, "must be a live proposal");
require(proposal.passed == false, "cannot execute twice");
if (_decision == 1) {
proposal.passed = true;
EXECUTE34(_proposalId);
} else {
delete organizationsProposals[address(avatar)][_proposalId];
emit PROPOSALDELETED34(address(avatar), _proposalId);
}
emit PROPOSALEXECUTEDBYVOTINGMACHINE53(address(avatar), _proposalId, _decision);
return true;
}
function EXECUTE34(bytes32 _proposalId) public { //inject NONSTANDARD NAMING
avatar70 avatar = proposalsInfo[_proposalId].avatar;
Parameters memory params = parameters[GETPARAMETERSFROMCONTROLLER72(avatar)];
CallProposal storage proposal = organizationsProposals[address(avatar)][_proposalId];
require(proposal.exist, "must be a live proposal");
require(proposal.passed, "proposal must passed by voting machine");
proposal.exist = false;
bytes memory genericCallReturnValue;
bool success;
controllerinterface59 controller = controllerinterface59(avatar70(avatar).OWNER8());
(success, genericCallReturnValue) = controller.GENERICCALL24(params.contractToCall, proposal.callData, avatar);
if (success) {
delete organizationsProposals[address(avatar)][_proposalId];
emit PROPOSALDELETED34(address(avatar), _proposalId);
emit PROPOSALEXECUTED2(address(avatar), _proposalId, genericCallReturnValue);
} else {
proposal.exist = true;
}
}
function SETPARAMETERS19( //inject NONSTANDARD NAMING
bytes32 _voteParams,
intvoteinterface31 _intVote,
address _contractToCall
) public returns(bytes32)
{
bytes32 paramsHash = GETPARAMETERSHASH35(_voteParams, _intVote, _contractToCall);
parameters[paramsHash].voteParams = _voteParams;
parameters[paramsHash].intVote = _intVote;
parameters[paramsHash].contractToCall = _contractToCall;
return paramsHash;
}
function GETPARAMETERSHASH35( //inject NONSTANDARD NAMING
bytes32 _voteParams,
intvoteinterface31 _intVote,
address _contractToCall
) public pure returns(bytes32)
{
return keccak256(abi.encodePacked(_voteParams, _intVote, _contractToCall));
}
function PROPOSECALL64(avatar70 _avatar, bytes memory _callData, string memory _descriptionHash) //inject NONSTANDARD NAMING
public
returns(bytes32)
{
Parameters memory params = parameters[GETPARAMETERSFROMCONTROLLER72(_avatar)];
intvoteinterface31 intVote = params.intVote;
bytes32 proposalId = intVote.PROPOSE48(2, params.voteParams, msg.sender, address(_avatar));
organizationsProposals[address(_avatar)][proposalId] = CallProposal({
callData: _callData,
exist: true,
passed: false
});
proposalsInfo[proposalId] = ProposalInfo({
blockNumber:block.number,
avatar:_avatar,
votingMachine:address(params.intVote)
});
emit NEWCALLPROPOSAL18(address(_avatar), proposalId, _callData, _descriptionHash);
return proposalId;
}
function GETCONTRACTTOCALL27(avatar70 _avatar) public view returns(address) { //inject NONSTANDARD NAMING
return parameters[GETPARAMETERSFROMCONTROLLER72(_avatar)].contractToCall;
}
} | inject NONSTANDARD NAMING
| function WINNINGVOTE73(bytes32 _proposalId) external view returns(uint256) { | 12,775,979 | [
1,
4625,
348,
7953,
560,
30,
4590,
18708,
882,
18264,
423,
2192,
1360,
203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
678,
706,
15870,
16169,
1448,
9036,
12,
3890,
1578,
389,
685,
8016,
548,
13,
3903,
1476,
1135,
12,
11890,
5034,
13,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x025122f28C47BBa43371f562420137d01aDE0C08/sources/project_/contracts/KFGDAO.sol | cannot burn more than 30% of token supply in pool | function ManualBurning(uint256 _amount) private {
if (_amount > 0 && _amount <= (balanceOf(uniswapV2Pair) * 30) / 100) {
_burn(uniswapV2Pair, _amount);
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
}
}
| 7,081,594 | [
1,
4625,
348,
7953,
560,
30,
225,
2780,
18305,
1898,
2353,
5196,
9,
434,
1147,
14467,
316,
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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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
8660,
1462,
38,
321,
310,
12,
11890,
5034,
389,
8949,
13,
3238,
288,
203,
3639,
309,
261,
67,
8949,
405,
374,
597,
389,
8949,
1648,
261,
12296,
951,
12,
318,
291,
91,
438,
58,
22,
4154,
13,
380,
5196,
13,
342,
2130,
13,
288,
203,
5411,
389,
70,
321,
12,
318,
291,
91,
438,
58,
22,
4154,
16,
389,
8949,
1769,
203,
5411,
467,
984,
291,
91,
438,
58,
22,
4154,
3082,
273,
467,
984,
291,
91,
438,
58,
22,
4154,
12,
318,
291,
91,
438,
58,
22,
4154,
1769,
203,
5411,
3082,
18,
8389,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/11155111/0x7309a1385A6db5069b4a490c4fd50Be219a6973c/sources/project:/contracts/USDTStakingV1.sol | Calculate Percentage Check if user already withdrawn reward if (timeToCheck > stakeInfo.endTime) { calculate reward for all available tokens. Check if token is set as reward set reward token and balance | function claimableReward(
address _user
) public view returns (address[] memory, uint256[] memory, uint256 i) {
User storage user = userStakes[_user];
require(user.stakesCount != 0, "Stakes not found!");
uint256 _tokensCount = rewardManager.totalTokens();
address[] memory tokens = new address[](_tokensCount);
uint256[] memory balances = new uint256[](_tokensCount);
(uint256 stakedAmount, , ) = calculateTotalStakedInfo(_user);
uint256 stakePercentage = stakedAmount.mul(PERCENT_DIVIDER).div(
usdtToken.balanceOf(address(this))
);
for (
uint256 k = user.lastWithdrawnIndex + 1;
k <= user.stakesCount;
k++
) {
Stake memory stakeInfo = user.stakes[k];
uint256 _tokenIndex = 0;
uint256 timeToCheck = stakeInfo.unstakedAt != 0
? block.timestamp
: stakeInfo.unstakedAt;
for (uint256 j = 0; j < _tokensCount; j++) {
address rewardToken = rewardManager.rewardToken(j);
if (rewardManager.isRewardToken(rewardToken)) {
uint256 availableReward = IERC20Upgradeable(rewardToken)
.balanceOf(address(rewardManager));
uint256 _claimableReward = availableReward
.mul(stakePercentage)
.div(PERCENT_DIVIDER);
balances[_tokenIndex] += _claimableReward;
if (tokens[_tokenIndex] == address(0)) {
tokens[_tokenIndex] = rewardToken;
}
_tokenIndex++;
}
}
}
return (tokens, balances, i);
}
| 3,786,797 | [
1,
4625,
348,
7953,
560,
30,
225,
9029,
21198,
410,
2073,
309,
729,
1818,
598,
9446,
82,
19890,
309,
261,
957,
18126,
405,
384,
911,
966,
18,
409,
950,
13,
288,
4604,
19890,
364,
777,
2319,
2430,
18,
2073,
309,
1147,
353,
444,
487,
19890,
444,
19890,
1147,
471,
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,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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7516,
429,
17631,
1060,
12,
203,
3639,
1758,
389,
1355,
203,
565,
262,
1071,
1476,
1135,
261,
2867,
8526,
3778,
16,
2254,
5034,
8526,
3778,
16,
2254,
5034,
277,
13,
288,
203,
3639,
2177,
2502,
729,
273,
729,
510,
3223,
63,
67,
1355,
15533,
203,
3639,
2583,
12,
1355,
18,
334,
3223,
1380,
480,
374,
16,
315,
510,
3223,
486,
1392,
4442,
1769,
203,
3639,
2254,
5034,
389,
7860,
1380,
273,
19890,
1318,
18,
4963,
5157,
5621,
203,
3639,
1758,
8526,
3778,
2430,
273,
394,
1758,
8526,
24899,
7860,
1380,
1769,
203,
3639,
2254,
5034,
8526,
3778,
324,
26488,
273,
394,
2254,
5034,
8526,
24899,
7860,
1380,
1769,
203,
203,
3639,
261,
11890,
5034,
384,
9477,
6275,
16,
269,
262,
273,
4604,
5269,
510,
9477,
966,
24899,
1355,
1769,
203,
3639,
2254,
5034,
384,
911,
16397,
273,
384,
9477,
6275,
18,
16411,
12,
3194,
19666,
67,
2565,
20059,
2934,
2892,
12,
203,
5411,
584,
7510,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
203,
3639,
11272,
203,
3639,
364,
261,
203,
5411,
2254,
5034,
417,
273,
729,
18,
2722,
1190,
9446,
82,
1016,
397,
404,
31,
203,
5411,
417,
1648,
729,
18,
334,
3223,
1380,
31,
203,
5411,
417,
9904,
203,
3639,
262,
288,
203,
5411,
934,
911,
3778,
384,
911,
966,
273,
729,
18,
334,
3223,
63,
79,
15533,
203,
203,
5411,
2254,
5034,
389,
2316,
1016,
273,
374,
31,
203,
5411,
2254,
5034,
813,
18126,
273,
384,
911,
966,
18,
23412,
9477,
861,
480,
374,
203,
7734,
692,
1203,
18,
5508,
203,
7734,
294,
384,
911,
966,
18,
23412,
9477,
861,
31,
203,
5411,
364,
261,
11890,
5034,
525,
273,
374,
31,
525,
411,
389,
7860,
1380,
31,
525,
27245,
288,
203,
7734,
1758,
19890,
1345,
273,
19890,
1318,
18,
266,
2913,
1345,
12,
78,
1769,
203,
7734,
309,
261,
266,
2913,
1318,
18,
291,
17631,
1060,
1345,
12,
266,
2913,
1345,
3719,
288,
203,
10792,
2254,
5034,
2319,
17631,
1060,
273,
467,
654,
39,
3462,
10784,
429,
12,
266,
2913,
1345,
13,
203,
13491,
263,
12296,
951,
12,
2867,
12,
266,
2913,
1318,
10019,
203,
203,
10792,
2254,
5034,
389,
14784,
429,
17631,
1060,
273,
2319,
17631,
1060,
203,
13491,
263,
16411,
12,
334,
911,
16397,
13,
203,
13491,
263,
2892,
12,
3194,
19666,
67,
2565,
20059,
1769,
203,
10792,
324,
26488,
63,
67,
2316,
1016,
65,
1011,
389,
14784,
429,
17631,
1060,
31,
203,
10792,
309,
261,
7860,
63,
67,
2316,
1016,
65,
422,
1758,
12,
20,
3719,
288,
203,
13491,
2430,
63,
67,
2316,
1016,
65,
273,
19890,
1345,
31,
203,
10792,
289,
203,
10792,
389,
2316,
1016,
9904,
31,
203,
7734,
289,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
327,
261,
7860,
16,
324,
26488,
16,
277,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/4/0x64fD3aea4Df3b76348a8cC9F2A18930fD6927738/sources/RAYv2.sol | = portfolioNav * redeemTokens / raised
| uint amountToRedeem = portfolioNav.mul(redeemTokens).div(raised); | 8,750,747 | [
1,
4625,
348,
7953,
560,
30,
225,
273,
19933,
12599,
380,
283,
24903,
5157,
342,
11531,
203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3844,
774,
426,
24903,
273,
19933,
12599,
18,
16411,
12,
266,
24903,
5157,
2934,
2892,
12,
354,
5918,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/11155111/0x71fc03eAf2490dc4ADA14c293c69357a1425426c/sources/src/ERC5289Library.sol | require( false, "signDocument : dont use this function" ); | function signDocument( address signer, uint16 documentId) public {
emit SignedWrongCall( msg.sender, signer, documentId );
}
| 3,797,714 | [
1,
4625,
348,
7953,
560,
30,
2583,
12,
629,
16,
315,
2977,
2519,
294,
14046,
999,
333,
445,
6,
11272,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1573,
2519,
12,
1758,
10363,
16,
2254,
2313,
28573,
13,
1071,
288,
203,
3639,
3626,
16724,
13634,
1477,
12,
1234,
18,
15330,
16,
10363,
16,
28573,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x0D91892FB500100ca665C05980a3649FF5cD865A/sources/Ownable.sol | * @dev Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner./ | function transferOwnership(address newOwner) external virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| 2,703,478 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
5206,
2604,
18881,
23178,
434,
326,
6835,
358,
279,
394,
2236,
21863,
2704,
5541,
68,
2934,
4480,
1338,
506,
2566,
635,
326,
783,
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,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5460,
12565,
12,
2867,
394,
5541,
13,
3903,
5024,
1338,
5541,
288,
203,
3639,
2583,
12,
203,
5411,
394,
5541,
480,
1758,
12,
20,
3631,
203,
5411,
315,
5460,
429,
30,
394,
3410,
353,
326,
3634,
1758,
6,
203,
3639,
11272,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
24899,
8443,
16,
394,
5541,
1769,
203,
3639,
389,
8443,
273,
394,
5541,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-08-14
*/
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
interface ERC20 {
function transferFrom(address from, address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns(bool);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Ethrim is ERC20 {
using SafeMath for uint256;
address public owner;
//1 token = 0.01 eth
uint256 public tokenCost = 0.01 ether;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply = 1e9* 10**18;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
constructor () public {
symbol = "ETRM";
name = "Ethrim";
decimals = 18;
owner = msg.sender;
balances[owner] = totalSupply;
}
modifier onlyOwner() {
require(msg.sender == owner, "Only owner");
_;
}
/**
* @dev To change burnt Address
* @param _newOwner New owner address
*/
function changeOwner(address _newOwner) public onlyOwner returns(bool) {
require(_newOwner != address(0), "Invalid Address");
owner = _newOwner;
uint256 _value = balances[msg.sender];
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_newOwner] = balances[_newOwner].add(_value);
//minting total supply tokens
return true;
}
function getAmountOfToken(uint256 amount) public view returns (uint256) {
uint256 tokenValue = (amount.mul(10 ** 18)).div(tokenCost);
return tokenValue;
}
/**
* @dev Check balance of the holder
* @param _owner Token holder address
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
/**
* @dev Transfer token to specified address
* @param _to Receiver address
* @param _value Amount of the tokens
*/
function transfer(address _to, uint256 _value) public override returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from The holder address
* @param _to The Receiver address
* @param _value the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool){
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve respective tokens for spender
* @param _spender Spender address
* @param _value Amount of tokens to be allowed
*/
function approve(address _spender, uint256 _value) public override returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev To view approved balance
* @param _owner Holder address
* @param _spender Spender address
*/
function allowance(address _owner, address _spender) public override view returns (uint256) {
return allowed[_owner][_spender];
}
function mint(uint256 _tokens) public returns (bool) {
balances[owner] = balances[owner].add(_tokens);
totalSupply = totalSupply.add(_tokens);
return true;
}
}
contract Referral {
using SafeMath for uint256;
//user structure
struct UserStruct {
bool isExist;
//unique id
uint256 id;
//person who referred unique id
uint256 referrerID;
//user current level
uint256 currentLevel;
//total eraning for user
uint256 totalEarningEth;
//persons referred
address[] referral;
//time for every level
uint256 levelExpiresAt;
}
//address to tarnsfer eth/2
address payable public ownerAddress1;
//address to tarnsfer eth/2
address payable public ownerAddress2;
//unique id for every user
uint256 public last_uid = 0;
//token variable
Ethrim public ETRM;
//map user by their unique trust wallet address
mapping(address => UserStruct) public users;
//users trust wallet address corresponding to unique id
mapping(uint256 => address) public userAddresses;
/**
* @dev View referrals
*/
function viewUserReferral(address _userAddress) external view returns (address[] memory) {
return users[_userAddress].referral;
}
}
contract ProjectEthrim {
using SafeMath for uint256;
//user structure
struct UserStruct {
bool isExist;
//unique id
uint256 id;
//person who referred unique id
uint256 referrerID;
//user current level
uint256 currentLevel;
//total eraning for user
uint256 totalEarningEth;
//persons referred
address[] referral;
//time for every level
uint256 levelExpiresAt;
}
//levelInecntives
struct incentiveStruct {
uint256 directNumerator;
uint256 inDirectNumerator;
}
//owner who deploys contracts
address public owner;
//address to tarnsfer eth/2
address payable public ownerAddress1;
//address to tarnsfer eth/2
address payable public ownerAddress2;
//unique id for every user
uint256 public last_uid;
//time limit for each level
uint256 public PERIOD_LENGTH = 60 days;
//no of users in each level
uint256 REFERRALS_LIMIT = 5;
//maximum level from 0 to 7
uint256 MAX_LEVEL = 7;
//precenateg denominator- 100= 10000
uint256 public percentageDenominator = 10000;
//token per level i.e, for L1-> 1*25, L2-> 2*25
uint256 tokenPerLevel = 25;
//token variable
Ethrim public ETRM;
//Referral contract address
Referral public OldEthrimObj;
//map user by their unique trust wallet address
mapping(address => UserStruct) public users;
//users trust wallet address corresponding to unique id
mapping(uint256 => address) public userAddresses;
//maps level incentive by level
mapping(uint256 => incentiveStruct) public LEVEL_INCENTIVE;
//check if user not registered previously
modifier userRegistered() {
require(users[msg.sender].isExist == true, "User is not registered");
_;
}
//check if referrer id is invalid or not
modifier validReferrerID(uint256 _referrerID) {
require( _referrerID > 0 && _referrerID <= last_uid, "Invalid referrer ID");
_;
}
//check if user is already registerd
modifier userNotRegistered() {
require(users[msg.sender].isExist == false, "User is already registered");
_;
}
//check if selected level is valid or not
modifier validLevel(uint256 _level) {
require(_level > 0 && _level <= MAX_LEVEL, "Invalid level entered");
_;
}
event RegisterUserEvent(address indexed user, address indexed referrer, uint256 time);
event BuyLevelEvent(address indexed user, uint256 indexed level, uint256 time);
constructor(address payable _ownerAddress1, address payable _ownerAddress2, address _tokenAddr, address payable _oldEthrimAddr) public {
require(_ownerAddress1 != address(0), "Invalid owner address 1");
require(_ownerAddress2 != address(0), "Invalid owner address 2");
require(_tokenAddr != address(0), "Invalid token address");
owner = msg.sender;
ownerAddress1 = _ownerAddress1;
ownerAddress2 = _ownerAddress2;
ETRM = Ethrim(_tokenAddr);
OldEthrimObj = Referral(_oldEthrimAddr);
OldEthrimObj = Referral(_oldEthrimAddr);
last_uid = OldEthrimObj.last_uid();
//20% = 2000
LEVEL_INCENTIVE[1].directNumerator = 2000;
//10% =1000
LEVEL_INCENTIVE[1].inDirectNumerator = 1000;
//10% = 1000
LEVEL_INCENTIVE[2].directNumerator = 1000;
//5% = 500
LEVEL_INCENTIVE[2].inDirectNumerator = 500;
//6.67% = 667
LEVEL_INCENTIVE[3].directNumerator = 667;
//3.34% = 334
LEVEL_INCENTIVE[3].inDirectNumerator = 334;
//5% = 500
LEVEL_INCENTIVE[4].directNumerator = 500;
//2.5% = 1000
LEVEL_INCENTIVE[4].inDirectNumerator = 250;
//4% = 400
LEVEL_INCENTIVE[5].directNumerator = 400;
//2% = 200
LEVEL_INCENTIVE[5].inDirectNumerator = 200;
//3.34% = 334
LEVEL_INCENTIVE[6].directNumerator = 334;
//1.7% = 170
LEVEL_INCENTIVE[6].inDirectNumerator = 170;
//2.86% = 286
LEVEL_INCENTIVE[7].directNumerator = 286;
//1.43% = 143
LEVEL_INCENTIVE[7].inDirectNumerator = 143;
}
/**
* @dev User registration
*/
function registerUser(uint256 _referrerUniqueID) public payable userNotRegistered() validReferrerID(_referrerUniqueID) {
require(msg.value > 0, "ether value is 0");
uint256 referrerUniqueID = _referrerUniqueID;
if (users[userAddresses[referrerUniqueID]].referral.length >= REFERRALS_LIMIT) {
referrerUniqueID = users[findFreeReferrer(userAddresses[referrerUniqueID])].id;
}
last_uid = last_uid + 1;
users[msg.sender] = UserStruct({
isExist: true,
id: last_uid,
referrerID: referrerUniqueID,
currentLevel: 1,
totalEarningEth: 0,
referral: new address[](0),
levelExpiresAt: now.add(PERIOD_LENGTH)
});
userAddresses[last_uid] = msg.sender;
users[userAddresses[referrerUniqueID]].referral.push(msg.sender);
uint256 tokenAmount = getTokenAmountByLevel(1);
require(ETRM.transferFrom(owner, msg.sender, tokenAmount), "token transfer failed");
//get upline level
address userUpline = userAddresses[referrerUniqueID];
//transfer payment to all upline from current upline
transferLevelPayment(userUpline, 1);
emit RegisterUserEvent(msg.sender, userAddresses[referrerUniqueID], now);
}
/**
* @dev View free Referrer Address
*/
function findFreeReferrer(address _userAddress) public view returns (address) {
if (users[_userAddress].referral.length < REFERRALS_LIMIT){
return _userAddress;
}
address[] memory referrals = new address[](254);
referrals[0] = users[_userAddress].referral[0];
referrals[1] = users[_userAddress].referral[1];
referrals[2] = users[_userAddress].referral[2];
referrals[3] = users[_userAddress].referral[3];
referrals[4] = users[_userAddress].referral[4];
address referrer;
for (uint256 i = 0; i < 1048576; i++) {
if (users[referrals[i]].referral.length < REFERRALS_LIMIT) {
referrer = referrals[i];
break;
}
if (i >= 8191) {
continue;
}
//adding pyramid trees
referrals[((i.add(1).mul(5))).add(i.add(0))] = users[referrals[i]].referral[0];
referrals[((i.add(1).mul(5))).add(i.add(1))] = users[referrals[i]].referral[1];
referrals[((i.add(1).mul(5))).add(i.add(2))] = users[referrals[i]].referral[2];
referrals[((i.add(1).mul(5))).add(i.add(3))] = users[referrals[i]].referral[3];
referrals[((i.add(1).mul(5))).add(i.add(4))] = users[referrals[i]].referral[4];
}
require(referrer != address(0), 'Referrer not found');
return referrer;
}
function transferLevelPayment(address _userUpline, uint256 _levelForIncentive) internal {
//ether value
uint256 etherValue = msg.value;
address uplineAddress = _userUpline;
//current upline to be sent money
uint256 uplineLevel = users[uplineAddress].currentLevel;
//upline user level expiry time
uint256 uplineUserLevelExpiry = users[uplineAddress].levelExpiresAt;
//uid
uint256 uplineUID = users[uplineAddress].id;
//incentive amount total
uint256 amountSentAsIncetives = 0;
uint256 count = 1;
while(uplineUID > 0 && count <= 7) {
address payable receiver = payable(uplineAddress);
if(count == 1) {
uint256 uplineIncentive = (etherValue.mul(LEVEL_INCENTIVE[_levelForIncentive].directNumerator)).div(percentageDenominator);
if(now <= uplineUserLevelExpiry && users[uplineAddress].isExist) {
receiver.transfer(uplineIncentive);
users[uplineAddress].totalEarningEth = users[uplineAddress].totalEarningEth.add(uplineIncentive);
} else {
users[uplineAddress].isExist = false;
(ownerAddress1).transfer(uplineIncentive.div(2));
(ownerAddress2).transfer(uplineIncentive.div(2));
}
amountSentAsIncetives = amountSentAsIncetives.add(uplineIncentive);
} else {
uint256 uplineIncentive = (etherValue.mul(LEVEL_INCENTIVE[_levelForIncentive].inDirectNumerator)).div(percentageDenominator);
if(now <= uplineUserLevelExpiry && users[uplineAddress].isExist) {
receiver.transfer(uplineIncentive);
users[uplineAddress].totalEarningEth = users[uplineAddress].totalEarningEth.add(uplineIncentive);
} else {
users[uplineAddress].isExist = false;
(ownerAddress1).transfer(uplineIncentive.div(2));
(ownerAddress2).transfer(uplineIncentive.div(2));
}
amountSentAsIncetives = amountSentAsIncetives.add(uplineIncentive);
}
//get upline level
uint256 uplineReferrerId = users[uplineAddress].referrerID;
uplineAddress = userAddresses[uplineReferrerId];
//level of upline for user
uplineLevel = users[uplineAddress].currentLevel;
uplineUID = users[uplineAddress].id;
count++;
}
uint256 remAmount = msg.value.sub(amountSentAsIncetives);
transferToOwner(remAmount);
}
function buyLevel(uint256 _level) public payable userRegistered() validLevel(_level){
require(msg.value > 0, "ether value is 0");
uint256 userCurrentLevel = users[msg.sender].currentLevel;
require((_level == userCurrentLevel.add(1)) || (userCurrentLevel == 7 && _level == 7), "Invalid level upgrade value");
users[msg.sender].levelExpiresAt = now.add(PERIOD_LENGTH);
users[msg.sender].currentLevel = _level;
uint256 tokenAmount = getTokenAmountByLevel(_level);
require(ETRM.transferFrom(owner, msg.sender, tokenAmount), "token transfer failed");
//get upline user address
address userUpline = userAddresses[users[msg.sender].referrerID];
//transfer payment to all upline from current upline
transferLevelPayment(userUpline, _level);
emit BuyLevelEvent(msg.sender, _level, now);
}
/**
* @dev Contract balance withdraw
*/
function failSafe() public returns (bool) {
require(msg.sender == owner, "only Owner Wallet");
require(address(this).balance > 0, "Insufficient balance");
transferToOwner(address(this).balance);
return true;
}
function transferToOwner(uint256 _amount) internal{
uint256 amount = _amount.div(2);
(ownerAddress1).transfer(amount);
(ownerAddress2).transfer(amount);
}
/**
* @dev Total earned ETH
*/
function getTotalEarnedEther() public view returns (uint256) {
uint256 totalEth;
for (uint256 i = 1; i <= last_uid; i++) {
totalEth = totalEth.add(users[userAddresses[i]].totalEarningEth);
}
return totalEth;
}
/**
* @dev get token amount by level i.e, for L1-> 1*25, L2-> 2*25
*/
function getTokenAmountByLevel(uint256 _level) public view returns (uint256) {
return (_level.mul(tokenPerLevel)).mul(10**18);
}
/**
* @dev View referrals
*/
function viewUserReferral(address _userAddress) external view returns (address[] memory) {
return users[_userAddress].referral;
}
/**
* @dev View level expired time
*/
function viewUserLevelExpired(address _userAddress) external view returns (uint256) {
return users[_userAddress].levelExpiresAt;
}
/**
* @dev Update old contract data
*/
function oldEthrimSync(uint256 limit) public {
require(address(OldEthrimObj) != address(0), "Initialize closed");
require(msg.sender == owner, "Access denied");
uint256 oldUserId = 0;
for (uint256 i = 0; i <= limit; i++) {
UserStruct memory oldUserStruct;
address oldUser = OldEthrimObj.userAddresses(oldUserId);
(oldUserStruct.isExist,
oldUserStruct.id,
oldUserStruct.referrerID,
oldUserStruct.currentLevel,
oldUserStruct.totalEarningEth,
oldUserStruct.levelExpiresAt) = OldEthrimObj.users(oldUser);
users[oldUser].isExist = oldUserStruct.isExist;
users[oldUser].id = oldUserId;
users[oldUser].referrerID = oldUserStruct.referrerID;
users[oldUser].levelExpiresAt = oldUserStruct.levelExpiresAt;
users[oldUser].currentLevel = oldUserStruct.currentLevel;
users[oldUser].totalEarningEth = oldUserStruct.totalEarningEth;
users[oldUser].referral = OldEthrimObj.viewUserReferral(oldUser);
userAddresses[oldUserId] = oldUser;
oldUserId++;
}
}
// fallback
fallback() external payable {
revert("Invalid Transaction");
}
// receive
receive() external payable {
revert("Invalid Transaction");
}
} | * @dev Transfer token to specified address @param _to Receiver address @param _value Amount of the tokens/ | function transfer(address _to, uint256 _value) public override returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
| 7,659,488 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
5206,
12279,
1147,
358,
1269,
1758,
632,
891,
389,
869,
31020,
1758,
632,
891,
389,
1132,
16811,
434,
326,
2430,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
3849,
1135,
261,
6430,
13,
288,
203,
5411,
2583,
24899,
1132,
1648,
324,
26488,
63,
3576,
18,
15330,
19226,
203,
5411,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
203,
5411,
324,
26488,
63,
3576,
18,
15330,
65,
273,
324,
26488,
63,
3576,
18,
15330,
8009,
1717,
24899,
1132,
1769,
203,
5411,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
1132,
1769,
203,
5411,
3626,
12279,
12,
3576,
18,
15330,
16,
389,
869,
16,
389,
1132,
1769,
203,
5411,
327,
638,
31,
203,
3639,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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: 0x737ac585809c0f64ee09d7b8050d195d14f14c55
//Contract name: SmartToken
//Balance: 0 Ether
//Verification Date: 2/22/2018
//Transacion Count: 5
// CODE STARTS HERE
pragma solidity ^0.4.18;
/*
Bancor Converter Extensions interface
*/
contract IBancorConverterExtensions {
function formula() public view returns (IBancorFormula) {}
function gasPriceLimit() public view returns (IBancorGasPriceLimit) {}
function quickConverter() public view returns (IBancorQuickConverter) {}
}
contract IBancorFormula {
function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256);
function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256);
}
contract IBancorGasPriceLimit {
function gasPrice() public view returns (uint256) {}
}
contract IBancorQuickConverter {
function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256);
function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public payable returns (uint256);
}
contract IERC20Token {
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
function name() public view returns (string) {}
function symbol() public view returns (string) {}
function decimals() public view returns (uint8) {}
function totalSupply() public view returns (uint256) {}
function balanceOf(address _owner) public view returns (uint256) { _owner; }
function allowance(address _owner, address _spender) public view returns (uint256) { _owner; _spender; }
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
contract IOwned {
// this function isn't abstract since the compiler emits automatically generated getter functions as external
function owner() public view returns (address) {}
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
}
contract ITokenHolder is IOwned {
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
}
contract IEtherToken is ITokenHolder, IERC20Token {
function deposit() public payable;
function withdraw(uint256 _amount) public;
function withdrawTo(address _to, uint256 _amount) public;
}
contract ISmartToken is IOwned, IERC20Token {
function disableTransfers(bool _disable) public;
function issue(address _to, uint256 _amount) public;
function destroy(address _from, uint256 _amount) public;
}
contract ITokenConverter {
function convertibleTokenCount() public view returns (uint16);
function convertibleToken(uint16 _tokenIndex) public view returns (address);
function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256);
function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256);
// deprecated, backward compatibility
function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256);
}
contract Owned is IOwned {
address public owner;
address public newOwner;
event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
/**
@dev constructor
*/
function Owned() public {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
/**
@dev allows transferring the contract ownership
the new owner still needs to accept the transfer
can only be called by the contract owner
@param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
/**
@dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract Utils {
/**
constructor
*/
function Utils() public {
}
// verifies that an amount is greater than zero
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0);
_;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != address(0));
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
// Overflow protected math functions
/**
@dev returns the sum of _x and _y, asserts if the calculation overflows
@param _x value 1
@param _y value 2
@return sum
*/
function safeAdd(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
/**
@dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number
@param _x minuend
@param _y subtrahend
@return difference
*/
function safeSub(uint256 _x, uint256 _y) internal pure returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
/**
@dev returns the product of multiplying _x by _y, asserts if the calculation overflows
@param _x factor 1
@param _y factor 2
@return product
*/
function safeMul(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
contract TokenHolder is ITokenHolder, Owned, Utils {
/**
@dev constructor
*/
function TokenHolder() public {
}
/**
@dev withdraws tokens held by the contract and sends them to an account
can only be called by the owner
@param _token ERC20 token contract address
@param _to account to receive the new amount
@param _amount amount to withdraw
*/
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
public
ownerOnly
validAddress(_token)
validAddress(_to)
notThis(_to)
{
assert(_token.transfer(_to, _amount));
}
}
contract SmartTokenController is TokenHolder {
ISmartToken public token; // smart token
/**
@dev constructor
*/
function SmartTokenController(ISmartToken _token)
public
validAddress(_token)
{
token = _token;
}
// ensures that the controller is the token's owner
modifier active() {
assert(token.owner() == address(this));
_;
}
// ensures that the controller is not the token's owner
modifier inactive() {
assert(token.owner() != address(this));
_;
}
/**
@dev allows transferring the token ownership
the new owner still need to accept the transfer
can only be called by the contract owner
@param _newOwner new token owner
*/
function transferTokenOwnership(address _newOwner) public ownerOnly {
token.transferOwnership(_newOwner);
}
/**
@dev used by a new owner to accept a token ownership transfer
can only be called by the contract owner
*/
function acceptTokenOwnership() public ownerOnly {
token.acceptOwnership();
}
/**
@dev disables/enables token transfers
can only be called by the contract owner
@param _disable true to disable transfers, false to enable them
*/
function disableTokenTransfers(bool _disable) public ownerOnly {
token.disableTransfers(_disable);
}
/**
@dev withdraws tokens held by the controller and sends them to an account
can only be called by the owner
@param _token ERC20 token contract address
@param _to account to receive the new amount
@param _amount amount to withdraw
*/
function withdrawFromToken(
IERC20Token _token,
address _to,
uint256 _amount
)
public
ownerOnly
{
ITokenHolder(token).withdrawTokens(_token, _to, _amount);
}
}
contract Managed {
address public manager;
address public newManager;
event ManagerUpdate(address indexed _prevManager, address indexed _newManager);
/**
@dev constructor
*/
function Managed() public {
manager = msg.sender;
}
// allows execution by the manager only
modifier managerOnly {
assert(msg.sender == manager);
_;
}
/**
@dev allows transferring the contract management
the new manager still needs to accept the transfer
can only be called by the contract manager
@param _newManager new contract manager
*/
function transferManagement(address _newManager) public managerOnly {
require(_newManager != manager);
newManager = _newManager;
}
/**
@dev used by a new manager to accept a management transfer
*/
function acceptManagement() public {
require(msg.sender == newManager);
ManagerUpdate(manager, newManager);
manager = newManager;
newManager = address(0);
}
}
contract BancorConverter is ITokenConverter, SmartTokenController, Managed {
uint32 private constant MAX_WEIGHT = 1000000;
uint32 private constant MAX_CONVERSION_FEE = 1000000;
struct Connector {
uint256 virtualBalance; // connector virtual balance
uint32 weight; // connector weight, represented in ppm, 1-1000000
bool isVirtualBalanceEnabled; // true if virtual balance is enabled, false if not
bool isPurchaseEnabled; // is purchase of the smart token enabled with the connector, can be set by the owner
bool isSet; // used to tell if the mapping element is defined
}
string public version = '0.7';
string public converterType = 'bancor';
IBancorConverterExtensions public extensions; // bancor converter extensions contract
IERC20Token[] public connectorTokens; // ERC20 standard token addresses
IERC20Token[] public quickBuyPath; // conversion path that's used in order to buy the token with ETH
mapping (address => Connector) public connectors; // connector token addresses -> connector data
uint32 private totalConnectorWeight = 0; // used to efficiently prevent increasing the total connector weight above 100%
uint32 public maxConversionFee = 0; // maximum conversion fee for the lifetime of the contract, represented in ppm, 0...1000000 (0 = no fee, 100 = 0.01%, 1000000 = 100%)
uint32 public conversionFee = 0; // current conversion fee, represented in ppm, 0...maxConversionFee
bool public conversionsEnabled = true; // true if token conversions is enabled, false if not
// triggered when a conversion between two tokens occurs (TokenConverter event)
event Conversion(address indexed _fromToken, address indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return,
int256 _conversionFee, uint256 _currentPriceN, uint256 _currentPriceD);
// triggered when the conversion fee is updated
event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee);
/**
@dev constructor
@param _token smart token governed by the converter
@param _extensions address of a bancor converter extensions contract
@param _maxConversionFee maximum conversion fee, represented in ppm
@param _connectorToken optional, initial connector, allows defining the first connector at deployment time
@param _connectorWeight optional, weight for the initial connector
*/
function BancorConverter(ISmartToken _token, IBancorConverterExtensions _extensions, uint32 _maxConversionFee, IERC20Token _connectorToken, uint32 _connectorWeight)
public
SmartTokenController(_token)
validAddress(_extensions)
validMaxConversionFee(_maxConversionFee)
{
extensions = _extensions;
maxConversionFee = _maxConversionFee;
if (_connectorToken != address(0))
addConnector(_connectorToken, _connectorWeight, false);
}
// validates a connector token address - verifies that the address belongs to one of the connector tokens
modifier validConnector(IERC20Token _address) {
require(connectors[_address].isSet);
_;
}
// validates a token address - verifies that the address belongs to one of the convertible tokens
modifier validToken(IERC20Token _address) {
require(_address == token || connectors[_address].isSet);
_;
}
// verifies that the gas price is lower than the universal limit
modifier validGasPrice() {
assert(tx.gasprice <= extensions.gasPriceLimit().gasPrice());
_;
}
// validates maximum conversion fee
modifier validMaxConversionFee(uint32 _conversionFee) {
require(_conversionFee >= 0 && _conversionFee <= MAX_CONVERSION_FEE);
_;
}
// validates conversion fee
modifier validConversionFee(uint32 _conversionFee) {
require(_conversionFee >= 0 && _conversionFee <= maxConversionFee);
_;
}
// validates connector weight range
modifier validConnectorWeight(uint32 _weight) {
require(_weight > 0 && _weight <= MAX_WEIGHT);
_;
}
// validates a conversion path - verifies that the number of elements is odd and that maximum number of 'hops' is 10
modifier validConversionPath(IERC20Token[] _path) {
require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1);
_;
}
// allows execution only when conversions aren't disabled
modifier conversionsAllowed {
assert(conversionsEnabled);
_;
}
// allows execution only for owner or manager
modifier ownerOrManagerOnly {
require(msg.sender == owner || msg.sender == manager);
_;
}
/**
@dev returns the number of connector tokens defined
@return number of connector tokens
*/
function connectorTokenCount() public view returns (uint16) {
return uint16(connectorTokens.length);
}
/**
@dev returns the number of convertible tokens supported by the contract
note that the number of convertible tokens is the number of connector token, plus 1 (that represents the smart token)
@return number of convertible tokens
*/
function convertibleTokenCount() public view returns (uint16) {
return connectorTokenCount() + 1;
}
/**
@dev given a convertible token index, returns its contract address
@param _tokenIndex convertible token index
@return convertible token address
*/
function convertibleToken(uint16 _tokenIndex) public view returns (address) {
if (_tokenIndex == 0)
return token;
return connectorTokens[_tokenIndex - 1];
}
/*
@dev allows the owner to update the extensions contract address
@param _extensions address of a bancor converter extensions contract
*/
function setExtensions(IBancorConverterExtensions _extensions)
public
ownerOnly
validAddress(_extensions)
notThis(_extensions)
{
extensions = _extensions;
}
/*
@dev allows the manager to update the quick buy path
@param _path new quick buy path, see conversion path format in the BancorQuickConverter contract
*/
function setQuickBuyPath(IERC20Token[] _path)
public
ownerOnly
validConversionPath(_path)
{
quickBuyPath = _path;
}
/*
@dev allows the manager to clear the quick buy path
*/
function clearQuickBuyPath() public ownerOnly {
quickBuyPath.length = 0;
}
/**
@dev returns the length of the quick buy path array
@return quick buy path length
*/
function getQuickBuyPathLength() public view returns (uint256) {
return quickBuyPath.length;
}
/**
@dev disables the entire conversion functionality
this is a safety mechanism in case of a emergency
can only be called by the manager
@param _disable true to disable conversions, false to re-enable them
*/
function disableConversions(bool _disable) public ownerOrManagerOnly {
conversionsEnabled = !_disable;
}
/**
@dev updates the current conversion fee
can only be called by the manager
@param _conversionFee new conversion fee, represented in ppm
*/
function setConversionFee(uint32 _conversionFee)
public
ownerOrManagerOnly
validConversionFee(_conversionFee)
{
ConversionFeeUpdate(conversionFee, _conversionFee);
conversionFee = _conversionFee;
}
/*
@dev returns the conversion fee amount for a given return amount
@return conversion fee amount
*/
function getConversionFeeAmount(uint256 _amount) public view returns (uint256) {
return safeMul(_amount, conversionFee) / MAX_CONVERSION_FEE;
}
/**
@dev defines a new connector for the token
can only be called by the owner while the converter is inactive
@param _token address of the connector token
@param _weight constant connector weight, represented in ppm, 1-1000000
@param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it
*/
function addConnector(IERC20Token _token, uint32 _weight, bool _enableVirtualBalance)
public
ownerOnly
inactive
validAddress(_token)
notThis(_token)
validConnectorWeight(_weight)
{
require(_token != token && !connectors[_token].isSet && totalConnectorWeight + _weight <= MAX_WEIGHT); // validate input
connectors[_token].virtualBalance = 0;
connectors[_token].weight = _weight;
connectors[_token].isVirtualBalanceEnabled = _enableVirtualBalance;
connectors[_token].isPurchaseEnabled = true;
connectors[_token].isSet = true;
connectorTokens.push(_token);
totalConnectorWeight += _weight;
}
/**
@dev updates one of the token connectors
can only be called by the owner
@param _connectorToken address of the connector token
@param _weight constant connector weight, represented in ppm, 1-1000000
@param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it
@param _virtualBalance new connector's virtual balance
*/
function updateConnector(IERC20Token _connectorToken, uint32 _weight, bool _enableVirtualBalance, uint256 _virtualBalance)
public
ownerOnly
validConnector(_connectorToken)
validConnectorWeight(_weight)
{
Connector storage connector = connectors[_connectorToken];
require(totalConnectorWeight - connector.weight + _weight <= MAX_WEIGHT); // validate input
totalConnectorWeight = totalConnectorWeight - connector.weight + _weight;
connector.weight = _weight;
connector.isVirtualBalanceEnabled = _enableVirtualBalance;
connector.virtualBalance = _virtualBalance;
}
/**
@dev disables purchasing with the given connector token in case the connector token got compromised
can only be called by the owner
note that selling is still enabled regardless of this flag and it cannot be disabled by the owner
@param _connectorToken connector token contract address
@param _disable true to disable the token, false to re-enable it
*/
function disableConnectorPurchases(IERC20Token _connectorToken, bool _disable)
public
ownerOnly
validConnector(_connectorToken)
{
connectors[_connectorToken].isPurchaseEnabled = !_disable;
}
/**
@dev returns the connector's virtual balance if one is defined, otherwise returns the actual balance
@param _connectorToken connector token contract address
@return connector balance
*/
function getConnectorBalance(IERC20Token _connectorToken)
public
view
validConnector(_connectorToken)
returns (uint256)
{
Connector storage connector = connectors[_connectorToken];
return connector.isVirtualBalanceEnabled ? connector.virtualBalance : _connectorToken.balanceOf(this);
}
/**
@dev returns the expected return for converting a specific amount of _fromToken to _toToken
@param _fromToken ERC20 token to convert from
@param _toToken ERC20 token to convert to
@param _amount amount to convert, in fromToken
@return expected conversion return amount
*/
function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256) {
require(_fromToken != _toToken); // validate input
// conversion between the token and one of its connectors
if (_toToken == token)
return getPurchaseReturn(_fromToken, _amount);
else if (_fromToken == token)
return getSaleReturn(_toToken, _amount);
// conversion between 2 connectors
uint256 purchaseReturnAmount = getPurchaseReturn(_fromToken, _amount);
return getSaleReturn(_toToken, purchaseReturnAmount, safeAdd(token.totalSupply(), purchaseReturnAmount));
}
/**
@dev returns the expected return for buying the token for a connector token
@param _connectorToken connector token contract address
@param _depositAmount amount to deposit (in the connector token)
@return expected purchase return amount
*/
function getPurchaseReturn(IERC20Token _connectorToken, uint256 _depositAmount)
public
view
active
validConnector(_connectorToken)
returns (uint256)
{
Connector storage connector = connectors[_connectorToken];
require(connector.isPurchaseEnabled); // validate input
uint256 tokenSupply = token.totalSupply();
uint256 connectorBalance = getConnectorBalance(_connectorToken);
uint256 amount = extensions.formula().calculatePurchaseReturn(tokenSupply, connectorBalance, connector.weight, _depositAmount);
// deduct the fee from the return amount
uint256 feeAmount = getConversionFeeAmount(amount);
return safeSub(amount, feeAmount);
}
/**
@dev returns the expected return for selling the token for one of its connector tokens
@param _connectorToken connector token contract address
@param _sellAmount amount to sell (in the smart token)
@return expected sale return amount
*/
function getSaleReturn(IERC20Token _connectorToken, uint256 _sellAmount) public view returns (uint256) {
return getSaleReturn(_connectorToken, _sellAmount, token.totalSupply());
}
/**
@dev converts a specific amount of _fromToken to _toToken
@param _fromToken ERC20 token to convert from
@param _toToken ERC20 token to convert to
@param _amount amount to convert, in fromToken
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return conversion return amount
*/
function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) {
require(_fromToken != _toToken); // validate input
// conversion between the token and one of its connectors
if (_toToken == token)
return buy(_fromToken, _amount, _minReturn);
else if (_fromToken == token)
return sell(_toToken, _amount, _minReturn);
// conversion between 2 connectors
uint256 purchaseAmount = buy(_fromToken, _amount, 1);
return sell(_toToken, purchaseAmount, _minReturn);
}
/**
@dev buys the token by depositing one of its connector tokens
@param _connectorToken connector token contract address
@param _depositAmount amount to deposit (in the connector token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return buy return amount
*/
function buy(IERC20Token _connectorToken, uint256 _depositAmount, uint256 _minReturn)
public
conversionsAllowed
validGasPrice
greaterThanZero(_minReturn)
returns (uint256)
{
uint256 amount = getPurchaseReturn(_connectorToken, _depositAmount);
require(amount != 0 && amount >= _minReturn); // ensure the trade gives something in return and meets the minimum requested amount
// update virtual balance if relevant
Connector storage connector = connectors[_connectorToken];
if (connector.isVirtualBalanceEnabled)
connector.virtualBalance = safeAdd(connector.virtualBalance, _depositAmount);
// transfer _depositAmount funds from the caller in the connector token
assert(_connectorToken.transferFrom(msg.sender, this, _depositAmount));
// issue new funds to the caller in the smart token
token.issue(msg.sender, amount);
dispatchConversionEvent(_connectorToken, _depositAmount, amount, true);
return amount;
}
/**
@dev sells the token by withdrawing from one of its connector tokens
@param _connectorToken connector token contract address
@param _sellAmount amount to sell (in the smart token)
@param _minReturn if the conversion results in an amount smaller the minimum return - it is cancelled, must be nonzero
@return sell return amount
*/
function sell(IERC20Token _connectorToken, uint256 _sellAmount, uint256 _minReturn)
public
conversionsAllowed
validGasPrice
greaterThanZero(_minReturn)
returns (uint256)
{
require(_sellAmount <= token.balanceOf(msg.sender)); // validate input
uint256 amount = getSaleReturn(_connectorToken, _sellAmount);
require(amount != 0 && amount >= _minReturn); // ensure the trade gives something in return and meets the minimum requested amount
uint256 tokenSupply = token.totalSupply();
uint256 connectorBalance = getConnectorBalance(_connectorToken);
// ensure that the trade will only deplete the connector if the total supply is depleted as well
assert(amount < connectorBalance || (amount == connectorBalance && _sellAmount == tokenSupply));
// update virtual balance if relevant
Connector storage connector = connectors[_connectorToken];
if (connector.isVirtualBalanceEnabled)
connector.virtualBalance = safeSub(connector.virtualBalance, amount);
// destroy _sellAmount from the caller's balance in the smart token
token.destroy(msg.sender, _sellAmount);
// transfer funds to the caller in the connector token
// the transfer might fail if the actual connector balance is smaller than the virtual balance
assert(_connectorToken.transfer(msg.sender, amount));
dispatchConversionEvent(_connectorToken, _sellAmount, amount, false);
return amount;
}
/**
@dev converts the token to any other token in the bancor network by following a predefined conversion path
note that when converting from an ERC20 token (as opposed to a smart token), allowance must be set beforehand
@param _path conversion path, see conversion path format in the BancorQuickConverter contract
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return tokens issued in return
*/
function quickConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn)
public
payable
validConversionPath(_path)
returns (uint256)
{
IERC20Token fromToken = _path[0];
IBancorQuickConverter quickConverter = extensions.quickConverter();
// we need to transfer the source tokens from the caller to the quick converter,
// so it can execute the conversion on behalf of the caller
if (msg.value == 0) {
// not ETH, send the source tokens to the quick converter
// if the token is the smart token, no allowance is required - destroy the tokens from the caller and issue them to the quick converter
if (fromToken == token) {
token.destroy(msg.sender, _amount); // destroy _amount tokens from the caller's balance in the smart token
token.issue(quickConverter, _amount); // issue _amount new tokens to the quick converter
}
else {
// otherwise, we assume we already have allowance, transfer the tokens directly to the quick converter
assert(fromToken.transferFrom(msg.sender, quickConverter, _amount));
}
}
// execute the conversion and pass on the ETH with the call
return quickConverter.convertFor.value(msg.value)(_path, _amount, _minReturn, msg.sender);
}
// deprecated, backward compatibility
function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) {
return convert(_fromToken, _toToken, _amount, _minReturn);
}
/**
@dev utility, returns the expected return for selling the token for one of its connector tokens, given a total supply override
@param _connectorToken connector token contract address
@param _sellAmount amount to sell (in the smart token)
@param _totalSupply total token supply, overrides the actual token total supply when calculating the return
@return sale return amount
*/
function getSaleReturn(IERC20Token _connectorToken, uint256 _sellAmount, uint256 _totalSupply)
private
view
active
validConnector(_connectorToken)
greaterThanZero(_totalSupply)
returns (uint256)
{
Connector storage connector = connectors[_connectorToken];
uint256 connectorBalance = getConnectorBalance(_connectorToken);
uint256 amount = extensions.formula().calculateSaleReturn(_totalSupply, connectorBalance, connector.weight, _sellAmount);
// deduct the fee from the return amount
uint256 feeAmount = getConversionFeeAmount(amount);
return safeSub(amount, feeAmount);
}
/**
@dev helper, dispatches the Conversion event
The function also takes the tokens' decimals into account when calculating the current price
@param _connectorToken connector token contract address
@param _amount amount purchased/sold (in the source token)
@param _returnAmount amount returned (in the target token)
@param isPurchase true if it's a purchase, false if it's a sale
*/
function dispatchConversionEvent(IERC20Token _connectorToken, uint256 _amount, uint256 _returnAmount, bool isPurchase) private {
Connector storage connector = connectors[_connectorToken];
// calculate the new price using the simple price formula
// price = connector balance / (supply * weight)
// weight is represented in ppm, so multiplying by 1000000
uint256 connectorAmount = safeMul(getConnectorBalance(_connectorToken), MAX_WEIGHT);
uint256 tokenAmount = safeMul(token.totalSupply(), connector.weight);
// normalize values
uint8 tokenDecimals = token.decimals();
uint8 connectorTokenDecimals = _connectorToken.decimals();
if (tokenDecimals != connectorTokenDecimals) {
if (tokenDecimals > connectorTokenDecimals)
connectorAmount = safeMul(connectorAmount, 10 ** uint256(tokenDecimals - connectorTokenDecimals));
else
tokenAmount = safeMul(tokenAmount, 10 ** uint256(connectorTokenDecimals - tokenDecimals));
}
uint256 feeAmount = getConversionFeeAmount(_returnAmount);
// ensure that the fee is capped at 255 bits to prevent overflow when converting it to a signed int
assert(feeAmount <= 2 ** 255);
if (isPurchase)
Conversion(_connectorToken, token, msg.sender, _amount, _returnAmount, int256(feeAmount), connectorAmount, tokenAmount);
else
Conversion(token, _connectorToken, msg.sender, _amount, _returnAmount, int256(feeAmount), tokenAmount, connectorAmount);
}
/**
@dev fallback, buys the smart token with ETH
note that the purchase will use the price at the time of the purchase
*/
function() payable public {
quickConvert(quickBuyPath, msg.value, 1);
}
}
contract BancorConverterExtensions is IBancorConverterExtensions, TokenHolder {
IBancorFormula public formula; // bancor calculation formula contract
IBancorGasPriceLimit public gasPriceLimit; // bancor universal gas price limit contract
IBancorQuickConverter public quickConverter; // bancor quick converter contract
/**
@dev constructor
@param _formula address of a bancor formula contract
@param _gasPriceLimit address of a bancor gas price limit contract
@param _quickConverter address of a bancor quick converter contract
*/
function BancorConverterExtensions(IBancorFormula _formula, IBancorGasPriceLimit _gasPriceLimit, IBancorQuickConverter _quickConverter)
public
validAddress(_formula)
validAddress(_gasPriceLimit)
validAddress(_quickConverter)
{
formula = _formula;
gasPriceLimit = _gasPriceLimit;
quickConverter = _quickConverter;
}
/*
@dev allows the owner to update the formula contract address
@param _formula address of a bancor formula contract
*/
function setFormula(IBancorFormula _formula)
public
ownerOnly
validAddress(_formula)
notThis(_formula)
{
formula = _formula;
}
/*
@dev allows the owner to update the gas price limit contract address
@param _gasPriceLimit address of a bancor gas price limit contract
*/
function setGasPriceLimit(IBancorGasPriceLimit _gasPriceLimit)
public
ownerOnly
validAddress(_gasPriceLimit)
notThis(_gasPriceLimit)
{
gasPriceLimit = _gasPriceLimit;
}
/*
@dev allows the owner to update the quick converter contract address
@param _quickConverter address of a bancor quick converter contract
*/
function setQuickConverter(IBancorQuickConverter _quickConverter)
public
ownerOnly
validAddress(_quickConverter)
notThis(_quickConverter)
{
quickConverter = _quickConverter;
}
}
contract BancorFormula is IBancorFormula, Utils {
string public version = '0.3';
uint256 private constant ONE = 1;
uint32 private constant MAX_WEIGHT = 1000000;
uint8 private constant MIN_PRECISION = 32;
uint8 private constant MAX_PRECISION = 127;
/**
The values below depend on MAX_PRECISION. If you choose to change it:
Apply the same change in file 'PrintIntScalingFactors.py', run it and paste the results below.
*/
uint256 private constant FIXED_1 = 0x080000000000000000000000000000000;
uint256 private constant FIXED_2 = 0x100000000000000000000000000000000;
uint256 private constant MAX_NUM = 0x1ffffffffffffffffffffffffffffffff;
/**
The values below depend on MAX_PRECISION. If you choose to change it:
Apply the same change in file 'PrintLn2ScalingFactors.py', run it and paste the results below.
*/
uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8;
uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80;
/**
The values below depend on MIN_PRECISION and MAX_PRECISION. If you choose to change either one of them:
Apply the same change in file 'PrintFunctionBancorFormula.py', run it and paste the results below.
*/
uint256[128] private maxExpArray;
function BancorFormula() public {
// maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff;
// maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff;
// maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff;
// maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff;
// maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff;
// maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff;
// maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff;
// maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff;
// maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff;
// maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff;
// maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff;
// maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff;
// maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff;
// maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff;
// maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff;
// maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff;
// maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff;
// maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff;
// maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff;
// maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff;
// maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff;
// maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff;
// maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff;
// maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff;
// maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff;
// maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff;
// maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff;
// maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff;
// maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff;
// maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff;
// maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff;
// maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff;
maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff;
maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff;
maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff;
maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff;
maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff;
maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff;
maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff;
maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff;
maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff;
maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff;
maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff;
maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff;
maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff;
maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff;
maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff;
maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff;
maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff;
maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff;
maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff;
maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff;
maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff;
maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff;
maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff;
maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff;
maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff;
maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff;
maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff;
maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff;
maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff;
maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff;
maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff;
maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff;
maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff;
maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff;
maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff;
maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff;
maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff;
maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff;
maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff;
maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff;
maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff;
maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff;
maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff;
maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff;
maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff;
maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff;
maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff;
maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff;
maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff;
maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff;
maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff;
maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff;
maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff;
maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff;
maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff;
maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff;
maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff;
maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff;
maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff;
maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff;
maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff;
maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff;
maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff;
maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff;
maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff;
maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff;
maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff;
maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff;
maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff;
maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff;
maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff;
maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff;
maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff;
maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff;
maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff;
maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff;
maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff;
maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff;
maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff;
maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff;
maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff;
maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff;
maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff;
maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff;
maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff;
maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff;
maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff;
maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff;
maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff;
maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf;
maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df;
maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f;
maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037;
maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf;
maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9;
maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6;
}
/**
@dev given a token supply, connector balance, weight and a deposit amount (in the connector token),
calculates the return for a given conversion (in the main token)
Formula:
Return = _supply * ((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1)
@param _supply token total supply
@param _connectorBalance total connector balance
@param _connectorWeight connector weight, represented in ppm, 1-1000000
@param _depositAmount deposit amount, in connector token
@return purchase return amount
*/
function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256) {
// validate input
require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT);
// special case for 0 deposit amount
if (_depositAmount == 0)
return 0;
// special case if the weight = 100%
if (_connectorWeight == MAX_WEIGHT)
return safeMul(_supply, _depositAmount) / _connectorBalance;
uint256 result;
uint8 precision;
uint256 baseN = safeAdd(_depositAmount, _connectorBalance);
(result, precision) = power(baseN, _connectorBalance, _connectorWeight, MAX_WEIGHT);
uint256 temp = safeMul(_supply, result) >> precision;
return temp - _supply;
}
/**
@dev given a token supply, connector balance, weight and a sell amount (in the main token),
calculates the return for a given conversion (in the connector token)
Formula:
Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000)))
@param _supply token total supply
@param _connectorBalance total connector
@param _connectorWeight constant connector Weight, represented in ppm, 1-1000000
@param _sellAmount sell amount, in the token itself
@return sale return amount
*/
function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256) {
// validate input
require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply);
// special case for 0 sell amount
if (_sellAmount == 0)
return 0;
// special case for selling the entire supply
if (_sellAmount == _supply)
return _connectorBalance;
// special case if the weight = 100%
if (_connectorWeight == MAX_WEIGHT)
return safeMul(_connectorBalance, _sellAmount) / _supply;
uint256 result;
uint8 precision;
uint256 baseD = _supply - _sellAmount;
(result, precision) = power(_supply, baseD, MAX_WEIGHT, _connectorWeight);
uint256 temp1 = safeMul(_connectorBalance, result);
uint256 temp2 = _connectorBalance << precision;
return (temp1 - temp2) / result;
}
/**
General Description:
Determine a value of precision.
Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision.
Return the result along with the precision used.
Detailed Description:
Instead of calculating "base ^ exp", we calculate "e ^ (ln(base) * exp)".
The value of "ln(base)" is represented with an integer slightly smaller than "ln(base) * 2 ^ precision".
The larger "precision" is, the more accurately this value represents the real value.
However, the larger "precision" is, the more bits are required in order to store this value.
And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x").
This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function.
This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations.
This functions assumes that "_expN < (1 << 256) / ln(MAX_NUM, 1)", otherwise the multiplication should be replaced with a "safeMul".
*/
function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal view returns (uint256, uint8) {
uint256 lnBaseTimesExp = ln(_baseN, _baseD) * _expN / _expD;
uint8 precision = findPositionInMaxExpArray(lnBaseTimesExp);
return (fixedExp(lnBaseTimesExp >> (MAX_PRECISION - precision), precision), precision);
}
/**
Return floor(ln(numerator / denominator) * 2 ^ MAX_PRECISION), where:
- The numerator is a value between 1 and 2 ^ (256 - MAX_PRECISION) - 1
- The denominator is a value between 1 and 2 ^ (256 - MAX_PRECISION) - 1
- The output is a value between 0 and floor(ln(2 ^ (256 - MAX_PRECISION) - 1) * 2 ^ MAX_PRECISION)
This functions assumes that the numerator is larger than or equal to the denominator, because the output would be negative otherwise.
*/
function ln(uint256 _numerator, uint256 _denominator) internal pure returns (uint256) {
assert(_numerator <= MAX_NUM);
uint256 res = 0;
uint256 x = _numerator * FIXED_1 / _denominator;
// If x >= 2, then we compute the integer part of log2(x), which is larger than 0.
if (x >= FIXED_2) {
uint8 count = floorLog2(x / FIXED_1);
x >>= count; // now x < 2
res = count * FIXED_1;
}
// If x > 1, then we compute the fraction part of log2(x), which is larger than 0.
if (x > FIXED_1) {
for (uint8 i = MAX_PRECISION; i > 0; --i) {
x = (x * x) / FIXED_1; // now 1 < x < 4
if (x >= FIXED_2) {
x >>= 1; // now 1 < x < 2
res += ONE << (i - 1);
}
}
}
return res * LN2_NUMERATOR / LN2_DENOMINATOR;
}
/**
Compute the largest integer smaller than or equal to the binary logarithm of the input.
*/
function floorLog2(uint256 _n) internal pure returns (uint8) {
uint8 res = 0;
if (_n < 256) {
// At most 8 iterations
while (_n > 1) {
_n >>= 1;
res += 1;
}
}
else {
// Exactly 8 iterations
for (uint8 s = 128; s > 0; s >>= 1) {
if (_n >= (ONE << s)) {
_n >>= s;
res |= s;
}
}
}
return res;
}
/**
The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent:
- This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"]
- This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"]
*/
function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) {
uint8 lo = MIN_PRECISION;
uint8 hi = MAX_PRECISION;
while (lo + 1 < hi) {
uint8 mid = (lo + hi) / 2;
if (maxExpArray[mid] >= _x)
lo = mid;
else
hi = mid;
}
if (maxExpArray[hi] >= _x)
return hi;
if (maxExpArray[lo] >= _x)
return lo;
assert(false);
return 0;
}
/**
This function can be auto-generated by the script 'PrintFunctionFixedExp.py'.
It approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!".
It returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy.
The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1".
The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
*/
function fixedExp(uint256 _x, uint8 _precision) internal pure returns (uint256) {
uint256 xi = _x;
uint256 res = 0;
xi = (xi * _x) >> _precision;
res += xi * 0x03442c4e6074a82f1797f72ac0000000; // add x^2 * (33! / 2!)
xi = (xi * _x) >> _precision;
res += xi * 0x0116b96f757c380fb287fd0e40000000; // add x^3 * (33! / 3!)
xi = (xi * _x) >> _precision;
res += xi * 0x0045ae5bdd5f0e03eca1ff4390000000; // add x^4 * (33! / 4!)
xi = (xi * _x) >> _precision;
res += xi * 0x000defabf91302cd95b9ffda50000000; // add x^5 * (33! / 5!)
xi = (xi * _x) >> _precision;
res += xi * 0x0002529ca9832b22439efff9b8000000; // add x^6 * (33! / 6!)
xi = (xi * _x) >> _precision;
res += xi * 0x000054f1cf12bd04e516b6da88000000; // add x^7 * (33! / 7!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000a9e39e257a09ca2d6db51000000; // add x^8 * (33! / 8!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000012e066e7b839fa050c309000000; // add x^9 * (33! / 9!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000048177ebe1fa812375200000; // add x^13 * (33! / 13!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000057e22099c030d94100000; // add x^15 * (33! / 15!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000057e22099c030d9410000; // add x^16 * (33! / 16!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000052b6b54569976310000; // add x^17 * (33! / 17!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000004985f67696bf748000; // add x^18 * (33! / 18!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000003dea12ea99e498000; // add x^19 * (33! / 19!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000031880f2214b6e000; // add x^20 * (33! / 20!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000025bcff56eb36000; // add x^21 * (33! / 21!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000001b722e10ab1000; // add x^22 * (33! / 22!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000001317c70077000; // add x^23 * (33! / 23!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000000000cba84aafa00; // add x^24 * (33! / 24!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000000000082573a0a00; // add x^25 * (33! / 25!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000000000005035ad900; // add x^26 * (33! / 26!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000000000002f881b00; // add x^27 * (33! / 27!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000001b29340; // add x^28 * (33! / 28!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000000000000000efc40; // add x^29 * (33! / 29!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000000007fe0; // add x^30 * (33! / 30!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000000000420; // add x^31 * (33! / 31!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000000000021; // add x^32 * (33! / 32!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000000000001; // add x^33 * (33! / 33!)
return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0!
}
}
contract BancorGasPriceLimit is IBancorGasPriceLimit, Owned, Utils {
uint256 public gasPrice = 0 wei; // maximum gas price for bancor transactions
/**
@dev constructor
@param _gasPrice gas price limit
*/
function BancorGasPriceLimit(uint256 _gasPrice)
public
greaterThanZero(_gasPrice)
{
gasPrice = _gasPrice;
}
/*
@dev allows the owner to update the gas price limit
@param _gasPrice new gas price limit
*/
function setGasPrice(uint256 _gasPrice)
public
ownerOnly
greaterThanZero(_gasPrice)
{
gasPrice = _gasPrice;
}
}
contract BancorPriceFloor is Owned, TokenHolder {
uint256 public constant TOKEN_PRICE_N = 1; // crowdsale price in wei (numerator)
uint256 public constant TOKEN_PRICE_D = 100; // crowdsale price in wei (denominator)
string public version = '0.1';
ISmartToken public token; // smart token the contract allows selling
/**
@dev constructor
@param _token smart token the contract allows selling
*/
function BancorPriceFloor(ISmartToken _token)
public
validAddress(_token)
{
token = _token;
}
/**
@dev sells the smart token for ETH
note that the function will sell the full allowance amount
@return ETH sent in return
*/
function sell() public returns (uint256 amount) {
uint256 allowance = token.allowance(msg.sender, this); // get the full allowance amount
assert(token.transferFrom(msg.sender, this, allowance)); // transfer all tokens from the sender to the contract
uint256 etherValue = safeMul(allowance, TOKEN_PRICE_N) / TOKEN_PRICE_D; // calculate ETH value of the tokens
msg.sender.transfer(etherValue); // send the ETH amount to the seller
return etherValue;
}
/**
@dev withdraws ETH from the contract
@param _amount amount of ETH to withdraw
*/
function withdraw(uint256 _amount) public ownerOnly {
msg.sender.transfer(_amount); // send the amount
}
/**
@dev deposits ETH in the contract
*/
function() public payable {
}
}
contract BancorQuickConverter is IBancorQuickConverter, TokenHolder {
mapping (address => bool) public etherTokens; // list of all supported ether tokens
/**
@dev constructor
*/
function BancorQuickConverter() public {
}
// validates a conversion path - verifies that the number of elements is odd and that maximum number of 'hops' is 10
modifier validConversionPath(IERC20Token[] _path) {
require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1);
_;
}
/**
@dev allows the owner to register/unregister ether tokens
@param _token ether token contract address
@param _register true to register, false to unregister
*/
function registerEtherToken(IEtherToken _token, bool _register)
public
ownerOnly
validAddress(_token)
notThis(_token)
{
etherTokens[_token] = _register;
}
/**
@dev converts the token to any other token in the bancor network by following
a predefined conversion path and transfers the result tokens to a target account
note that the converter should already own the source tokens
@param _path conversion path, see conversion path format above
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@param _for account that will receive the conversion result
@return tokens issued in return
*/
function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for)
public
payable
validConversionPath(_path)
returns (uint256)
{
// if ETH is provided, ensure that the amount is identical to _amount and verify that the source token is an ether token
IERC20Token fromToken = _path[0];
require(msg.value == 0 || (_amount == msg.value && etherTokens[fromToken]));
ISmartToken smartToken;
IERC20Token toToken;
ITokenConverter converter;
uint256 pathLength = _path.length;
// if ETH was sent with the call, the source is an ether token - deposit the ETH in it
// otherwise, we assume we already have the tokens
if (msg.value > 0)
IEtherToken(fromToken).deposit.value(msg.value)();
// iterate over the conversion path
for (uint256 i = 1; i < pathLength; i += 2) {
smartToken = ISmartToken(_path[i]);
toToken = _path[i + 1];
converter = ITokenConverter(smartToken.owner());
// if the smart token isn't the source (from token), the converter doesn't have control over it and thus we need to approve the request
if (smartToken != fromToken)
ensureAllowance(fromToken, converter, _amount);
// make the conversion - if it's the last one, also provide the minimum return value
_amount = converter.change(fromToken, toToken, _amount, i == pathLength - 2 ? _minReturn : 1);
fromToken = toToken;
}
// finished the conversion, transfer the funds to the target account
// if the target token is an ether token, withdraw the tokens and send them as ETH
// otherwise, transfer the tokens as is
if (etherTokens[toToken])
IEtherToken(toToken).withdrawTo(_for, _amount);
else
assert(toToken.transfer(_for, _amount));
return _amount;
}
/**
@dev claims the caller's tokens, converts them to any other token in the bancor network
by following a predefined conversion path and transfers the result tokens to a target account
note that allowance must be set beforehand
@param _path conversion path, see conversion path format above
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@param _for account that will receive the conversion result
@return tokens issued in return
*/
function claimAndConvertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public returns (uint256) {
// we need to transfer the tokens from the caller to the converter before we follow
// the conversion path, to allow it to execute the conversion on behalf of the caller
// note: we assume we already have allowance
IERC20Token fromToken = _path[0];
assert(fromToken.transferFrom(msg.sender, this, _amount));
return convertFor(_path, _amount, _minReturn, _for);
}
/**
@dev converts the token to any other token in the bancor network by following
a predefined conversion path and transfers the result tokens back to the sender
note that the converter should already own the source tokens
@param _path conversion path, see conversion path format above
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return tokens issued in return
*/
function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256) {
return convertFor(_path, _amount, _minReturn, msg.sender);
}
/**
@dev claims the caller's tokens, converts them to any other token in the bancor network
by following a predefined conversion path and transfers the result tokens back to the sender
note that allowance must be set beforehand
@param _path conversion path, see conversion path format above
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return tokens issued in return
*/
function claimAndConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public returns (uint256) {
return claimAndConvertFor(_path, _amount, _minReturn, msg.sender);
}
/**
@dev utility, checks whether allowance for the given spender exists and approves one if it doesn't
@param _token token to check the allowance in
@param _spender approved address
@param _value allowance amount
*/
function ensureAllowance(IERC20Token _token, address _spender, uint256 _value) private {
// check if allowance for the given amount already exists
if (_token.allowance(this, _spender) >= _value)
return;
// if the allowance is nonzero, must reset it to 0 first
if (_token.allowance(this, _spender) != 0)
assert(_token.approve(_spender, 0));
// approve the new allowance
assert(_token.approve(_spender, _value));
}
}
contract CrowdsaleController is SmartTokenController {
uint256 public constant DURATION = 14 days; // crowdsale duration
uint256 public constant TOKEN_PRICE_N = 1; // initial price in wei (numerator)
uint256 public constant TOKEN_PRICE_D = 100; // initial price in wei (denominator)
uint256 public constant BTCS_ETHER_CAP = 50000 ether; // maximum bitcoin suisse ether contribution
uint256 public constant MAX_GAS_PRICE = 50000000000 wei; // maximum gas price for contribution transactions
string public version = '0.1';
uint256 public startTime = 0; // crowdsale start time (in seconds)
uint256 public endTime = 0; // crowdsale end time (in seconds)
uint256 public totalEtherCap = 1000000 ether; // current ether contribution cap, initialized with a temp value as a safety mechanism until the real cap is revealed
uint256 public totalEtherContributed = 0; // ether contributed so far
bytes32 public realEtherCapHash; // ensures that the real cap is predefined on deployment and cannot be changed later
address public beneficiary = address(0); // address to receive all ether contributions
address public btcs = address(0); // bitcoin suisse address
// triggered on each contribution
event Contribution(address indexed _contributor, uint256 _amount, uint256 _return);
/**
@dev constructor
@param _token smart token the crowdsale is for
@param _startTime crowdsale start time
@param _beneficiary address to receive all ether contributions
@param _btcs bitcoin suisse address
*/
function CrowdsaleController(ISmartToken _token, uint256 _startTime, address _beneficiary, address _btcs, bytes32 _realEtherCapHash)
public
SmartTokenController(_token)
validAddress(_beneficiary)
validAddress(_btcs)
earlierThan(_startTime)
greaterThanZero(uint256(_realEtherCapHash))
{
startTime = _startTime;
endTime = startTime + DURATION;
beneficiary = _beneficiary;
btcs = _btcs;
realEtherCapHash = _realEtherCapHash;
}
// verifies that the gas price is lower than 50 gwei
modifier validGasPrice() {
assert(tx.gasprice <= MAX_GAS_PRICE);
_;
}
// verifies that the ether cap is valid based on the key provided
modifier validEtherCap(uint256 _cap, uint256 _key) {
require(computeRealCap(_cap, _key) == realEtherCapHash);
_;
}
// ensures that it's earlier than the given time
modifier earlierThan(uint256 _time) {
assert(now < _time);
_;
}
// ensures that the current time is between _startTime (inclusive) and _endTime (exclusive)
modifier between(uint256 _startTime, uint256 _endTime) {
assert(now >= _startTime && now < _endTime);
_;
}
// ensures that the sender is bitcoin suisse
modifier btcsOnly() {
assert(msg.sender == btcs);
_;
}
// ensures that we didn't reach the ether cap
modifier etherCapNotReached(uint256 _contribution) {
assert(safeAdd(totalEtherContributed, _contribution) <= totalEtherCap);
_;
}
// ensures that we didn't reach the bitcoin suisse ether cap
modifier btcsEtherCapNotReached(uint256 _ethContribution) {
assert(safeAdd(totalEtherContributed, _ethContribution) <= BTCS_ETHER_CAP);
_;
}
/**
@dev computes the real cap based on the given cap & key
@param _cap cap
@param _key key used to compute the cap hash
@return computed real cap hash
*/
function computeRealCap(uint256 _cap, uint256 _key) public pure returns (bytes32) {
return keccak256(_cap, _key);
}
/**
@dev enables the real cap defined on deployment
@param _cap predefined cap
@param _key key used to compute the cap hash
*/
function enableRealCap(uint256 _cap, uint256 _key)
public
ownerOnly
active
between(startTime, endTime)
validEtherCap(_cap, _key)
{
require(_cap < totalEtherCap); // validate input
totalEtherCap = _cap;
}
/**
@dev computes the number of tokens that should be issued for a given contribution
@param _contribution contribution amount
@return computed number of tokens
*/
function computeReturn(uint256 _contribution) public pure returns (uint256) {
return safeMul(_contribution, TOKEN_PRICE_D) / TOKEN_PRICE_N;
}
/**
@dev ETH contribution
can only be called during the crowdsale
@return tokens issued in return
*/
function contributeETH()
public
payable
between(startTime, endTime)
returns (uint256 amount)
{
return processContribution();
}
/**
@dev Contribution through BTCs (Bitcoin Suisse only)
can only be called before the crowdsale started
@return tokens issued in return
*/
function contributeBTCs()
public
payable
btcsOnly
btcsEtherCapNotReached(msg.value)
earlierThan(startTime)
returns (uint256 amount)
{
return processContribution();
}
/**
@dev handles contribution logic
note that the Contribution event is triggered using the sender as the contributor, regardless of the actual contributor
@return tokens issued in return
*/
function processContribution() private
active
etherCapNotReached(msg.value)
validGasPrice
returns (uint256 amount)
{
uint256 tokenAmount = computeReturn(msg.value);
beneficiary.transfer(msg.value); // transfer the ether to the beneficiary account
totalEtherContributed = safeAdd(totalEtherContributed, msg.value); // update the total contribution amount
token.issue(msg.sender, tokenAmount); // issue new funds to the contributor in the smart token
token.issue(beneficiary, tokenAmount); // issue tokens to the beneficiary
Contribution(msg.sender, msg.value, tokenAmount);
return tokenAmount;
}
// fallback
function() payable public {
contributeETH();
}
}
contract ERC20Token is IERC20Token, Utils {
string public standard = 'Token 0.1';
string public name = '';
string public symbol = '';
uint8 public decimals = 0;
uint256 public totalSupply = 0;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
@dev constructor
@param _name token name
@param _symbol token symbol
@param _decimals decimal points, for display purposes
*/
function ERC20Token(string _name, string _symbol, uint8 _decimals) public {
require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input
name = _name;
symbol = _symbol;
decimals = _decimals;
}
/**
@dev send coins
throws on any error rather then return a false flag to minimize user errors
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _value)
public
validAddress(_to)
returns (bool success)
{
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
@dev an account/contract attempts to get the coins
throws on any error rather then return a false flag to minimize user errors
@param _from source address
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value)
public
validAddress(_from)
validAddress(_to)
returns (bool success)
{
allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value);
balanceOf[_from] = safeSub(balanceOf[_from], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(_from, _to, _value);
return true;
}
/**
@dev allow another account/contract to spend some tokens on your behalf
throws on any error rather then return a false flag to minimize user errors
also, to minimize the risk of the approve/transferFrom attack vector
(see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice
in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value
@param _spender approved address
@param _value allowance amount
@return true if the approval was successful, false if it wasn't
*/
function approve(address _spender, uint256 _value)
public
validAddress(_spender)
returns (bool success)
{
// if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
}
contract EtherToken is IEtherToken, Owned, ERC20Token, TokenHolder {
// triggered when the total supply is increased
event Issuance(uint256 _amount);
// triggered when the total supply is decreased
event Destruction(uint256 _amount);
/**
@dev constructor
*/
function EtherToken()
public
ERC20Token('Ether Token', 'ETH', 18) {
}
/**
@dev deposit ether in the account
*/
function deposit() public payable {
balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender], msg.value); // add the value to the account balance
totalSupply = safeAdd(totalSupply, msg.value); // increase the total supply
Issuance(msg.value);
Transfer(this, msg.sender, msg.value);
}
/**
@dev withdraw ether from the account
@param _amount amount of ether to withdraw
*/
function withdraw(uint256 _amount) public {
withdrawTo(msg.sender, _amount);
}
/**
@dev withdraw ether from the account to a target account
@param _to account to receive the ether
@param _amount amount of ether to withdraw
*/
function withdrawTo(address _to, uint256 _amount)
public
notThis(_to)
{
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _amount); // deduct the amount from the account balance
totalSupply = safeSub(totalSupply, _amount); // decrease the total supply
_to.transfer(_amount); // send the amount to the target account
Transfer(msg.sender, this, _amount);
Destruction(_amount);
}
// ERC20 standard method overrides with some extra protection
/**
@dev send coins
throws on any error rather then return a false flag to minimize user errors
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _value)
public
notThis(_to)
returns (bool success)
{
assert(super.transfer(_to, _value));
return true;
}
/**
@dev an account/contract attempts to get the coins
throws on any error rather then return a false flag to minimize user errors
@param _from source address
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value)
public
notThis(_to)
returns (bool success)
{
assert(super.transferFrom(_from, _to, _value));
return true;
}
/**
@dev deposit ether in the account
*/
function() public payable {
deposit();
}
}
contract SmartToken is ISmartToken, Owned, ERC20Token, TokenHolder {
string public version = '0.3';
bool public transfersEnabled = true; // true if transfer/transferFrom are enabled, false if not
// triggered when a smart token is deployed - the _token address is defined for forward compatibility, in case we want to trigger the event from a factory
event NewSmartToken(address _token);
// triggered when the total supply is increased
event Issuance(uint256 _amount);
// triggered when the total supply is decreased
event Destruction(uint256 _amount);
/**
@dev constructor
@param _name token name
@param _symbol token short symbol, minimum 1 character
@param _decimals for display purposes only
*/
function SmartToken(string _name, string _symbol, uint8 _decimals)
public
ERC20Token(_name, _symbol, _decimals)
{
NewSmartToken(address(this));
}
// allows execution only when transfers aren't disabled
modifier transfersAllowed {
assert(transfersEnabled);
_;
}
/**
@dev disables/enables transfers
can only be called by the contract owner
@param _disable true to disable transfers, false to enable them
*/
function disableTransfers(bool _disable) public ownerOnly {
transfersEnabled = !_disable;
}
/**
@dev increases the token supply and sends the new tokens to an account
can only be called by the contract owner
@param _to account to receive the new amount
@param _amount amount to increase the supply by
*/
function issue(address _to, uint256 _amount)
public
ownerOnly
validAddress(_to)
notThis(_to)
{
totalSupply = safeAdd(totalSupply, _amount);
balanceOf[_to] = safeAdd(balanceOf[_to], _amount);
Issuance(_amount);
Transfer(this, _to, _amount);
}
/**
@dev removes tokens from an account and decreases the token supply
can be called by the contract owner to destroy tokens from any account or by any holder to destroy tokens from his/her own account
@param _from account to remove the amount from
@param _amount amount to decrease the supply by
*/
function destroy(address _from, uint256 _amount) public {
require(msg.sender == _from || msg.sender == owner); // validate input
balanceOf[_from] = safeSub(balanceOf[_from], _amount);
totalSupply = safeSub(totalSupply, _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
// ERC20 standard method overrides with some extra functionality
/**
@dev send coins
throws on any error rather then return a false flag to minimize user errors
in addition to the standard checks, the function throws if transfers are disabled
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _value) public transfersAllowed returns (bool success) {
assert(super.transfer(_to, _value));
return true;
}
/**
@dev an account/contract attempts to get the coins
throws on any error rather then return a false flag to minimize user errors
in addition to the standard checks, the function throws if transfers are disabled
@param _from source address
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool success) {
assert(super.transferFrom(_from, _to, _value));
return true;
}
}
| add x^3 * (33! / 3!)
| res += xi * 0x0116b96f757c380fb287fd0e40000000; | 880,300 | [
1,
4625,
348,
7953,
560,
30,
225,
527,
619,
66,
23,
380,
261,
3707,
5,
342,
890,
24949,
203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
400,
1011,
14087,
380,
374,
92,
1611,
2313,
70,
10525,
74,
5877,
27,
71,
23,
3672,
19192,
6030,
27,
8313,
20,
73,
24,
17877,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x6FC94c66Bd7AB2Bea81b6aEe3e007206e8fe96A9/sources/SharedDeposit.sol | address goerli_medella_beacon_testnet = 0x07b39F4fDE4A38bACe212b546dAc87C58DfE3fDC; TODO: change Its hard to exactly hit the max deposit amount with small shares. this allows a small bit of overflow room Eth in the buffer cannot be withdrawn by an admin, only by burning the underlying token via a user withdraw | contract SharedDeposit is Pausable, ReentrancyGuard {
using SafeMath for uint256;
using SafeMath for uint;
address public pyrmontDepositContractAddress = 0x8c5fecdC472E27Bc447696F431E425D02dd46a8c;
address public mainnetDepositContractAddress = 0x00000000219ab540356cBB839Cbe05303d7705Fa;
IDepositContract depositContract;
uint256 public adminFee;
uint256 public numValidators;
uint256 public costPerValidator;
uint256 public curValidatorShares;
uint256 public validatorsCreated;
uint256 public adminFeeTotal;
bool public disableWithdrawRefund;
uint256 public buffer;
address public BETHTokenAddress;
IBETH BETHToken;
constructor(uint256 _numValidators, uint256 _adminFee, address _BETHTokenAddress) public {
depositContract = IDepositContract(pyrmontDepositContractAddress);
BETHTokenAddress = _BETHTokenAddress;
BETHToken = IBETH(BETHTokenAddress);
costPerValidator = uint(32).mul(1e18).add(adminFee);
}
function mintingAllowedAfter() external view returns (uint256) {
return BETHToken.mintingAllowedAfter();
}
function workable() public view returns (bool) {
uint256 amount = 32 ether;
bool validatorLimitReached = (curValidatorShares >= maxValidatorShares());
bool balanceEnough = (address(this).balance >= amount);
return validatorLimitReached && balanceEnough;
}
function maxValidatorShares() public view returns (uint256) {
return uint(32).mul(1e18).mul(numValidators);
}
function remainingSpaceInEpoch() external view returns (uint256) {
uint remainingShares = (maxValidatorShares()).sub(curValidatorShares);
uint valBeforeAdmin = remainingShares.mul(1e18).div(uint(1).mul(1e18).sub(adminFee.mul(1e18).div(costPerValidator)));
return valBeforeAdmin;
}
function isContract(address _addr) private returns (bool isit){
uint32 size;
assembly {
size := extcodesize(_addr)
}
return (size > 0);
}
Principal deposit input = P
AdminFee = a
AdminFee as percent in 1e18 = a% = a / 32
AdminFee on tx in 1e18 = (P * a% / 1e18)
on deposit:
P - (P * a%) = Z
on withdraw with admin fee refund:
P = Z / (1 - a%)
function isContract(address _addr) private returns (bool isit){
uint32 size;
assembly {
size := extcodesize(_addr)
}
return (size > 0);
}
Principal deposit input = P
AdminFee = a
AdminFee as percent in 1e18 = a% = a / 32
AdminFee on tx in 1e18 = (P * a% / 1e18)
on deposit:
P - (P * a%) = Z
on withdraw with admin fee refund:
P = Z / (1 - a%)
Shares minted = Z
function deposit() public payable nonReentrant whenNotPaused {
uint value = uint(msg.value);
uint myAdminFee = adminFee.mul(value).mul(1e18).div(costPerValidator).div(1e18);
uint valMinusAdmin = value.sub(myAdminFee);
uint newShareTotal = curValidatorShares.add(valMinusAdmin);
require(newShareTotal <= buffer.add(maxValidatorShares()), "Eth2Staker:deposit:Amount too large, not enough validators left");
curValidatorShares = newShareTotal;
adminFeeTotal = adminFeeTotal.add(myAdminFee);
BETHToken.mint(msg.sender, valMinusAdmin);
}
function withdraw(uint256 amount) public nonReentrant whenNotPaused {
uint valBeforeAdmin = amount.mul(1e18).div(uint(1).mul(1e18).sub(adminFee.mul(1e18).div(costPerValidator)));
if (disableWithdrawRefund == true) {
valBeforeAdmin = amount;
}
uint newShareTotal = curValidatorShares.sub(amount);
require(newShareTotal <= buffer.add(maxValidatorShares()), "Eth2Staker:withdraw:Amount too large, not enough validators supplied");
require(newShareTotal >= 0, "Eth2Staker:withdraw:Amount too small, not enough validators left");
require(address(this).balance > amount, "Eth2Staker:withdraw:not enough balancce in contract");
require(BETHToken.balanceOf(msg.sender) >= amount, "Eth2Staker: Sender balance not enough");
adminFeeTotal = adminFeeTotal.sub(valBeforeAdmin.sub(amount));
BETHToken.burn(msg.sender, amount);
address payable sender = msg.sender;
sender.transfer(valBeforeAdmin);
}
function withdraw(uint256 amount) public nonReentrant whenNotPaused {
uint valBeforeAdmin = amount.mul(1e18).div(uint(1).mul(1e18).sub(adminFee.mul(1e18).div(costPerValidator)));
if (disableWithdrawRefund == true) {
valBeforeAdmin = amount;
}
uint newShareTotal = curValidatorShares.sub(amount);
require(newShareTotal <= buffer.add(maxValidatorShares()), "Eth2Staker:withdraw:Amount too large, not enough validators supplied");
require(newShareTotal >= 0, "Eth2Staker:withdraw:Amount too small, not enough validators left");
require(address(this).balance > amount, "Eth2Staker:withdraw:not enough balancce in contract");
require(BETHToken.balanceOf(msg.sender) >= amount, "Eth2Staker: Sender balance not enough");
adminFeeTotal = adminFeeTotal.sub(valBeforeAdmin.sub(amount));
BETHToken.burn(msg.sender, amount);
address payable sender = msg.sender;
sender.transfer(valBeforeAdmin);
}
curValidatorShares = newShareTotal;
function depositToEth2(bytes calldata pubkey,
bytes calldata withdrawal_credentials,
bytes calldata signature,
bytes32 deposit_data_root) external onlyOwner nonReentrant {
uint256 amount = 32 ether;
validatorsCreated = validatorsCreated.add(1);
}
depositContract.deposit{value: amount}(pubkey, withdrawal_credentials, signature, deposit_data_root);
function setNumValidators(uint256 _numValidators) external onlyOwner {
numValidators = _numValidators;
}
function toggleWithdrawAdminFeeRefund() external onlyOwner {
disableWithdrawRefund = !disableWithdrawRefund;
}
function setMinter(address payable minter_) external onlyOwner nonReentrant {
require(isContract(minter_), "Eth2Staker:setMinter: Cannot migrate funds to non contract address");
BETHToken.setMinter(minter_);
minter_.transfer(address(this).balance);
}
function setAdminFee(uint256 amount) external onlyOwner {
adminFee = amount;
costPerValidator = uint(32).mul(1e18).add(adminFee);
}
function withdrawAdminFee(uint amount) external onlyOwner nonReentrant {
require(validatorsCreated >= 0, "Eth2Staker:withdrawAdminFee: No validators created. Admins cannot withdraw without creation");
address payable sender = msg.sender;
if (amount == 0) {
amount = adminFeeTotal;
}
require(amount <= adminFeeTotal, "Eth2Staker:withdrawAdminFee: More than adminFeeTotal cannot be withdrawn");
sender.transfer(amount);
adminFeeTotal = adminFeeTotal.sub(amount);
}
function withdrawAdminFee(uint amount) external onlyOwner nonReentrant {
require(validatorsCreated >= 0, "Eth2Staker:withdrawAdminFee: No validators created. Admins cannot withdraw without creation");
address payable sender = msg.sender;
if (amount == 0) {
amount = adminFeeTotal;
}
require(amount <= adminFeeTotal, "Eth2Staker:withdrawAdminFee: More than adminFeeTotal cannot be withdrawn");
sender.transfer(amount);
adminFeeTotal = adminFeeTotal.sub(amount);
}
}
| 16,863,143 | [
1,
4625,
348,
7953,
560,
30,
1758,
1960,
264,
549,
67,
2937,
1165,
69,
67,
2196,
16329,
67,
3813,
2758,
273,
374,
92,
8642,
70,
5520,
42,
24,
74,
1639,
24,
37,
7414,
70,
2226,
73,
22,
2138,
70,
6564,
26,
72,
9988,
11035,
39,
8204,
40,
74,
41,
23,
74,
5528,
31,
2660,
30,
2549,
29517,
7877,
358,
8950,
6800,
326,
943,
443,
1724,
3844,
598,
5264,
24123,
18,
333,
5360,
279,
5264,
2831,
434,
9391,
7725,
512,
451,
316,
326,
1613,
2780,
506,
598,
9446,
82,
635,
392,
3981,
16,
1338,
635,
18305,
310,
326,
6808,
1147,
3970,
279,
729,
598,
9446,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
10314,
758,
1724,
353,
21800,
16665,
16,
868,
8230,
12514,
16709,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
565,
1758,
1071,
2395,
8864,
1580,
758,
1724,
8924,
1887,
273,
374,
92,
28,
71,
25,
74,
557,
72,
39,
24,
9060,
41,
5324,
38,
71,
6334,
6669,
10525,
42,
24,
6938,
41,
24,
2947,
40,
3103,
449,
8749,
69,
28,
71,
31,
203,
565,
1758,
1071,
2774,
2758,
758,
1724,
8924,
1887,
273,
374,
92,
12648,
22,
3657,
378,
6564,
4630,
4313,
71,
9676,
28,
5520,
39,
2196,
6260,
23,
4630,
72,
4700,
6260,
29634,
31,
203,
203,
565,
467,
758,
1724,
8924,
443,
1724,
8924,
31,
203,
203,
565,
2254,
5034,
1071,
3981,
14667,
31,
203,
565,
2254,
5034,
1071,
818,
19420,
31,
7010,
565,
2254,
5034,
1071,
6991,
2173,
5126,
31,
203,
565,
2254,
5034,
1071,
662,
5126,
24051,
31,
203,
565,
2254,
5034,
1071,
11632,
6119,
31,
203,
565,
2254,
5034,
1071,
3981,
14667,
5269,
31,
203,
565,
1426,
1071,
4056,
1190,
9446,
21537,
31,
203,
565,
2254,
5034,
1071,
1613,
31,
7010,
565,
1758,
1071,
605,
1584,
44,
1345,
1887,
31,
203,
565,
23450,
1584,
44,
605,
1584,
44,
1345,
31,
203,
203,
565,
3885,
12,
11890,
5034,
389,
2107,
19420,
16,
2254,
5034,
389,
3666,
14667,
16,
1758,
389,
38,
1584,
44,
1345,
1887,
13,
1071,
288,
203,
3639,
443,
1724,
8924,
273,
467,
758,
1724,
8924,
12,
2074,
8864,
1580,
758,
1724,
8924,
1887,
1769,
203,
203,
203,
203,
377,
203,
3639,
605,
1584,
44,
1345,
1887,
273,
389,
38,
1584,
44,
1345,
1887,
31,
203,
3639,
605,
1584,
44,
1345,
273,
23450,
1584,
44,
12,
38,
1584,
44,
1345,
1887,
1769,
203,
203,
3639,
6991,
2173,
5126,
273,
2254,
12,
1578,
2934,
16411,
12,
21,
73,
2643,
2934,
1289,
12,
3666,
14667,
1769,
203,
565,
289,
203,
377,
203,
565,
445,
312,
474,
310,
5042,
4436,
1435,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
605,
1584,
44,
1345,
18,
81,
474,
310,
5042,
4436,
5621,
203,
565,
289,
203,
203,
565,
445,
1440,
429,
1435,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
2254,
5034,
3844,
273,
3847,
225,
2437,
31,
203,
3639,
1426,
4213,
3039,
23646,
273,
261,
1397,
5126,
24051,
1545,
943,
5126,
24051,
10663,
203,
3639,
1426,
11013,
664,
4966,
273,
261,
2867,
12,
2211,
2934,
12296,
1545,
3844,
1769,
203,
3639,
327,
4213,
3039,
23646,
597,
11013,
664,
4966,
31,
203,
565,
289,
203,
203,
565,
445,
943,
5126,
24051,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
2254,
12,
1578,
2934,
16411,
12,
21,
73,
2643,
2934,
16411,
12,
2107,
19420,
1769,
203,
565,
289,
203,
203,
565,
445,
4463,
3819,
382,
14638,
1435,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
4463,
24051,
273,
261,
1896,
5126,
24051,
1435,
2934,
1717,
12,
1397,
5126,
24051,
1769,
203,
3639,
2254,
1244,
4649,
4446,
273,
4463,
24051,
18,
16411,
12,
21,
73,
2643,
2934,
2892,
12,
11890,
12,
21,
2934,
16411,
12,
21,
73,
2643,
2934,
1717,
12,
3666,
14667,
18,
16411,
12,
21,
73,
2643,
2934,
2892,
12,
12398,
2173,
5126,
3719,
1769,
203,
3639,
327,
1244,
4649,
4446,
31,
203,
565,
289,
203,
203,
565,
445,
353,
8924,
12,
2867,
389,
4793,
13,
3238,
1135,
261,
6430,
353,
305,
15329,
203,
3639,
2254,
1578,
963,
31,
203,
3639,
19931,
288,
203,
5411,
963,
519,
1110,
7000,
554,
24899,
4793,
13,
203,
3639,
289,
203,
3639,
327,
261,
1467,
405,
374,
1769,
203,
565,
289,
203,
203,
565,
17010,
443,
1724,
810,
273,
453,
203,
565,
7807,
14667,
273,
279,
203,
565,
7807,
14667,
487,
5551,
316,
404,
73,
2643,
273,
279,
9,
273,
225,
279,
342,
3847,
203,
565,
7807,
14667,
603,
2229,
316,
404,
73,
2643,
273,
261,
52,
380,
279,
9,
342,
404,
73,
2643,
13,
203,
203,
565,
603,
443,
1724,
30,
203,
565,
453,
300,
261,
52,
380,
279,
9,
13,
273,
2285,
203,
203,
565,
603,
598,
9446,
598,
3981,
14036,
16255,
30,
203,
565,
453,
273,
2285,
342,
261,
21,
300,
279,
9,
13,
203,
565,
445,
353,
8924,
12,
2867,
389,
4793,
13,
3238,
1135,
261,
6430,
353,
305,
15329,
203,
3639,
2254,
1578,
963,
31,
203,
3639,
19931,
288,
203,
5411,
963,
519,
1110,
7000,
554,
24899,
4793,
13,
203,
3639,
289,
203,
3639,
327,
261,
1467,
405,
374,
1769,
203,
565,
289,
203,
203,
565,
17010,
443,
1724,
810,
273,
453,
203,
565,
7807,
14667,
273,
279,
203,
565,
7807,
14667,
487,
5551,
316,
404,
73,
2643,
273,
279,
9,
273,
225,
279,
342,
3847,
203,
565,
7807,
14667,
603,
2229,
316,
404,
73,
2643,
273,
261,
52,
380,
279,
9,
342,
404,
73,
2643,
13,
203,
203,
565,
603,
443,
1724,
30,
203,
565,
453,
300,
261,
52,
380,
279,
9,
13,
273,
2285,
203,
203,
565,
603,
598,
9446,
598,
3981,
14036,
16255,
30,
203,
565,
453,
273,
2285,
342,
261,
21,
300,
279,
9,
13,
203,
565,
2638,
4807,
312,
474,
329,
273,
2285,
203,
203,
565,
445,
443,
1724,
1435,
1071,
8843,
429,
1661,
426,
8230,
970,
1347,
1248,
28590,
288,
203,
3639,
2254,
460,
273,
2254,
12,
3576,
18,
1132,
1769,
203,
203,
3639,
2254,
3399,
4446,
14667,
273,
3981,
14667,
18,
16411,
12,
1132,
2934,
16411,
12,
21,
73,
2643,
2934,
2892,
12,
12398,
2173,
5126,
2934,
2892,
12,
21,
73,
2643,
1769,
540,
203,
3639,
2254,
1244,
18434,
4446,
273,
460,
18,
1717,
12,
4811,
4446,
14667,
1769,
203,
3639,
2254,
394,
9535,
5269,
273,
662,
5126,
24051,
18,
1289,
12,
1125,
18434,
4446,
1769,
203,
540,
203,
3639,
2583,
12,
2704,
9535,
5269,
1648,
1613,
18,
1289,
12,
1896,
5126,
24051,
1435,
3631,
315,
41,
451,
22,
510,
6388,
30,
323,
1724,
30,
6275,
4885,
7876,
16,
486,
7304,
11632,
2002,
8863,
203,
3639,
662,
5126,
24051,
273,
394,
9535,
5269,
31,
203,
3639,
3981,
14667,
5269,
273,
3981,
14667,
5269,
18,
1289,
12,
4811,
4446,
14667,
1769,
203,
3639,
605,
1584,
44,
1345,
18,
81,
474,
12,
2
] |
./full_match/5/0xb2cf1b2f138bD26282137e96De0346579386B77B/sources/_manifoldxyz/creator-core-solidity/contracts/core/ERC721CreatorCoreEnumerable.sol | * @dev Core ERC721 creator implementation (with enumerable api's)/ For enumerating tokens for a given extension For enumerating an extension's tokens for an owner | abstract contract ERC721CreatorCoreEnumerable is ERC721CreatorCore, IERC721CreatorCoreEnumerable {
using Strings for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
mapping (address => uint256) private _extensionBalances;
mapping (address => mapping(uint256 => uint256)) private _extensionTokens;
mapping (uint256 => uint256) private _extensionTokensIndex;
mapping (address => mapping(address => uint256)) private _extensionBalancesByOwner;
mapping (address => mapping(address => mapping(uint256 => uint256))) private _extensionTokensByOwner;
mapping (uint256 => uint256) private _extensionTokensIndexByOwner;
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721CreatorCore, IERC165) returns (bool) {
return interfaceId == type(IERC721CreatorCoreEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
function totalSupplyExtension(address extension) public view virtual override returns (uint256) {
requireNonBlacklist(extension);
return _extensionBalances[extension];
}
function tokenByIndexExtension(address extension, uint256 index) external view virtual override returns (uint256) {
requireNonBlacklist(extension);
require(index < totalSupplyExtension(extension), "ERC721Creator: Index out of bounds");
return _extensionTokens[extension][index];
}
function balanceOfExtension(address extension, address owner) public view virtual override returns (uint256) {
requireNonBlacklist(extension);
return _extensionBalancesByOwner[extension][owner];
}
function tokenOfOwnerByIndexExtension(address extension, address owner, uint256 index) external view virtual override returns (uint256) {
requireNonBlacklist(extension);
require(index < balanceOfExtension(extension, owner), "ERC721Creator: Index out of bounds");
return _extensionTokensByOwner[extension][owner][index];
}
function totalSupplyBase() public view virtual override returns (uint256) {
return _extensionBalances[address(0)];
}
function tokenByIndexBase(uint256 index) external view virtual override returns (uint256) {
require(index < totalSupplyBase(), "ERC721Creator: Index out of bounds");
return _extensionTokens[address(0)][index];
}
function balanceOfBase(address owner) public view virtual override returns (uint256) {
return _extensionBalancesByOwner[address(0)][owner];
}
function tokenOfOwnerByIndexBase(address owner, uint256 index) external view virtual override returns (uint256) {
require(index < balanceOfBase(owner), "ERC721Creator: Index out of bounds");
return _extensionTokensByOwner[address(0)][owner][index];
}
function _addTokenToOwnerEnumeration(address to, uint256 tokenId, address tokenExtension_) private {
uint256 lengthByOwner = balanceOfExtension(tokenExtension_, to);
_extensionTokensByOwner[tokenExtension_][to][lengthByOwner] = tokenId;
_extensionTokensIndexByOwner[tokenId] = lengthByOwner;
_extensionBalancesByOwner[tokenExtension_][to] += 1;
}
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId, address tokenExtension_) private {
uint256 lastTokenIndexByOwner = balanceOfExtension(tokenExtension_, from) - 1;
uint256 tokenIndexByOwner = _extensionTokensIndexByOwner[tokenId];
if (tokenIndexByOwner != lastTokenIndexByOwner) {
uint256 lastTokenIdByOwner = _extensionTokensByOwner[tokenExtension_][from][lastTokenIndexByOwner];
}
_extensionBalancesByOwner[tokenExtension_][from] -= 1;
delete _extensionTokensByOwner[tokenExtension_][from][lastTokenIndexByOwner];
}
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId, address tokenExtension_) private {
uint256 lastTokenIndexByOwner = balanceOfExtension(tokenExtension_, from) - 1;
uint256 tokenIndexByOwner = _extensionTokensIndexByOwner[tokenId];
if (tokenIndexByOwner != lastTokenIndexByOwner) {
uint256 lastTokenIdByOwner = _extensionTokensByOwner[tokenExtension_][from][lastTokenIndexByOwner];
}
_extensionBalancesByOwner[tokenExtension_][from] -= 1;
delete _extensionTokensByOwner[tokenExtension_][from][lastTokenIndexByOwner];
}
delete _extensionTokensIndexByOwner[tokenId];
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual {
if (from != address(0) && to != address(0)) {
address tokenExtension_ = _tokenExtension(tokenId);
if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId, tokenExtension_);
}
if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId, tokenExtension_);
}
}
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual {
if (from != address(0) && to != address(0)) {
address tokenExtension_ = _tokenExtension(tokenId);
if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId, tokenExtension_);
}
if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId, tokenExtension_);
}
}
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual {
if (from != address(0) && to != address(0)) {
address tokenExtension_ = _tokenExtension(tokenId);
if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId, tokenExtension_);
}
if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId, tokenExtension_);
}
}
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual {
if (from != address(0) && to != address(0)) {
address tokenExtension_ = _tokenExtension(tokenId);
if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId, tokenExtension_);
}
if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId, tokenExtension_);
}
}
}
function _postMintBase(address to, uint256 tokenId) internal virtual override {
uint256 length = totalSupplyBase();
_extensionTokens[address(0)][length] = tokenId;
_extensionTokensIndex[tokenId] = length;
_extensionBalances[address(0)] += 1;
_addTokenToOwnerEnumeration(to, tokenId, address(0));
}
function _postMintExtension(address to, uint256 tokenId) internal virtual override {
uint256 length = totalSupplyExtension(msg.sender);
_extensionTokens[msg.sender][length] = tokenId;
_extensionTokensIndex[tokenId] = length;
_extensionBalances[msg.sender] += 1;
_addTokenToOwnerEnumeration(to, tokenId, msg.sender);
}
function _postBurn(address owner, uint256 tokenId) internal override(ERC721CreatorCore) virtual {
address tokenExtension_ = _tokensExtension[tokenId];
uint256 lastTokenIndex = totalSupplyExtension(tokenExtension_) - 1;
uint256 tokenIndex = _extensionTokensIndex[tokenId];
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _extensionTokens[tokenExtension_][lastTokenIndex];
}
_extensionBalances[tokenExtension_] -= 1;
delete _extensionTokens[tokenExtension_][lastTokenIndex];
ERC721CreatorCore._postBurn(owner, tokenId);
}
function _postBurn(address owner, uint256 tokenId) internal override(ERC721CreatorCore) virtual {
address tokenExtension_ = _tokensExtension[tokenId];
uint256 lastTokenIndex = totalSupplyExtension(tokenExtension_) - 1;
uint256 tokenIndex = _extensionTokensIndex[tokenId];
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _extensionTokens[tokenExtension_][lastTokenIndex];
}
_extensionBalances[tokenExtension_] -= 1;
delete _extensionTokens[tokenExtension_][lastTokenIndex];
ERC721CreatorCore._postBurn(owner, tokenId);
}
delete _extensionTokensIndex[tokenId];
_removeTokenFromOwnerEnumeration(owner, tokenId, tokenExtension_);
} | 1,923,798 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
5206,
4586,
4232,
39,
27,
5340,
11784,
4471,
261,
1918,
14873,
1536,
1807,
13176,
2457,
3557,
1776,
2430,
364,
279,
864,
2710,
2457,
3557,
1776,
392,
2710,
1807,
2430,
364,
392,
3410,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
4232,
39,
27,
5340,
10636,
4670,
3572,
25121,
353,
4232,
39,
27,
5340,
10636,
4670,
16,
467,
654,
39,
27,
5340,
10636,
4670,
3572,
25121,
288,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
565,
1450,
6057,
25121,
694,
364,
6057,
25121,
694,
18,
1887,
694,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
6447,
38,
26488,
31,
203,
565,
2874,
261,
2867,
516,
2874,
12,
11890,
5034,
516,
2254,
5034,
3719,
3238,
389,
6447,
5157,
31,
203,
565,
2874,
261,
11890,
5034,
516,
2254,
5034,
13,
3238,
389,
6447,
5157,
1016,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
6447,
38,
26488,
858,
5541,
31,
203,
565,
2874,
261,
2867,
516,
2874,
12,
2867,
516,
2874,
12,
11890,
5034,
516,
2254,
5034,
20349,
3238,
389,
6447,
5157,
858,
5541,
31,
203,
565,
2874,
261,
11890,
5034,
516,
2254,
5034,
13,
3238,
389,
6447,
5157,
1016,
858,
5541,
31,
203,
203,
203,
203,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
1071,
1476,
5024,
3849,
12,
654,
39,
27,
5340,
10636,
4670,
16,
467,
654,
39,
28275,
13,
1135,
261,
6430,
13,
288,
203,
3639,
327,
1560,
548,
422,
618,
12,
45,
654,
39,
27,
5340,
10636,
4670,
3572,
25121,
2934,
5831,
548,
747,
2240,
18,
28064,
1358,
12,
5831,
548,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
2078,
3088,
1283,
3625,
12,
2867,
2710,
13,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
3989,
25811,
12,
6447,
1769,
203,
3639,
327,
389,
6447,
38,
26488,
63,
6447,
15533,
203,
565,
289,
203,
203,
565,
445,
1147,
21268,
3625,
12,
2867,
2710,
16,
2254,
5034,
770,
13,
3903,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
3989,
25811,
12,
6447,
1769,
203,
3639,
2583,
12,
1615,
411,
2078,
3088,
1283,
3625,
12,
6447,
3631,
315,
654,
39,
27,
5340,
10636,
30,
3340,
596,
434,
4972,
8863,
203,
3639,
327,
389,
6447,
5157,
63,
6447,
6362,
1615,
15533,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
3625,
12,
2867,
2710,
16,
1758,
3410,
13,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
3989,
25811,
12,
6447,
1769,
203,
3639,
327,
389,
6447,
38,
26488,
858,
5541,
63,
6447,
6362,
8443,
15533,
203,
565,
289,
203,
203,
565,
445,
1147,
951,
5541,
21268,
3625,
12,
2867,
2710,
16,
1758,
3410,
16,
2254,
5034,
770,
13,
3903,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
3989,
25811,
12,
6447,
1769,
203,
3639,
2583,
12,
1615,
411,
11013,
951,
3625,
12,
6447,
16,
3410,
3631,
315,
654,
39,
27,
5340,
10636,
30,
3340,
596,
434,
4972,
8863,
203,
3639,
327,
389,
6447,
5157,
858,
5541,
63,
6447,
6362,
8443,
6362,
1615,
15533,
203,
565,
289,
203,
203,
565,
445,
2078,
3088,
1283,
2171,
1435,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
6447,
38,
26488,
63,
2867,
12,
20,
13,
15533,
203,
565,
289,
203,
203,
565,
445,
1147,
21268,
2171,
12,
11890,
5034,
770,
13,
3903,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
1615,
411,
2078,
3088,
1283,
2171,
9334,
315,
654,
39,
27,
5340,
10636,
30,
3340,
596,
434,
4972,
8863,
203,
3639,
327,
389,
6447,
5157,
63,
2867,
12,
20,
13,
6362,
1615,
15533,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
2171,
12,
2867,
3410,
13,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
6447,
38,
26488,
858,
5541,
63,
2867,
12,
20,
13,
6362,
8443,
15533,
203,
565,
289,
203,
203,
565,
445,
1147,
951,
5541,
21268,
2171,
12,
2867,
3410,
16,
2254,
5034,
770,
13,
3903,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
1615,
411,
11013,
951,
2171,
12,
8443,
3631,
315,
654,
39,
27,
5340,
10636,
30,
3340,
596,
434,
4972,
8863,
203,
3639,
327,
389,
6447,
5157,
858,
5541,
63,
2867,
12,
20,
13,
6362,
8443,
6362,
1615,
15533,
203,
565,
289,
203,
203,
565,
445,
389,
1289,
1345,
774,
5541,
21847,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
16,
1758,
1147,
3625,
67,
13,
3238,
288,
203,
3639,
2254,
5034,
769,
858,
5541,
273,
11013,
951,
3625,
12,
2316,
3625,
67,
16,
358,
1769,
203,
3639,
389,
6447,
5157,
858,
5541,
63,
2316,
3625,
67,
6362,
869,
6362,
2469,
858,
5541,
65,
273,
1147,
548,
31,
203,
3639,
389,
6447,
5157,
1016,
858,
5541,
63,
2316,
548,
65,
273,
769,
858,
5541,
31,
203,
3639,
389,
6447,
38,
26488,
858,
5541,
63,
2316,
3625,
67,
6362,
869,
65,
1011,
404,
31,
540,
203,
565,
289,
203,
203,
565,
445,
389,
4479,
1345,
1265,
5541,
21847,
12,
2867,
628,
16,
2254,
5034,
1147,
548,
16,
1758,
1147,
3625,
67,
13,
3238,
288,
203,
3639,
2254,
5034,
27231,
1016,
858,
5541,
273,
11013,
951,
3625,
12,
2316,
3625,
67,
16,
628,
13,
300,
404,
31,
203,
3639,
2254,
5034,
1147,
1016,
858,
5541,
273,
389,
6447,
5157,
1016,
858,
5541,
63,
2316,
548,
15533,
203,
203,
3639,
309,
261,
2316,
1016,
858,
5541,
480,
27231,
1016,
858,
5541,
13,
288,
203,
5411,
2254,
5034,
27231,
548,
858,
5541,
273,
389,
6447,
5157,
858,
5541,
63,
2316,
3625,
67,
6362,
2080,
6362,
2722,
1345,
1016,
858,
5541,
15533,
203,
203,
3639,
289,
203,
3639,
389,
6447,
38,
26488,
858,
5541,
63,
2316,
3625,
67,
6362,
2080,
65,
3947,
404,
31,
203,
203,
3639,
1430,
389,
6447,
5157,
858,
5541,
63,
2316,
3625,
67,
6362,
2080,
6362,
2722,
1345,
1016,
858,
5541,
15533,
203,
565,
289,
203,
377,
203,
565,
445,
389,
4479,
1345,
1265,
5541,
21847,
12,
2867,
628,
16,
2254,
5034,
1147,
548,
16,
1758,
1147,
3625,
67,
13,
3238,
288,
203,
3639,
2254,
5034,
27231,
1016,
858,
5541,
273,
11013,
951,
3625,
12,
2316,
3625,
67,
16,
628,
13,
300,
404,
31,
203,
3639,
2254,
5034,
1147,
1016,
858,
5541,
273,
389,
6447,
5157,
1016,
858,
5541,
63,
2316,
548,
15533,
203,
2
] |
// SPDX-License-Identifier: MIT-open-group
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "contracts/libraries/governance/GovernanceMaxLock.sol";
import "contracts/libraries/StakingNFT/StakingNFTStorage.sol";
import "contracts/utils/ImmutableAuth.sol";
import "contracts/utils/EthSafeTransfer.sol";
import "contracts/utils/ERC20SafeTransfer.sol";
import "contracts/utils/MagicValue.sol";
import "contracts/interfaces/ICBOpener.sol";
import "contracts/interfaces/IStakingNFT.sol";
import "contracts/interfaces/IStakingNFTDescriptor.sol";
import {StakingNFTErrorCodes} from "contracts/libraries/errorCodes/StakingNFTErrorCodes.sol";
import {
CircuitBreakerErrorCodes
} from "contracts/libraries/errorCodes/CircuitBreakerErrorCodes.sol";
abstract contract StakingNFT is
Initializable,
ERC721Upgradeable,
StakingNFTStorage,
MagicValue,
EthSafeTransfer,
ERC20SafeTransfer,
GovernanceMaxLock,
ICBOpener,
IStakingNFT,
ImmutableFactory,
ImmutableValidatorPool,
ImmutableAToken,
ImmutableGovernance,
ImmutableStakingPositionDescriptor
{
// withCircuitBreaker is a modifier to enforce the CircuitBreaker must
// be set for a call to succeed
modifier withCircuitBreaker() {
require(
_circuitBreaker == _CIRCUIT_BREAKER_CLOSED,
string(abi.encodePacked(CircuitBreakerErrorCodes.CIRCUIT_BREAKER_OPENED))
);
_;
}
constructor()
ImmutableFactory(msg.sender)
ImmutableAToken()
ImmutableGovernance()
ImmutableValidatorPool()
ImmutableStakingPositionDescriptor()
{}
/// gets the current value for the Eth accumulator
function getEthAccumulator() external view returns (uint256 accumulator, uint256 slush) {
accumulator = _ethState.accumulator;
slush = _ethState.slush;
}
/// gets the current value for the Token accumulator
function getTokenAccumulator() external view returns (uint256 accumulator, uint256 slush) {
accumulator = _tokenState.accumulator;
slush = _tokenState.slush;
}
/// @dev tripCB opens the circuit breaker may only be called by _admin
function tripCB() public override onlyFactory {
_tripCB();
}
/// skimExcessEth will send to the address passed as to_ any amount of Eth
/// held by this contract that is not tracked by the Accumulator system. This
/// function allows the Admin role to refund any Eth sent to this contract in
/// error by a user. This method can not return any funds sent to the contract
/// via the depositEth method. This function should only be necessary if a
/// user somehow manages to accidentally selfDestruct a contract with this
/// contract as the recipient.
function skimExcessEth(address to_) public onlyFactory returns (uint256 excess) {
excess = _estimateExcessEth();
_safeTransferEth(to_, excess);
return excess;
}
/// skimExcessToken will send to the address passed as to_ any amount of
/// AToken held by this contract that is not tracked by the Accumulator
/// system. This function allows the Admin role to refund any AToken sent to
/// this contract in error by a user. This method can not return any funds
/// sent to the contract via the depositToken method.
function skimExcessToken(address to_) public onlyFactory returns (uint256 excess) {
IERC20Transferable aToken;
(aToken, excess) = _estimateExcessToken();
_safeTransferERC20(aToken, to_, excess);
return excess;
}
/// lockPosition is called by governance system when a governance
/// vote is cast. This function will lock the specified Position for up to
/// _MAX_GOVERNANCE_LOCK. This method may only be called by the governance
/// contract. This function will fail if the circuit breaker is tripped
function lockPosition(
address caller_,
uint256 tokenID_,
uint256 lockDuration_
) public override withCircuitBreaker onlyGovernance returns (uint256) {
require(
caller_ == ownerOf(tokenID_),
string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_CALLER_NOT_TOKEN_OWNER))
);
require(
lockDuration_ <= _MAX_GOVERNANCE_LOCK,
string(
abi.encodePacked(
StakingNFTErrorCodes.STAKENFT_LOCK_DURATION_GREATER_THAN_GOVERNANCE_LOCK
)
)
);
return _lockPosition(tokenID_, lockDuration_);
}
/// This function will lock an owned Position for up to _MAX_GOVERNANCE_LOCK. This method may
/// only be called by the owner of the Position. This function will fail if the circuit breaker
/// is tripped
function lockOwnPosition(uint256 tokenID_, uint256 lockDuration_)
public
withCircuitBreaker
returns (uint256)
{
require(
msg.sender == ownerOf(tokenID_),
string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_CALLER_NOT_TOKEN_OWNER))
);
require(
lockDuration_ <= _MAX_GOVERNANCE_LOCK,
string(
abi.encodePacked(
StakingNFTErrorCodes.STAKENFT_LOCK_DURATION_GREATER_THAN_GOVERNANCE_LOCK
)
)
);
return _lockPosition(tokenID_, lockDuration_);
}
/// This function will lock withdraws on the specified Position for up to
/// _MAX_GOVERNANCE_LOCK. This function will fail if the circuit breaker is tripped
function lockWithdraw(uint256 tokenID_, uint256 lockDuration_)
public
withCircuitBreaker
returns (uint256)
{
require(
msg.sender == ownerOf(tokenID_),
string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_CALLER_NOT_TOKEN_OWNER))
);
require(
lockDuration_ <= _MAX_GOVERNANCE_LOCK,
string(
abi.encodePacked(
StakingNFTErrorCodes.STAKENFT_LOCK_DURATION_GREATER_THAN_GOVERNANCE_LOCK
)
)
);
return _lockWithdraw(tokenID_, lockDuration_);
}
/// DO NOT CALL THIS METHOD UNLESS YOU ARE MAKING A DISTRIBUTION AS ALL VALUE
/// WILL BE DISTRIBUTED TO STAKERS EVENLY. depositToken distributes AToken
/// to all stakers evenly should only be called during a slashing event. Any
/// AToken sent to this method in error will be lost. This function will
/// fail if the circuit breaker is tripped. The magic_ parameter is intended
/// to stop some one from successfully interacting with this method without
/// first reading the source code and hopefully this comment
function depositToken(uint8 magic_, uint256 amount_)
public
withCircuitBreaker
checkMagic(magic_)
{
// collect tokens
_safeTransferFromERC20(IERC20Transferable(_aTokenAddress()), msg.sender, amount_);
// update state
_tokenState = _deposit(_shares, amount_, _tokenState);
_reserveToken += amount_;
}
/// DO NOT CALL THIS METHOD UNLESS YOU ARE MAKING A DISTRIBUTION ALL VALUE
/// WILL BE DISTRIBUTED TO STAKERS EVENLY depositEth distributes Eth to all
/// stakers evenly should only be called by BTokens contract any Eth sent to
/// this method in error will be lost this function will fail if the circuit
/// breaker is tripped the magic_ parameter is intended to stop some one from
/// successfully interacting with this method without first reading the
/// source code and hopefully this comment
function depositEth(uint8 magic_) public payable withCircuitBreaker checkMagic(magic_) {
_ethState = _deposit(_shares, msg.value, _ethState);
_reserveEth += msg.value;
}
/// mint allows a staking position to be opened. This function
/// requires the caller to have performed an approve invocation against
/// AToken into this contract. This function will fail if the circuit
/// breaker is tripped.
function mint(uint256 amount_) public virtual withCircuitBreaker returns (uint256 tokenID) {
return _mintNFT(msg.sender, amount_);
}
/// mintTo allows a staking position to be opened in the name of an
/// account other than the caller. This method also allows a lock to be
/// placed on the position up to _MAX_MINT_LOCK . This function requires the
/// caller to have performed an approve invocation against AToken into
/// this contract. This function will fail if the circuit breaker is
/// tripped.
function mintTo(
address to_,
uint256 amount_,
uint256 lockDuration_
) public virtual withCircuitBreaker returns (uint256 tokenID) {
require(
lockDuration_ <= _MAX_MINT_LOCK,
string(
abi.encodePacked(StakingNFTErrorCodes.STAKENFT_LOCK_DURATION_GREATER_THAN_MINT_LOCK)
)
);
tokenID = _mintNFT(to_, amount_);
if (lockDuration_ > 0) {
_lockPosition(tokenID, lockDuration_);
}
return tokenID;
}
/// burn exits a staking position such that all accumulated value is
/// transferred to the owner on burn.
function burn(uint256 tokenID_)
public
virtual
returns (uint256 payoutEth, uint256 payoutAToken)
{
return _burn(msg.sender, msg.sender, tokenID_);
}
/// burnTo exits a staking position such that all accumulated value
/// is transferred to a specified account on burn
function burnTo(address to_, uint256 tokenID_)
public
virtual
returns (uint256 payoutEth, uint256 payoutAToken)
{
return _burn(msg.sender, to_, tokenID_);
}
/// collectEth returns all due Eth allocations to caller. The caller
/// of this function must be the owner of the tokenID
function collectEth(uint256 tokenID_) public returns (uint256 payout) {
address owner = ownerOf(tokenID_);
require(
msg.sender == owner,
string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_CALLER_NOT_TOKEN_OWNER))
);
Position memory position = _positions[tokenID_];
require(
_positions[tokenID_].withdrawFreeAfter < block.number,
string(
abi.encodePacked(
StakingNFTErrorCodes.STAKENFT_LOCK_DURATION_WITHDRAW_TIME_NOT_REACHED
)
)
);
// get values and update state
(_positions[tokenID_], payout) = _collectEth(_shares, position);
_reserveEth -= payout;
// perform transfer and return amount paid out
_safeTransferEth(owner, payout);
return payout;
}
/// collectToken returns all due AToken allocations to caller. The
/// caller of this function must be the owner of the tokenID
function collectToken(uint256 tokenID_) public returns (uint256 payout) {
address owner = ownerOf(tokenID_);
require(
msg.sender == owner,
string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_CALLER_NOT_TOKEN_OWNER))
);
Position memory position = _positions[tokenID_];
require(
position.withdrawFreeAfter < block.number,
string(
abi.encodePacked(
StakingNFTErrorCodes.STAKENFT_LOCK_DURATION_WITHDRAW_TIME_NOT_REACHED
)
)
);
// get values and update state
(_positions[tokenID_], payout) = _collectToken(_shares, position);
_reserveToken -= payout;
// perform transfer and return amount paid out
_safeTransferERC20(IERC20Transferable(_aTokenAddress()), owner, payout);
return payout;
}
/// collectEth returns all due Eth allocations to the to_ address. The caller
/// of this function must be the owner of the tokenID
function collectEthTo(address to_, uint256 tokenID_) public returns (uint256 payout) {
address owner = ownerOf(tokenID_);
require(
msg.sender == owner,
string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_CALLER_NOT_TOKEN_OWNER))
);
Position memory position = _positions[tokenID_];
require(
_positions[tokenID_].withdrawFreeAfter < block.number,
string(
abi.encodePacked(
StakingNFTErrorCodes.STAKENFT_LOCK_DURATION_WITHDRAW_TIME_NOT_REACHED
)
)
);
// get values and update state
(_positions[tokenID_], payout) = _collectEth(_shares, position);
_reserveEth -= payout;
// perform transfer and return amount paid out
_safeTransferEth(to_, payout);
return payout;
}
/// collectTokenTo returns all due AToken allocations to the to_ address. The
/// caller of this function must be the owner of the tokenID
function collectTokenTo(address to_, uint256 tokenID_) public returns (uint256 payout) {
address owner = ownerOf(tokenID_);
require(
msg.sender == owner,
string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_CALLER_NOT_TOKEN_OWNER))
);
Position memory position = _positions[tokenID_];
require(
position.withdrawFreeAfter < block.number,
string(
abi.encodePacked(
StakingNFTErrorCodes.STAKENFT_LOCK_DURATION_WITHDRAW_TIME_NOT_REACHED
)
)
);
// get values and update state
(_positions[tokenID_], payout) = _collectToken(_shares, position);
_reserveToken -= payout;
// perform transfer and return amount paid out
_safeTransferERC20(IERC20Transferable(_aTokenAddress()), to_, payout);
return payout;
}
function circuitBreakerState() public view returns (bool) {
return _circuitBreaker;
}
/// gets the total amount of AToken staked in contract
function getTotalShares() public view returns (uint256) {
return _shares;
}
/// gets the total amount of Ether staked in contract
function getTotalReserveEth() public view returns (uint256) {
return _reserveEth;
}
/// gets the total amount of AToken staked in contract
function getTotalReserveAToken() public view returns (uint256) {
return _reserveToken;
}
/// estimateEthCollection returns the amount of eth a tokenID may withdraw
function estimateEthCollection(uint256 tokenID_) public view returns (uint256 payout) {
require(
_exists(tokenID_),
string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_INVALID_TOKEN_ID))
);
Position memory p = _positions[tokenID_];
(, , , payout) = _collect(_shares, _ethState, p, p.accumulatorEth);
return payout;
}
/// estimateTokenCollection returns the amount of AToken a tokenID may withdraw
function estimateTokenCollection(uint256 tokenID_) public view returns (uint256 payout) {
require(
_exists(tokenID_),
string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_INVALID_TOKEN_ID))
);
Position memory p = _positions[tokenID_];
(, , , payout) = _collect(_shares, _tokenState, p, p.accumulatorToken);
return payout;
}
/// estimateExcessToken returns the amount of AToken that is held in the
/// name of this contract. The value returned is the value that would be
/// returned by a call to skimExcessToken.
function estimateExcessToken() public view returns (uint256 excess) {
(, excess) = _estimateExcessToken();
return excess;
}
/// estimateExcessEth returns the amount of Eth that is held in the name of
/// this contract. The value returned is the value that would be returned by
/// a call to skimExcessEth.
function estimateExcessEth() public view returns (uint256 excess) {
return _estimateExcessEth();
}
/// gets the position struct given a tokenID. The tokenId must
/// exist.
function getPosition(uint256 tokenID_)
public
view
returns (
uint256 shares,
uint256 freeAfter,
uint256 withdrawFreeAfter,
uint256 accumulatorEth,
uint256 accumulatorToken
)
{
require(
_exists(tokenID_),
string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_INVALID_TOKEN_ID))
);
Position memory p = _positions[tokenID_];
shares = uint256(p.shares);
freeAfter = uint256(p.freeAfter);
withdrawFreeAfter = uint256(p.withdrawFreeAfter);
accumulatorEth = p.accumulatorEth;
accumulatorToken = p.accumulatorToken;
}
/// Gets token URI
function tokenURI(uint256 tokenId)
public
view
override(ERC721Upgradeable)
returns (string memory)
{
require(
_exists(tokenId),
string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_INVALID_TOKEN_ID))
);
return IStakingNFTDescriptor(_stakingPositionDescriptorAddress()).tokenURI(this, tokenId);
}
/// gets the _ACCUMULATOR_SCALE_FACTOR used to scale the ether and tokens
/// deposited on this contract to reduce the integer division errors.
function getAccumulatorScaleFactor() public pure returns (uint256) {
return _ACCUMULATOR_SCALE_FACTOR;
}
/// gets the _MAX_MINT_LOCK value. This value is the maximum duration of blocks that we allow a
/// position to be locked
function getMaxMintLock() public pure returns (uint256) {
return _MAX_MINT_LOCK;
}
function __stakingNFTInit(string memory name_, string memory symbol_)
internal
onlyInitializing
{
__ERC721_init(name_, symbol_);
}
// _lockPosition prevents a position from being burned for duration_ number
// of blocks by setting the freeAfter field on the Position struct returns
// the number of shares in the locked Position so that governance vote
// counting may be performed when setting a lock
function _lockPosition(uint256 tokenID_, uint256 duration_) internal returns (uint256 shares) {
require(
_exists(tokenID_),
string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_INVALID_TOKEN_ID))
);
Position memory p = _positions[tokenID_];
uint32 freeDur = uint32(block.number) + uint32(duration_);
p.freeAfter = freeDur > p.freeAfter ? freeDur : p.freeAfter;
_positions[tokenID_] = p;
return p.shares;
}
// _lockWithdraw prevents a position from being collected and burned for duration_ number of blocks
// by setting the withdrawFreeAfter field on the Position struct.
// returns the number of shares in the locked Position so that
function _lockWithdraw(uint256 tokenID_, uint256 duration_) internal returns (uint256 shares) {
require(
_exists(tokenID_),
string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_INVALID_TOKEN_ID))
);
Position memory p = _positions[tokenID_];
uint256 freeDur = block.number + duration_;
p.withdrawFreeAfter = freeDur > p.withdrawFreeAfter ? freeDur : p.withdrawFreeAfter;
_positions[tokenID_] = p;
return p.shares;
}
// _mintNFT performs the mint operation and invokes the inherited _mint method
function _mintNFT(address to_, uint256 amount_) internal returns (uint256 tokenID) {
// this is to allow struct packing and is safe due to AToken having a
// total distribution of 220M
require(
amount_ <= 2**224 - 1,
string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_MINT_AMOUNT_EXCEEDS_MAX_SUPPLY))
);
// transfer the number of tokens specified by amount_ into contract
// from the callers account
_safeTransferFromERC20(IERC20Transferable(_aTokenAddress()), msg.sender, amount_);
// get local copy of storage vars to save gas
uint256 shares = _shares;
Accumulator memory ethState = _ethState;
Accumulator memory tokenState = _tokenState;
// get new tokenID from counter
tokenID = _increment();
// update storage
shares += amount_;
_shares = shares;
_positions[tokenID] = Position(
uint224(amount_),
uint32(block.number) + 1,
uint32(block.number) + 1,
ethState.accumulator,
tokenState.accumulator
);
_reserveToken += amount_;
// invoke inherited method and return
ERC721Upgradeable._mint(to_, tokenID);
return tokenID;
}
// _burn performs the burn operation and invokes the inherited _burn method
function _burn(
address from_,
address to_,
uint256 tokenID_
) internal returns (uint256 payoutEth, uint256 payoutToken) {
require(
from_ == ownerOf(tokenID_),
string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_CALLER_NOT_TOKEN_OWNER))
);
// collect state
Position memory p = _positions[tokenID_];
// enforce freeAfter to prevent burn during lock
require(
p.freeAfter < block.number && p.withdrawFreeAfter < block.number,
string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_FREE_AFTER_TIME_NOT_REACHED))
);
// get copy of storage to save gas
uint256 shares = _shares;
// calc Eth amounts due
(p, payoutEth) = _collectEth(shares, p);
// calc token amounts due
(p, payoutToken) = _collectToken(shares, p);
// add back to token payout the original stake position
payoutToken += p.shares;
// debit global shares counter and delete from mapping
_shares -= p.shares;
_reserveToken -= payoutToken;
_reserveEth -= payoutEth;
delete _positions[tokenID_];
// invoke inherited burn method
ERC721Upgradeable._burn(tokenID_);
// transfer out all eth and tokens owed
_safeTransferERC20(IERC20Transferable(_aTokenAddress()), to_, payoutToken);
_safeTransferEth(to_, payoutEth);
return (payoutEth, payoutToken);
}
function _collectToken(uint256 shares_, Position memory p_)
internal
returns (Position memory p, uint256 payout)
{
uint256 acc;
(_tokenState, p, acc, payout) = _collect(shares_, _tokenState, p_, p_.accumulatorToken);
p.accumulatorToken = acc;
return (p, payout);
}
// _collectEth performs call to _collect and updates state during a request
// for an eth distribution
function _collectEth(uint256 shares_, Position memory p_)
internal
returns (Position memory p, uint256 payout)
{
uint256 acc;
(_ethState, p, acc, payout) = _collect(shares_, _ethState, p_, p_.accumulatorEth);
p.accumulatorEth = acc;
return (p, payout);
}
function _tripCB() internal {
require(
_circuitBreaker == _CIRCUIT_BREAKER_CLOSED,
string(abi.encodePacked(CircuitBreakerErrorCodes.CIRCUIT_BREAKER_OPENED))
);
_circuitBreaker = _CIRCUIT_BREAKER_OPENED;
}
function _resetCB() internal {
require(
_circuitBreaker == _CIRCUIT_BREAKER_OPENED,
string(abi.encodePacked(CircuitBreakerErrorCodes.CIRCUIT_BREAKER_CLOSED))
);
_circuitBreaker = _CIRCUIT_BREAKER_CLOSED;
}
// _newTokenID increments the counter and returns the new value
function _increment() internal returns (uint256 count) {
count = _counter;
count += 1;
_counter = count;
return count;
}
// _estimateExcessEth returns the amount of Eth that is held in the name of
// this contract
function _estimateExcessEth() internal view returns (uint256 excess) {
uint256 reserve = _reserveEth;
uint256 balance = address(this).balance;
require(
balance >= reserve,
string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_BALANCE_LESS_THAN_RESERVE))
);
excess = balance - reserve;
}
// _estimateExcessToken returns the amount of AToken that is held in the
// name of this contract
function _estimateExcessToken()
internal
view
returns (IERC20Transferable aToken, uint256 excess)
{
uint256 reserve = _reserveToken;
aToken = IERC20Transferable(_aTokenAddress());
uint256 balance = aToken.balanceOf(address(this));
require(
balance >= reserve,
string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_BALANCE_LESS_THAN_RESERVE))
);
excess = balance - reserve;
return (aToken, excess);
}
function _getCount() internal view returns (uint256) {
return _counter;
}
// _collect performs calculations necessary to determine any distributions
// due to an account such that it may be used for both token and eth
// distributions this prevents the need to keep redundant logic
function _collect(
uint256 shares_,
Accumulator memory state_,
Position memory p_,
uint256 positionAccumulatorValue_
)
internal
pure
returns (
Accumulator memory,
Position memory,
uint256,
uint256
)
{
// determine number of accumulator steps this Position needs distributions from
uint256 accumulatorDelta = 0;
if (positionAccumulatorValue_ > state_.accumulator) {
accumulatorDelta = type(uint168).max - positionAccumulatorValue_;
accumulatorDelta += state_.accumulator;
positionAccumulatorValue_ = state_.accumulator;
} else {
accumulatorDelta = state_.accumulator - positionAccumulatorValue_;
// update accumulator value for calling method
positionAccumulatorValue_ += accumulatorDelta;
}
// calculate payout based on shares held in position
uint256 payout = accumulatorDelta * p_.shares;
// if there are no shares other than this position, flush the slush fund
// into the payout and update the in memory state object
if (shares_ == p_.shares) {
payout += state_.slush;
state_.slush = 0;
}
uint256 payoutRemainder = payout;
// reduce payout by scale factor
payout /= _ACCUMULATOR_SCALE_FACTOR;
// Computing and saving the numeric error from the floor division in the
// slush.
payoutRemainder -= payout * _ACCUMULATOR_SCALE_FACTOR;
state_.slush += payoutRemainder;
return (state_, p_, positionAccumulatorValue_, payout);
}
// _deposit allows an Accumulator to be updated with new value if there are
// no currently staked positions, all value is stored in the slush
function _deposit(
uint256 shares_,
uint256 delta_,
Accumulator memory state_
) internal pure returns (Accumulator memory) {
state_.slush += (delta_ * _ACCUMULATOR_SCALE_FACTOR);
if (shares_ > 0) {
(state_.accumulator, state_.slush) = _slushSkim(
shares_,
state_.accumulator,
state_.slush
);
}
// Slush should be never be above 2**167 to protect against overflow in
// the later code.
require(
state_.slush < 2**167,
string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_SLUSH_TOO_LARGE))
);
return state_;
}
// _slushSkim flushes value from the slush into the accumulator if there are
// no currently staked positions, all value is stored in the slush
function _slushSkim(
uint256 shares_,
uint256 accumulator_,
uint256 slush_
) internal pure returns (uint256, uint256) {
if (shares_ > 0) {
uint256 deltaAccumulator = slush_ / shares_;
slush_ -= deltaAccumulator * shares_;
accumulator_ += deltaAccumulator;
// avoiding accumulator_ overflow.
if (accumulator_ > type(uint168).max) {
// The maximum allowed value for the accumulator is 2**168-1.
// This hard limit was set to not overflow the operation
// `accumulator * shares` that happens later in the code.
accumulator_ = accumulator_ % type(uint168).max;
}
}
return (accumulator_, slush_);
}
}
| _slushSkim flushes value from the slush into the accumulator if there are no currently staked positions, all value is stored in the slush avoiding accumulator_ overflow. The maximum allowed value for the accumulator is 2**168-1. This hard limit was set to not overflow the operation `accumulator * shares` that happens later in the code. | function _slushSkim(
uint256 shares_,
uint256 accumulator_,
uint256 slush_
) internal pure returns (uint256, uint256) {
if (shares_ > 0) {
uint256 deltaAccumulator = slush_ / shares_;
slush_ -= deltaAccumulator * shares_;
accumulator_ += deltaAccumulator;
if (accumulator_ > type(uint168).max) {
accumulator_ = accumulator_ % type(uint168).max;
}
}
return (accumulator_, slush_);
}
| 7,278,446 | [
1,
4625,
348,
7953,
560,
30,
225,
389,
2069,
1218,
5925,
381,
3663,
281,
460,
628,
326,
2020,
1218,
1368,
326,
13514,
309,
1915,
854,
1158,
4551,
384,
9477,
6865,
16,
777,
460,
353,
4041,
316,
326,
2020,
1218,
4543,
310,
13514,
67,
9391,
18,
1021,
4207,
2935,
460,
364,
326,
13514,
353,
576,
636,
23329,
17,
21,
18,
1220,
7877,
1800,
1703,
444,
358,
486,
9391,
326,
1674,
1375,
8981,
18514,
380,
24123,
68,
716,
10555,
5137,
316,
326,
981,
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,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2069,
1218,
5925,
381,
12,
203,
3639,
2254,
5034,
24123,
67,
16,
203,
3639,
2254,
5034,
13514,
67,
16,
203,
3639,
2254,
5034,
2020,
1218,
67,
203,
565,
262,
2713,
16618,
1135,
261,
11890,
5034,
16,
2254,
5034,
13,
288,
203,
3639,
309,
261,
30720,
67,
405,
374,
13,
288,
203,
5411,
2254,
5034,
3622,
27361,
273,
2020,
1218,
67,
342,
24123,
67,
31,
203,
5411,
2020,
1218,
67,
3947,
3622,
27361,
380,
24123,
67,
31,
203,
5411,
13514,
67,
1011,
3622,
27361,
31,
203,
5411,
309,
261,
8981,
18514,
67,
405,
618,
12,
11890,
23329,
2934,
1896,
13,
288,
203,
7734,
13514,
67,
273,
13514,
67,
738,
618,
12,
11890,
23329,
2934,
1896,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
261,
8981,
18514,
67,
16,
2020,
1218,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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
// File: contracts/NormieLib.sol
pragma solidity ^0.8.9;
// @author TheNormiesNFT (https://twitter.com/thenormiesnft)
library NormieLib {
struct Normie {
uint32 skinType; // Max number is 4,294,967,296
uint32 hair;
uint32 eyes;
uint32 mouth;
uint32 torso;
uint32 pants;
uint32 shoes;
uint32 accessoryOne;
uint32 accessoryTwo;
uint32 accessoryThree;
}
struct Trait {
string traitName;
string traitType;
string hash;
uint16 pixelCount;
uint32 traitID;
}
string internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/*
* @dev Function taken from Brecht Devos - <[email protected]>
*/
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return "";
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {
} lt(dataPtr, endPtr) {
} {
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(input, 0x3F))))
)
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
}
return result;
}
/*
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "a";
}
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);
}
function parseInt(string memory _a) internal pure
returns (uint8 _parsedInt) {
bytes memory bresult = bytes(_a);
uint8 mint = 0;
for (uint8 i = 0; i < bresult.length; i++) {
if (
(uint8(uint8(bresult[i])) >= 48) &&
(uint8(uint8(bresult[i])) <= 57)
) {
mint *= 10;
mint += uint8(bresult[i]) - 48;
}
}
return mint;
}
/*
* @dev Returns a substring from [startIndex, endIndex)
*/
function substring(string memory str, uint256 startIndex, uint256 endIndex) internal pure
returns (string memory) {
bytes memory strBytes = bytes(str);
bytes memory result = new bytes(endIndex - startIndex);
for (uint256 i = startIndex; i < endIndex; i++) {
result[i - startIndex] = strBytes[i];
}
return string(result);
}
}
// File: contracts/NormieTraits.sol
pragma solidity ^0.8.9;
// @author TheNormiesNFT (https://twitter.com/thenormiesnft)
contract NormieTraits {
using NormieLib for uint8;
// Private variables
address private owner;
uint256 private SEED_NONCE = 0;
mapping(address => bool) private adminAccess;
NormieLib.Trait private emptyTrait = NormieLib.Trait("Empty", "Empty", "", 0, 1000001);
// Public variables
string public colorString = ".c000{fill:#503e38}.c001{fill:#228b22}.c002{fill:#562c1a}.c003{fill:#313131}.c004{fill:#fee761}.c005{fill:#ff0044}"
".c006{fill:#ffffff}.c007{fill:#01badb}.c008{fill:#b9f2ff}.c009{fill:#000000}.c00A{fill:#01f8fc}.c00B{fill:#0088fc}.c00C{fill:#039112}.c00D{fill:#1a3276}"
".c00E{fill:#e2646d}.c00F{fill:#ea8c8f}.c00G{fill:#f6757a}.c00H{fill:#7234b2}.c00I{fill:#b881ef}.c00J{fill:#b90e0a}.c00K{fill:#e43b44}.c00L{fill:#f5999e}"
".c00M{fill:#1258d3}.c00N{fill:#733e39}.c00O{fill:#2dcf51}.c00P{fill:#260701}.c00Q{fill:#743d2b}.c00R{fill:#dcbeb5}.c00S{fill:#e8b796}.c00T{fill:#67371a}"
".c00U{fill:#874f2e}.c00V{fill:#182812}.c00W{fill:#115c35}.c00X{fill:#ff9493}.c00Y{fill:#a22633}.c00Z{fill:#302f2f}.c010{fill:#f0d991}.c011{fill:#f2e7c7}"
".c012{fill:#0099db}.c013{fill:#2ce8f5}.c014{fill:#124e89}.c015{fill:#b86f50}.c016{fill:#777777}.c017{fill:#afafaf}.c018{fill:#878787}.c019{fill:#ffed1b}"
".c01A{fill:#1b1a1b}.c01B{fill:#131314}.c01C{fill:#191970}.c01D{fill:#bb8b1f}.c01E{fill:#f8f7ed}.c01F{fill:#072083}.c01G{fill:#f65c1a}.c01H{fill:#4b5320}"
".c01I{fill:#8a9294}.c01J{fill:#969cba}.c01K{fill:#c0c0c0}.c01L{fill:#8c92ac}.c01M{fill:#01796f}.c01N{fill:#ce1141}.c01O{fill:#ff007f}.c01P{fill:#b6005b}"
".c01Q{fill:#feed26}.c01R{fill:#dccd21}.c01S{fill:#080808}.c01T{fill:#b2ffff}.c01U{fill:#18a8d8}.c01V{fill:#818589}.c01W{fill:#98fb98}.c01X{fill:#e0c4ff}"
".c01Y{fill:#e1c4ff}.c01Z{fill:#c0a8da}.c020{fill:#ce2029}.c021{fill:#b01b23}.c022{fill:#87ceeb}.c023{fill:#ff0000}";
uint32 public CURRENT_TRAIT = 1;
// Storage of all previous collections
mapping(uint256 => uint256[]) public currentCollectionTraits;
mapping(uint256 => NormieLib.Trait) public traitIDToTrait;
string[] LETTERS = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
// Array of the current trait rarity available in the current collection with 10 traits total
uint256[][10] public traitRarity;
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner == msg.sender, "Not the owner");
_;
}
/**
* @dev Throws if called by an account that does not have adminAccess.
*/
modifier onlyAdmin() {
require(adminAccess[msg.sender], "No admin access");
_;
}
constructor() {
owner = msg.sender;
// Register the Empty trait.
traitIDToTrait[1000001] = emptyTrait;
traitRarity[0] = [2500, 5000, 7500, 10000];
traitRarity[1] = [400, 800, 1600, 2400, 3200, 4200, 5200, 6600, 8000, 10000];
traitRarity[2] = [800, 1600, 2800, 4000, 5500, 7000, 8500, 10000];
traitRarity[3] = [200, 400, 1300, 2200, 4150, 6100, 8050, 10000];
traitRarity[4] = [200, 800, 1400, 2000, 3000, 4000, 5000, 6600, 8200, 10000];
traitRarity[5] = [200, 600, 1600, 2800, 4000, 6000, 8000, 10000];
traitRarity[6] = [100, 600, 1100, 2600, 4100, 7050, 10000];
traitRarity[7] = [100,600,1100,2100,10000];
traitRarity[8] = [100,800,2400,4400,10000];
traitRarity[9] = [100,600,2100,10000];
}
///////////////////////////// ONLY ADMIN FUNCTIONS /////////////////////////////
/**
* @dev Function used to generate a Normie.
* @param tokenID The token ID of the new Normie.
* @param _address The address that will own the Normie. Used in hashing function.
* @return Edited normie. Used by mintNormie function in Normies.sol.
*/
function generateNormie(uint256 tokenID, address _address) external onlyAdmin
returns (NormieLib.Normie memory) {
for (uint256 i=0; i < 10; i++){
require(traitRarity[i].length == currentCollectionTraits[i].length, "Trait arrays mismatch");
}
uint256[] memory generatedHash = hash(tokenID, _address);
return NormieLib.Normie(
uint32(currentCollectionTraits[0][generatedHash[0]]),
uint32(currentCollectionTraits[1][generatedHash[1]]),
uint32(currentCollectionTraits[2][generatedHash[2]]),
uint32(currentCollectionTraits[3][generatedHash[3]]),
uint32(currentCollectionTraits[4][generatedHash[4]]),
uint32(currentCollectionTraits[5][generatedHash[5]]),
uint32(currentCollectionTraits[6][generatedHash[6]]),
uint32(currentCollectionTraits[7][generatedHash[7]]),
uint32(currentCollectionTraits[8][generatedHash[8]]),
uint32(currentCollectionTraits[9][generatedHash[9]])
);
}
/*
* @dev Generates a array of length 10 that contains what indexes to use for each trait.
* @param _t The token id to be used within the hash.
* @param _a The address to be used within the hash.
* @return An array of size 10 with integers representing the trait within the current collection to use.
*/
function hash(uint256 _t, address _a) public onlyAdmin
returns (uint256[] memory) {
// This will generate a 10 trait array. All values in the array are random.
uint256[] memory ret = new uint[](10);
uint counter = SEED_NONCE;
uint256 _randinput = 0;
uint256 left = 0;
uint256 right = 0;
uint256 mid = 0;
uint256 traitRarityValue = 0;
for (uint256 i = 0; i <= 9; i++) {
counter++;
_randinput =
uint256(
keccak256(
abi.encodePacked(
block.timestamp,
block.difficulty,
_t,
_a,
counter
)
)
) % 10000;
left = 0;
right = traitRarity[i].length - 1;
// Binary search for the index
while (left < right){
mid = (left + right) / 2;
traitRarityValue = traitRarity[i][mid];
if (traitRarityValue == _randinput){
left = mid;
break;
}
else if (traitRarityValue < _randinput){
left = mid + 1;
} else {
right = mid;
}
}
ret[i] = left;
}
SEED_NONCE = counter;
return ret;
}
///////////////////////////// PUBLIC READ FUNCTIONS /////////////////////////////
/*
* @dev Hash to SVG function for a normie.
* @param normie The Normie that we are getting the URI of.
* @param normieID the ID of the normie.
* @return URI of a Normie as a string.
*/
function getNormieURI(NormieLib.Normie memory normie, uint256 normieID) external view returns (string memory) {
return string(
abi.encodePacked(
"data:application/json;base64,",
NormieLib.encode(
bytes(string(abi.encodePacked(
'{"name": "Normie #',
NormieLib.toString(normieID),
'", "description": "Normies are generated and stored 100% on the blockchain.", "image": "data:image/svg+xml;base64,',
NormieLib.encode(
bytes(normieToSVG(normie))
),
'","attributes":',
getMainTraitsString(normie),
getOptionalTraitsString(normie),
"}")))
)));
}
/*
* @dev Returns Asset URI for a given trait.
* @param assetID The ID of the asset we are getting the URI of.
* @return URI of an asset as a string.
*/
function getAssetURI(uint256 assetID) external view returns (string memory) {
NormieLib.Trait memory trait = traitIDToTrait[assetID];
return string(
abi.encodePacked(
"data:application/json;base64,",
NormieLib.encode(
bytes(
string(
abi.encodePacked(
'{"name": "',
trait.traitName,
'", "description": "Normie assets are generated and stored 100% on the blockchain.", "image": "data:image/svg+xml;base64,',
NormieLib.encode(
bytes(assetToSVG(assetID))
),
'","attributes":',
getSingleTraitString(trait),
"}"
)
)
)
)
)
);
}
/**
* @dev Gets a trait by its ID number using the provided "traitID" and returns its trait type. Used in Normies.sol
* @param traitID The traitID to get from the traitIDToTrait mapping.
* @return string object.
*/
function getTraitTypeByTraitID(uint256 traitID) external view returns (string memory){
return traitIDToTrait[traitID].traitType;
}
/**
* @dev Gets a trait from the current collection using the provided "traitIndex" and "index".
* Used in minting function.
* @param traitIndex The index which indicates what type of trait it is [0-9].
* @param index The index of the specific trait to grab. Variable array size depending on collection.
* @return Trait object.
*/
function getTraitFromCurrentCollection(uint256 traitIndex, uint256 index) public view
returns (NormieLib.Trait memory) {
return traitIDToTrait[currentCollectionTraits[traitIndex][index]];
}
///////////////////////////// PRIVATE READ FUNCTIONS /////////////////////////////
/*
* @notice Adapted function from Anonymice contract
* @dev Hash to SVG function for normie.
* @param normie The Normie object to generate an SVG image for.
* @return Normie SVG as a string.
*/
function normieToSVG(NormieLib.Normie memory normie) private view returns (string memory) {
string memory svgString;
for (uint8 i = 0; i <= 9; i++) {
NormieLib.Trait memory trait = getNormieTraitObject(normie, i);
for (uint16 j = 0; j < trait.pixelCount; j++) {
string memory thisPixel = NormieLib.substring(trait.hash, j * 5, j * 5 + 5);
uint8 x = letterToNumber(NormieLib.substring(thisPixel, 0, 1));
uint8 y = letterToNumber(NormieLib.substring(thisPixel, 1, 2));
svgString = string(
abi.encodePacked(
svgString,
"<rect class='c",
NormieLib.substring(thisPixel, 2, 5),
"' x='",
x.toString(),
"' y='",
y.toString(),
"'/>"
)
);
}
}
svgString = string(
abi.encodePacked(
'<svg id="normie-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ',
svgString,
"<style>rect{width:1px;height:1px;} #normie-svg{shape-rendering: crispedges;} ",
colorString,
"</style></svg>"
)
);
return svgString;
}
/*
* @notice Adapted function from Anonymice contract
* @dev Hash to SVG function for a trait.
* @param assetID The assetID for the trait we want to create an SVG for.
* @return Asset SVG as a string.
*/
function assetToSVG(uint256 assetID) private view returns (string memory) {
NormieLib.Trait memory trait = traitIDToTrait[assetID];
string memory svgString;
for (uint16 j = 0; j < trait.pixelCount; j++) {
string memory thisPixel = NormieLib.substring(trait.hash, j * 5, j * 5 + 5);
uint8 x = letterToNumber(NormieLib.substring(thisPixel, 0, 1));
uint8 y = letterToNumber(NormieLib.substring(thisPixel, 1, 2));
svgString = string(
abi.encodePacked(
svgString,
"<rect class='c",
NormieLib.substring(thisPixel, 2, 5),
"' x='",
x.toString(),
"' y='",
y.toString(),
"'/>"
)
);
}
svgString = string(
abi.encodePacked(
'<svg id="normie-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ',
svgString,
"<style>rect{width:1px;height:1px;} #normie-svg{shape-rendering: crispedges;} ",
colorString,
"</style></svg>"
)
);
return svgString;
}
/*
* @notice Original author is Anonymice.
* @dev Helper function to reduce pixel size within contract.
* @param _inputLetter The letter to change from base26 to base10.
* @return A base 10 number.
*/
function letterToNumber(string memory _inputLetter) private view returns (uint8) {
for (uint8 i = 0; i < LETTERS.length; i++) {
if (
keccak256(abi.encodePacked((LETTERS[i]))) ==
keccak256(abi.encodePacked((_inputLetter)))
) return (i);
}
revert();
}
/*
* @dev Gets the trait for a given "normie" using the provided "traitIndex".
* @param normie The normie whose trait we want to get.
* @param traitIndex Index that determines which trait to return [0-9].
* @return Trait object.
*/
function getNormieTraitObject(NormieLib.Normie memory normie, uint256 traitIndex) private view returns (NormieLib.Trait memory) {
if (traitIndex == 0) {
return traitIDToTrait[normie.skinType];
} else if (traitIndex == 1) {
return traitIDToTrait[normie.pants];
} else if (traitIndex == 2){
return traitIDToTrait[normie.shoes];
} else if (traitIndex == 3) {
return traitIDToTrait[normie.torso];
} else if (traitIndex == 4) {
return traitIDToTrait[normie.mouth];
} else if (traitIndex == 5) {
return traitIDToTrait[normie.eyes];
} else if (traitIndex == 6) {
return traitIDToTrait[normie.hair];
} else if (traitIndex == 7) {
return traitIDToTrait[normie.accessoryOne];
} else if (traitIndex == 8) {
return traitIDToTrait[normie.accessoryTwo];
} else {
return traitIDToTrait[normie.accessoryThree];
}
}
/*
* @dev Generates the string metadata for base Normie traits.
* @param normie The normie object to generate URI string from.
* @return Metadata for the normie as a string. Used for any call to URI..
*/
function getMainTraitsString(NormieLib.Normie memory normie) private view returns (string memory) {
return string(abi.encodePacked(
'{"Skin Type":"',
traitIDToTrait[normie.skinType].traitName,
'","Hair":"', traitIDToTrait[normie.hair].traitName,
'","Eyes":"', traitIDToTrait[normie.eyes].traitName,
'","Mouth":"', traitIDToTrait[normie.mouth].traitName,
'","Torso":"', traitIDToTrait[normie.torso].traitName,
'","Pants":"', traitIDToTrait[normie.pants].traitName,
'","Shoes":"', traitIDToTrait[normie.shoes].traitName
)
);
}
/*
* @dev Generates the string metadata for optional Normie traits.
* @param normie The normie object to generate URI string from.
* @return Metadata for the normie as a string. Used for any call to URI.
*/
function getOptionalTraitsString(NormieLib.Normie memory normie) private view returns (string memory) {
return string(abi.encodePacked(
'","Accessory One":"', traitIDToTrait[normie.accessoryOne].traitName,
'","Accessory Two":"', traitIDToTrait[normie.accessoryTwo].traitName,
'","Accessory Three":"', traitIDToTrait[normie.accessoryThree].traitName,
'"}'
)
);
}
/**
* @dev Generates the string metadata for a single trait NFT.
* @param trait The trait object to generate URI string from.
* @return Metadata for the asset as a string. Used for any call to URI.
*/
function getSingleTraitString(NormieLib.Trait memory trait) private pure returns (string memory) {
return string(abi.encodePacked(
'{"Trait Type":"',
trait.traitType,
'","Trait Name":"', trait.traitName,
'"}'
)
);
}
///////////////////////////// OWNER FUNCTIONS /////////////////////////////
//--------------------------
// Trait Rarity functions
//--------------------------
/**
* @dev Clears the trait rarity for a given trait (Ex. hair which is 0).
* @param traitIndex The index we want to clear.
*/
function clearTraitRarity(uint256 traitIndex) external onlyOwner {
delete traitRarity[traitIndex];
}
/**
* @dev Clears all trait rarities.
*/
function clearAllTraitRarities() external onlyOwner {
for (uint256 i = 0; i < traitRarity.length; i++){
delete traitRarity[i];
}
}
/**
* @dev Adds an array of trait rarity values to the traix index. Contains safety check to ensure the array sums to 10,000.
Also checks to make sure trait rarity is empty to begin with.
* @param traitIndex The trait index to add trait rarities to.
* @param newRarities Integer array of rarities that should sum to 10,000.
*/
function addTraitRarity(uint256 traitIndex, uint256[] memory newRarities) external onlyOwner {
require(traitRarity[traitIndex].length == 0, "Not empty trait");
require(newRarities[newRarities.length-1] == 10000, "Trait rarity does not end in 10,000. Reverting");
for (uint256 i = 0; i < newRarities.length; i++) {
traitRarity[traitIndex].push(newRarities[i]);
}
return;
}
//--------------------------
// Collection functions
//--------------------------
/**
* @dev Clears the traits for a given trait index in the current collection (Ex. hair which is 0).
* @param index The index to clear current collection traits from.
*/
function clearCurrentCollectionTrait(uint256 index) external onlyOwner {
delete currentCollectionTraits[index];
}
/**
* @dev Clears all traits for the current collection.
*/
function clearAllTraitsInCurrentCollection() external onlyOwner {
for (uint256 i = 0; i < 10; i++){
delete currentCollectionTraits[i];
}
}
/**
* Adds new trait to trait map. Good to use when adding new traits for giveaways or one offs.
* @param newTraits Array of traits to add to trait map.
*/
function addTraitToTraitMap(NormieLib.Trait[] memory newTraits) external onlyOwner {
uint32 currentTraitLocal = CURRENT_TRAIT;
for (uint256 i = 0; i < newTraits.length; i++){
NormieLib.Trait memory _trait = NormieLib.Trait(
newTraits[i].traitName,
newTraits[i].traitType,
newTraits[i].hash,
newTraits[i].pixelCount,
1000001 + currentTraitLocal
);
traitIDToTrait[1000001 + currentTraitLocal] = _trait;
currentTraitLocal = currentTraitLocal + 1;
}
CURRENT_TRAIT = currentTraitLocal;
}
/**
* @dev Function used to edit a trait in place in case we hashed incorrectly or something.
* @param traitID Trait ID of the trait we want to edit
* @param newTraitData Struct containing data that we want to overwrite the current trait with.
*/
function editTrait(uint256 traitID, NormieLib.Trait memory newTraitData) external onlyOwner {
NormieLib.Trait memory _trait = traitIDToTrait[traitID];
_trait.traitName = newTraitData.traitName;
_trait.traitType = newTraitData.traitType;
_trait.hash = newTraitData.hash;
_trait.pixelCount = newTraitData.pixelCount;
traitIDToTrait[traitID] = _trait;
}
/**
* @dev Emergency function to remove incorrect traits from existence. Checks to make sure ID provided is greater than 1,000,000.
* @param traitID The trait to remove from existence.
*/
function removeTraitFromTraitMap(uint256 traitID) external onlyOwner {
require(traitID >= 1000000, "Trait ID < 1,000,000");
traitIDToTrait[traitID] = emptyTrait;
}
/**
* @dev Adds traits to specific location. Good to use for reusing assets in another collection. (Ex. Reusing skinType assets).
* @param traitIndex The index to add these traits to.
* @param traitID Array of integers representing the traits to add to the given collectionNumber and traitIndex.
*/
function addTraitsToCurrentCollection(uint256 traitIndex, uint256[] memory traitID) external onlyOwner {
require(currentCollectionTraits[traitIndex].length + traitID.length <= traitRarity[traitIndex].length, "Trait array mismatch");
for (uint256 i = 0; i < traitID.length; i++){
currentCollectionTraits[traitIndex].push(traitID[i]);
}
}
/**
* @dev Sets the current color string. Allows us to add new colors in the future
* @param _colorString The new color string.
*/
function setColorString(string calldata _colorString) external onlyOwner {
colorString = _colorString;
}
/**
* @dev Used to add admin acccess for a contract
* @param _addressToAdd The address to give admin access to.
*/
function addAdminAccess(address _addressToAdd) external onlyOwner {
adminAccess[_addressToAdd] = true;
}
} | * @dev Function used to edit a trait in place in case we hashed incorrectly or something. @param traitID Trait ID of the trait we want to edit @param newTraitData Struct containing data that we want to overwrite the current trait with./ | function editTrait(uint256 traitID, NormieLib.Trait memory newTraitData) external onlyOwner {
NormieLib.Trait memory _trait = traitIDToTrait[traitID];
_trait.traitName = newTraitData.traitName;
_trait.traitType = newTraitData.traitType;
_trait.hash = newTraitData.hash;
_trait.pixelCount = newTraitData.pixelCount;
traitIDToTrait[traitID] = _trait;
}
| 12,603,911 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
5206,
4284,
1399,
358,
3874,
279,
13517,
316,
3166,
316,
648,
732,
14242,
25621,
578,
5943,
18,
632,
891,
13517,
734,
2197,
305,
1599,
434,
326,
13517,
732,
2545,
358,
3874,
632,
891,
394,
15525,
751,
7362,
4191,
501,
716,
732,
2545,
358,
6156,
326,
783,
13517,
598,
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,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3874,
15525,
12,
11890,
5034,
13517,
734,
16,
24773,
1385,
5664,
18,
15525,
3778,
394,
15525,
751,
13,
3903,
1338,
5541,
288,
203,
3639,
24773,
1385,
5664,
18,
15525,
3778,
389,
22513,
273,
13517,
734,
774,
15525,
63,
22513,
734,
15533,
203,
3639,
389,
22513,
18,
22513,
461,
273,
394,
15525,
751,
18,
22513,
461,
31,
203,
3639,
389,
22513,
18,
22513,
559,
273,
394,
15525,
751,
18,
22513,
559,
31,
203,
3639,
389,
22513,
18,
2816,
273,
394,
15525,
751,
18,
2816,
31,
203,
3639,
389,
22513,
18,
11743,
1380,
273,
394,
15525,
751,
18,
11743,
1380,
31,
203,
3639,
13517,
734,
774,
15525,
63,
22513,
734,
65,
273,
389,
22513,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x55B65931FCa5868009CbDEb6eeb3a8ccE182B56e/sources/Wallet.sol | Revokes a prior confirmation of the given operation Replaces an owner `_from` with another `_to`. (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today. | contract WalletAbi {
function revoke(bytes32 _operation) external;
function changeOwner(address _from, address _to) external;
function addOwner(address _owner) external;
function removeOwner(address _owner) external;
function changeRequirement(uint _newRequired) external;
function isOwner(address _addr) constant returns (bool);
function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool);
function setDailyLimit(uint _newLimit) external;
function execute(address _to, uint _value, bytes _data) external returns (bytes32 o_hash);
function confirm(bytes32 _h) returns (bool o_success);
}
| 3,949,748 | [
1,
4625,
348,
7953,
560,
30,
225,
14477,
601,
281,
279,
6432,
14296,
434,
326,
864,
1674,
868,
11350,
392,
3410,
1375,
67,
2080,
68,
598,
4042,
1375,
67,
869,
8338,
261,
266,
13,
4424,
326,
18872,
1800,
18,
4260,
4906,
434,
326,
25937,
358,
6932,
18,
3302,
1404,
10182,
326,
3844,
1818,
26515,
10074,
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,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
20126,
5895,
77,
288,
203,
225,
445,
18007,
12,
3890,
1578,
389,
7624,
13,
3903,
31,
203,
203,
225,
445,
2549,
5541,
12,
2867,
389,
2080,
16,
1758,
389,
869,
13,
3903,
31,
203,
203,
225,
445,
527,
5541,
12,
2867,
389,
8443,
13,
3903,
31,
203,
203,
225,
445,
1206,
5541,
12,
2867,
389,
8443,
13,
3903,
31,
203,
203,
225,
445,
2549,
18599,
12,
11890,
389,
2704,
3705,
13,
3903,
31,
203,
203,
225,
445,
353,
5541,
12,
2867,
389,
4793,
13,
5381,
1135,
261,
6430,
1769,
203,
203,
225,
445,
711,
3976,
11222,
12,
3890,
1578,
389,
7624,
16,
1758,
389,
8443,
13,
3903,
5381,
1135,
261,
6430,
1769,
203,
203,
225,
445,
444,
40,
12857,
3039,
12,
11890,
389,
2704,
3039,
13,
3903,
31,
203,
203,
225,
445,
1836,
12,
2867,
389,
869,
16,
2254,
389,
1132,
16,
1731,
389,
892,
13,
3903,
1135,
261,
3890,
1578,
320,
67,
2816,
1769,
203,
225,
445,
6932,
12,
3890,
1578,
389,
76,
13,
1135,
261,
6430,
320,
67,
4768,
1769,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xBB5A7481BEE7b1F058E006FC717379EE0B54d25d/sources/src/Jackpot.sol | * @dev Returns current game players./ | function getPlayedGamePlayers() public view returns (uint) {
return getPlayersInGame(game);
}
| 4,125,351 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
5206,
2860,
783,
7920,
18115,
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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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1689,
5544,
329,
12496,
1749,
3907,
1435,
1071,
1476,
1135,
261,
11890,
13,
288,
203,
3639,
327,
9774,
3907,
382,
12496,
12,
13957,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x8002Aa3A2065cdc24c72FE518a0aEd5c9f8FA9D9/sources/ShareTokenSaleData.sol | * @dev Get end time of `round`/ | function getTokenSaleEndTime(uint round) external view override returns(uint){
return _tokenSaleEndTimes[round];
}
| 4,138,305 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
5206,
968,
679,
813,
434,
1375,
2260,
68,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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63,
2260,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
pragma solidity ^0.4.21;
contract EIP20Interface {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public view returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract TestCoin is EIP20Interface {
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.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show.
string public symbol; //An identifier: eg SBX
function TestCoin(
) public {
balances[msg.sender] = 10*10**26; // Give the creator all initial tokens
totalSupply = 10*10**26; // Update total supply
name = "LHJT"; // Set the name for display purposes
decimals = 18; // Amount of decimals for display purposes
symbol = "LHJT"; // 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;
emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars
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;
}
emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
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;
emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
} | Set the name for display purposes
| name = "LHJT"; | 132,555 | [
1,
4625,
348,
7953,
560,
30,
225,
1000,
326,
508,
364,
2562,
13694,
203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
48,
44,
46,
56,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/4/0x477387b19bF53Ba3470bec91418A8360336a3e76/sources/IanCoin.sol | * Constrctor function Initializes contract with initial supply tokens to the creator of the contract/ | constructor() public {
name = "IanCoin";
symbol = "CWJ";
decimals = 0;
_totalSupply = 1000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
| 8,523,832 | [
1,
4625,
348,
7953,
560,
30,
380,
735,
701,
30206,
445,
10188,
3128,
6835,
598,
2172,
14467,
2430,
358,
326,
11784,
434,
326,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1435,
1071,
288,
203,
3639,
508,
273,
315,
45,
304,
27055,
14432,
203,
3639,
3273,
273,
315,
12844,
46,
14432,
203,
3639,
15105,
273,
374,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
15088,
31,
203,
203,
3639,
324,
26488,
63,
3576,
18,
15330,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
1234,
18,
15330,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 Owner {
address public owner;
//添加断路器
bool public stopped = false;
function Owner() internal {
owner = msg.sender;
}
modifier onlyOwner {
require (msg.sender == owner);
_;
}
function transferOwnership(address newOwner) external onlyOwner {
require (newOwner != 0x0);
require (newOwner != owner);
emit OwnerUpdate(owner, newOwner);
owner = newOwner;
}
function toggleContractActive() onlyOwner public {
//可以预置改变状态的条件,如基于投票人数
stopped = !stopped;
}
modifier stopInEmergency {
require(stopped == false);
_;
}
modifier onlyInEmergency {
require(stopped == true);
_;
}
event OwnerUpdate(address _prevOwner, address _newOwner);
}
contract Mortal is Owner {
//销毁合约
function close() external onlyOwner {
selfdestruct(owner);
}
}
/**
* @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;
}
}
contract Token is Owner, Mortal {
using SafeMath for uint256;
string public name; //代币名称
string public symbol; //代币符号
uint8 public decimals; //显示多少小数点
uint256 public totalSupply; //总供应量
//冻结的基金,解锁的数量根据时间动态计算出来
struct Fund{
uint amount; //总冻结数量,固定值
uint unlockStartTime; //从什么时候开始解锁
uint unlockInterval; //每次解锁的周期,单位 秒
uint unlockPercent; //每次解锁的百分比 50 为50%
bool isValue; // exist value
}
//所有的账户数据
mapping (address => uint) public balances;
//代理
mapping(address => mapping(address => uint)) approved;
//所有的账户冻结数据,时间,到期自动解冻,同时只支持一次冻结
mapping (address => Fund) public frozenAccount;
//事件日志
event Transfer(address indexed from, address indexed to, uint value);
event FrozenFunds(address indexed target, uint value, uint unlockStartTime, uint unlockIntervalUnit, uint unlockInterval, uint unlockPercent);
event Approval(address indexed accountOwner, address indexed spender, uint256 value);
/**
*
* Fix for the ERC20 short address attack
*
* http://vessenes.com/the-erc20-short-address-attack-explained/
*/
modifier onlyPayloadSize(uint256 size) {
require(msg.data.length == size + 4);
_;
}
//冻结固定时间
function freezeAccount(address target, uint value, uint unlockStartTime, uint unlockIntervalUnit, uint unlockInterval, uint unlockPercent) external onlyOwner freezeOutCheck(target, 0) {
require (value > 0);
require (frozenAccount[target].isValue == false);
require (balances[msg.sender] >= value);
require (unlockStartTime > now);
require (unlockInterval > 0);
require (unlockPercent > 0 && unlockPercent <= 100);
uint unlockIntervalSecond = toSecond(unlockIntervalUnit, unlockInterval);
frozenAccount[target] = Fund(value, unlockStartTime, unlockIntervalSecond, unlockPercent, true);
emit FrozenFunds(target, value, unlockStartTime, unlockIntervalUnit, unlockInterval, unlockPercent);
}
//转账并冻结
function transferAndFreeze(address target, uint256 value, uint unlockStartTime, uint unlockIntervalUnit, uint unlockInterval, uint unlockPercent) external onlyOwner freezeOutCheck(target, 0) {
require (value > 0);
require (frozenAccount[target].isValue == false);
require (unlockStartTime > now);
require (unlockInterval > 0);
require (unlockPercent > 0 && unlockPercent <= 100);
_transfer(msg.sender, target, value);
uint unlockIntervalSecond = toSecond(unlockIntervalUnit, unlockInterval);
frozenAccount[target] = Fund(value, unlockStartTime, unlockIntervalSecond, unlockPercent, true);
emit FrozenFunds(target, value, unlockStartTime, unlockIntervalUnit, unlockInterval, unlockPercent);
}
//转换单位时间到秒
function toSecond(uint unitType, uint value) internal pure returns (uint256 Seconds) {
uint _seconds;
if (unitType == 5){
_seconds = value.mul(1 years);
}else if(unitType == 4){
_seconds = value.mul(1 days);
}else if (unitType == 3){
_seconds = value.mul(1 hours);
}else if (unitType == 2){
_seconds = value.mul(1 minutes);
}else if (unitType == 1){
_seconds = value;
}else{
revert();
}
return _seconds;
}
modifier freezeOutCheck(address sender, uint value) {
require ( getAvailableBalance(sender) >= value);
_;
}
//计算可用余额 去除冻结部分
function getAvailableBalance(address sender) internal returns(uint balance) {
if (frozenAccount[sender].isValue) {
//未开始解锁
if (now < frozenAccount[sender].unlockStartTime){
return balances[sender] - frozenAccount[sender].amount;
}else{
//计算解锁了多少数量
uint unlockPercent = ((now - frozenAccount[sender].unlockStartTime ) / frozenAccount[sender].unlockInterval + 1) * frozenAccount[sender].unlockPercent;
if (unlockPercent > 100){
unlockPercent = 100;
}
//计算可用余额 = 总额 - 冻结总额
assert(frozenAccount[sender].amount <= balances[sender]);
uint available = balances[sender] - (100 - unlockPercent) * frozenAccount[sender].amount / 100;
if ( unlockPercent >= 100){
//release
frozenAccount[sender].isValue = false;
delete frozenAccount[sender];
}
return available;
}
}
return balances[sender];
}
function balanceOf(address sender) constant external returns (uint256 balance){
return balances[sender];
}
/* 代币转移的函数 */
function transfer(address to, uint256 value) external stopInEmergency onlyPayloadSize(2 * 32) {
_transfer(msg.sender, to, value);
}
function _transfer(address _from, address _to, uint _value) internal freezeOutCheck(_from, _value) {
require(_to != 0x0);
require(_from != _to);
require(_value > 0);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
}
//设置代理交易
//允许spender多次取出您的帐户,最高达value金额。value可以设置超过账户余额
function approve(address spender, uint value) external returns (bool success) {
approved[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
//返回spender仍然被允许从accountOwner提取的金额
function allowance(address accountOwner, address spender) constant external returns (uint remaining) {
return approved[accountOwner][spender];
}
//使用代理交易
//0值的传输必须被视为正常传输并触发传输事件
//代理交易不自动为对方补充gas
function transferFrom(address from, address to, uint256 value) external stopInEmergency freezeOutCheck(from, value) returns (bool success) {
require(value > 0);
require(value <= approved[from][msg.sender]);
require(value <= balances[from]);
approved[from][msg.sender] = approved[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
}
contract MigrationAgent {
function migrateFrom(address from, uint256 value) public;
}
contract UpgradeableToken is Owner, Token {
address public migrationAgent;
/**
* Somebody has upgraded some of his tokens.
*/
event Upgrade(address indexed from, address indexed to, uint256 value);
/**
* New upgrade agent available.
*/
event UpgradeAgentSet(address agent);
// Migrate tokens to the new token contract
function migrate() public {
require(migrationAgent != 0);
uint value = balances[msg.sender];
balances[msg.sender] = balances[msg.sender].sub(value);
totalSupply = totalSupply.sub(value);
MigrationAgent(migrationAgent).migrateFrom(msg.sender, value);
emit Upgrade(msg.sender, migrationAgent, value);
}
function () public payable {
require(migrationAgent != 0);
require(balances[msg.sender] > 0);
migrate();
msg.sender.transfer(msg.value);
}
function setMigrationAgent(address _agent) onlyOwner external {
migrationAgent = _agent;
emit UpgradeAgentSet(_agent);
}
}
contract MIToken is UpgradeableToken {
function MIToken() public {
name = "MI Token";
symbol = "MI";
decimals = 18;
owner = msg.sender;
uint initialSupply = 100000000;
totalSupply = initialSupply * 10 ** uint256(decimals);
require (totalSupply >= initialSupply);
balances[msg.sender] = totalSupply;
emit Transfer(0x0, msg.sender, totalSupply);
}
function mint(address _to, uint256 _amount) onlyOwner public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(address(0), _to, _amount);
return true;
}
} | 设置代理交易允许spender多次取出您的帐户,最高达value金额。value可以设置超过账户余额 | function approve(address spender, uint value) external returns (bool success) {
approved[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
| 896,743 | [
1,
4625,
348,
7953,
560,
30,
225,
169,
111,
127,
168,
126,
111,
165,
124,
101,
168,
243,
233,
165,
123,
102,
167,
251,
246,
166,
232,
228,
169,
111,
121,
87,
1302,
264,
166,
102,
253,
167,
110,
99,
166,
242,
249,
166,
234,
123,
167,
229,
106,
168,
253,
231,
166,
121,
243,
167,
235,
120,
176,
125,
239,
167,
255,
227,
170,
109,
251,
169,
127,
127,
1132,
170,
234,
244,
170,
100,
256,
164,
227,
229,
1132,
166,
242,
112,
165,
124,
103,
169,
111,
127,
168,
126,
111,
169,
119,
232,
169,
128,
234,
169,
117,
104,
167,
235,
120,
165,
126,
252,
170,
100,
256,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
460,
13,
3903,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
20412,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
65,
273,
460,
31,
203,
3639,
3626,
1716,
685,
1125,
12,
3576,
18,
15330,
16,
17571,
264,
16,
460,
1769,
203,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x6d1427F640406c5A46D5ced2FF5A1b2C89617690/sources/DEE.sol | 2% from total supply maxWallet
| maxWallet = 100 * 1e18; | 4,444,538 | [
1,
4625,
348,
7953,
560,
30,
225,
576,
9,
628,
2078,
14467,
943,
16936,
203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
943,
16936,
273,
2130,
380,
404,
73,
2643,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
// Contracts
import { TellerNFT } from "../nft/TellerNFT.sol";
import { RolesMods } from "../contexts2/access-control/roles/RolesMods.sol";
import { ADMIN, AUTHORIZED } from "../shared/roles.sol";
import "../nft/TellerNFTDictionary.sol";
// Libraries
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { NFTLib } from "./libraries/NFTLib.sol";
import { RolesLib } from "../contexts2/access-control/roles/RolesLib.sol";
import {
EnumerableSet
} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
contract NFTFacet is RolesMods {
/**
* @notice it gets the staked NFTs mapped to an owner's address
* @return staked_ the returned staked NFTs mapped to an owner's address
*/
function getStakedNFTs(address nftOwner)
public
view
returns (uint256[] memory staked_)
{
staked_ = NFTLib.stakedNFTs(nftOwner);
}
/**
* @notice it returns the NFTs mapped to a loan
* @param loanID the identifier of the respective loan to get the loan NFTs from
* @return loanNFTs the loan NFTs mapped to a loan ID
*/
function getLoanNFTs(uint256 loanID)
external
view
returns (uint256[] memory loanNFTs)
{
EnumerableSet.UintSet storage nfts = NFTLib.s().loanNFTs[loanID];
loanNFTs = new uint256[](EnumerableSet.length(nfts));
for (uint256 i; i < EnumerableSet.length(nfts); i++) {
loanNFTs[i] = EnumerableSet.at(nfts, i);
}
}
/**
* @notice Transfers multiple Teller NFTs to Diamond and applies user stake.
* @param nftIDs IDs of Teller NFTs to stake.
*/
function stakeNFTs(uint256[] calldata nftIDs) external {
for (uint256 i; i < nftIDs.length; i++) {
// Stake NFT and transfer into diamond
NFTLib.stake(nftIDs[i], msg.sender);
}
// Give the caller authorization to protocol
RolesLib.grantRole(AUTHORIZED, msg.sender);
}
/**
* @notice Sets the NFTDictionary address used to get information about an NFT and its tier.
* @param dictAddress Dictionary address to use.
*
* Requirements:
* - Sender must have `ADMIN` role
*/
function setNFTDictionary(address dictAddress)
external
authorized(ADMIN, msg.sender)
{
NFTLib.s().nftDictionary = TellerNFTDictionary(dictAddress);
}
}
| * @notice Transfers multiple Teller NFTs to Diamond and applies user stake. @param nftIDs IDs of Teller NFTs to stake./ Stake NFT and transfer into diamond | function stakeNFTs(uint256[] calldata nftIDs) external {
for (uint256 i; i < nftIDs.length; i++) {
NFTLib.stake(nftIDs[i], msg.sender);
}
}
| 13,011,482 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
20392,
2604,
18881,
3229,
399,
292,
749,
423,
4464,
87,
358,
12508,
301,
1434,
471,
10294,
729,
384,
911,
18,
632,
891,
290,
1222,
5103,
7115,
434,
399,
292,
749,
423,
4464,
87,
358,
384,
911,
18,
19,
934,
911,
423,
4464,
471,
7412,
1368,
4314,
301,
1434,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
384,
911,
50,
4464,
87,
12,
11890,
5034,
8526,
745,
892,
290,
1222,
5103,
13,
3903,
288,
203,
3639,
364,
261,
11890,
5034,
277,
31,
277,
411,
290,
1222,
5103,
18,
2469,
31,
277,
27245,
288,
203,
5411,
423,
4464,
5664,
18,
334,
911,
12,
82,
1222,
5103,
63,
77,
6487,
1234,
18,
15330,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x6B0B234fB2f380309D47A7E9391E29E9a179395a/sources/src/v0.8/tests/VerifiableLoadBase.sol | * @notice sets registrar, registry, and link token address. @param newRegistrar the new registrar address/ | function setConfig(AutomationRegistrar2_1 newRegistrar) external {
registrar = newRegistrar;
(address registryAddress, ) = registrar.getConfig();
registry = IKeeperRegistryMaster(payable(address(registryAddress)));
linkToken = registrar.LINK();
}
| 3,963,219 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
20392,
1678,
17450,
297,
16,
4023,
16,
471,
1692,
1147,
1758,
18,
632,
891,
394,
30855,
326,
394,
17450,
297,
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,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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
15517,
12,
28589,
30855,
22,
67,
21,
394,
30855,
13,
3903,
288,
203,
565,
17450,
297,
273,
394,
30855,
31,
203,
565,
261,
2867,
4023,
1887,
16,
262,
273,
17450,
297,
18,
588,
809,
5621,
203,
565,
4023,
273,
467,
17891,
4243,
7786,
12,
10239,
429,
12,
2867,
12,
9893,
1887,
3719,
1769,
203,
565,
1692,
1345,
273,
17450,
297,
18,
10554,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.4;
/// @notice Modern and gas-optimized ERC-20 + EIP-2612 implementation with COMP-style governance and pausing.
/// @author Modified from Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/erc20/ERC20.sol)
/// License-Identifier: AGPL-3.0-only
abstract contract KaliDAOtoken {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
event PauseFlipped(bool paused);
/*///////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
error NoArrayParity();
error Paused();
error SignatureExpired();
error NullAddress();
error InvalidNonce();
error NotDetermined();
error InvalidSignature();
error Uint32max();
error Uint96max();
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
uint8 public constant decimals = 18;
/*///////////////////////////////////////////////////////////////
ERC-20 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 INITIAL_CHAIN_ID;
bytes32 internal INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
/*///////////////////////////////////////////////////////////////
DAO STORAGE
//////////////////////////////////////////////////////////////*/
bool public paused;
bytes32 public constant DELEGATION_TYPEHASH =
keccak256('Delegation(address delegatee,uint256 nonce,uint256 deadline)');
mapping(address => address) internal _delegates;
mapping(address => mapping(uint256 => Checkpoint)) public checkpoints;
mapping(address => uint256) public numCheckpoints;
struct Checkpoint {
uint32 fromTimestamp;
uint96 votes;
}
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
function _init(
string memory name_,
string memory symbol_,
bool paused_,
address[] memory voters_,
uint256[] memory shares_
) internal virtual {
if (voters_.length != shares_.length) revert NoArrayParity();
name = name_;
symbol = symbol_;
paused = paused_;
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = _computeDomainSeparator();
// cannot realistically overflow on human timescales
unchecked {
for (uint256 i; i < voters_.length; i++) {
_mint(voters_[i], shares_[i]);
}
}
}
/*///////////////////////////////////////////////////////////////
ERC-20 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 amount) public payable virtual returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) public payable notPaused 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;
}
_moveDelegates(delegates(msg.sender), delegates(to), amount);
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public payable notPaused virtual returns (bool) {
if (allowance[from][msg.sender] != type(uint256).max)
allowance[from][msg.sender] -= amount;
balanceOf[from] -= amount;
// cannot overflow because the sum of all user
// balances can't exceed the max uint256 value
unchecked {
balanceOf[to] += amount;
}
_moveDelegates(delegates(from), delegates(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 payable virtual {
if (block.timestamp > deadline) revert SignatureExpired();
// cannot realistically overflow on human timescales
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);
if (recoveredAddress == address(0) || recoveredAddress != owner) revert InvalidSignature();
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)
)
);
}
/*///////////////////////////////////////////////////////////////
DAO LOGIC
//////////////////////////////////////////////////////////////*/
modifier notPaused() {
if (paused) revert Paused();
_;
}
function delegates(address delegator) public view virtual returns (address) {
address current = _delegates[delegator];
return current == address(0) ? delegator : current;
}
function getCurrentVotes(address account) public view virtual returns (uint256) {
// this is safe from underflow because decrement only occurs if `nCheckpoints` is positive
unchecked {
uint256 nCheckpoints = numCheckpoints[account];
return nCheckpoints != 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
}
function delegate(address delegatee) public payable virtual {
_delegate(msg.sender, delegatee);
}
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public payable virtual {
if (block.timestamp > deadline) revert SignatureExpired();
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, deadline));
bytes32 digest = keccak256(abi.encodePacked('\x19\x01', DOMAIN_SEPARATOR(), structHash));
address signatory = ecrecover(digest, v, r, s);
if (signatory == address(0)) revert NullAddress();
// cannot realistically overflow on human timescales
unchecked {
if (nonce != nonces[signatory]++) revert InvalidNonce();
}
_delegate(signatory, delegatee);
}
function getPriorVotes(address account, uint256 timestamp) public view virtual returns (uint96) {
if (block.timestamp <= timestamp) revert NotDetermined();
uint256 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) return 0;
// this is safe from underflow because decrement only occurs if `nCheckpoints` is positive
unchecked {
if (checkpoints[account][nCheckpoints - 1].fromTimestamp <= timestamp)
return checkpoints[account][nCheckpoints - 1].votes;
if (checkpoints[account][0].fromTimestamp > timestamp) return 0;
uint256 lower;
// this is safe from underflow because decrement only occurs if `nCheckpoints` is positive
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
// this is safe from underflow because `upper` ceiling is provided
uint256 center = upper - (upper - lower) / 2;
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromTimestamp == timestamp) {
return cp.votes;
} else if (cp.fromTimestamp < timestamp) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
}
function _delegate(address delegator, address delegatee) internal virtual {
address currentDelegate = delegates(delegator);
_delegates[delegator] = delegatee;
_moveDelegates(currentDelegate, delegatee, balanceOf[delegator]);
emit DelegateChanged(delegator, currentDelegate, delegatee);
}
function _moveDelegates(
address srcRep,
address dstRep,
uint256 amount
) internal virtual {
if (srcRep != dstRep && amount != 0)
if (srcRep != address(0)) {
uint256 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum != 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld - amount;
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint256 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum != 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld + amount;
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
function _writeCheckpoint(
address delegatee,
uint256 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
) internal virtual {
unchecked {
// this is safe from underflow because decrement only occurs if `nCheckpoints` is positive
if (nCheckpoints != 0 && checkpoints[delegatee][nCheckpoints - 1].fromTimestamp == block.timestamp) {
checkpoints[delegatee][nCheckpoints - 1].votes = _safeCastTo96(newVotes);
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(_safeCastTo32(block.timestamp), _safeCastTo96(newVotes));
// cannot realistically overflow on human timescales
numCheckpoints[delegatee] = nCheckpoints + 1;
}
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
/*///////////////////////////////////////////////////////////////
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;
}
_moveDelegates(address(0), delegates(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;
}
_moveDelegates(delegates(from), address(0), amount);
emit Transfer(from, address(0), amount);
}
function burn(uint256 amount) public payable virtual {
_burn(msg.sender, amount);
}
function burnFrom(address from, uint256 amount) public payable virtual {
if (allowance[from][msg.sender] != type(uint256).max)
allowance[from][msg.sender] -= amount;
_burn(from, amount);
}
/*///////////////////////////////////////////////////////////////
PAUSE LOGIC
//////////////////////////////////////////////////////////////*/
function _flipPause() internal virtual {
paused = !paused;
emit PauseFlipped(paused);
}
/*///////////////////////////////////////////////////////////////
SAFECAST LOGIC
//////////////////////////////////////////////////////////////*/
function _safeCastTo32(uint256 x) internal pure virtual returns (uint32) {
if (x > type(uint32).max) revert Uint32max();
return uint32(x);
}
function _safeCastTo96(uint256 x) internal pure virtual returns (uint96) {
if (x > type(uint96).max) revert Uint96max();
return uint96(x);
}
}
/// @notice Helper utility that enables calling multiple local methods in a single call.
/// @author Modified from Uniswap (https://github.com/Uniswap/v3-periphery/blob/main/contracts/base/Multicall.sol)
abstract contract Multicall {
function multicall(bytes[] calldata data) public payable virtual returns (bytes[] memory results) {
results = new bytes[](data.length);
// cannot realistically overflow on human timescales
unchecked {
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}
}
}
/// @notice Helper utility for NFT 'safe' transfers.
abstract contract NFThelper {
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external pure returns (bytes4 sig) {
sig = 0x150b7a02; // 'onERC721Received(address,address,uint256,bytes)'
}
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes calldata
) external pure returns (bytes4 sig) {
sig = 0xf23a6e61; // 'onERC1155Received(address,address,uint256,uint256,bytes)'
}
function onERC1155BatchReceived(
address,
address,
uint256[] calldata,
uint256[] calldata,
bytes calldata
) external pure returns (bytes4 sig) {
sig = 0xbc197c81; // 'onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)'
}
}
/// @notice Gas-optimized reentrancy protection.
/// @author Modified from OpenZeppelin
/// (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)
/// License-Identifier: MIT
abstract contract ReentrancyGuard {
error Reentrancy();
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private status = NOT_ENTERED;
modifier nonReentrant() {
if (status == ENTERED) revert Reentrancy();
status = ENTERED;
_;
status = NOT_ENTERED;
}
}
/// @notice Kali DAO membership extension interface.
interface IKaliDAOextension {
function setExtension(bytes calldata extensionData) external;
function callExtension(
address account,
uint256 amount,
bytes calldata extensionData
) external payable returns (bool mint, uint256 amountOut);
}
/// @notice Simple gas-optimized Kali DAO core module.
contract KaliDAO is KaliDAOtoken, Multicall, NFThelper, ReentrancyGuard {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event NewProposal(
address indexed proposer,
uint256 indexed proposal,
ProposalType indexed proposalType,
string description,
address[] accounts,
uint256[] amounts,
bytes[] payloads
);
event ProposalCancelled(address indexed proposer, uint256 indexed proposal);
event ProposalSponsored(address indexed sponsor, uint256 indexed proposal);
event VoteCast(address indexed voter, uint256 indexed proposal, bool indexed approve);
event ProposalProcessed(uint256 indexed proposal, bool indexed didProposalPass);
/*///////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
error Initialized();
error PeriodBounds();
error QuorumMax();
error SupermajorityBounds();
error InitCallFail();
error TypeBounds();
error NotProposer();
error Sponsored();
error NotMember();
error NotCurrentProposal();
error AlreadyVoted();
error NotVoteable();
error VotingNotEnded();
error PrevNotProcessed();
error NotExtension();
/*///////////////////////////////////////////////////////////////
DAO STORAGE
//////////////////////////////////////////////////////////////*/
string public docs;
uint256 private currentSponsoredProposal;
uint256 public proposalCount;
uint32 public votingPeriod;
uint32 public gracePeriod;
uint32 public quorum; // 1-100
uint32 public supermajority; // 1-100
bytes32 public constant VOTE_HASH =
keccak256('SignVote(address signer,uint256 proposal,bool approve)');
mapping(address => bool) public extensions;
mapping(uint256 => Proposal) public proposals;
mapping(uint256 => ProposalState) public proposalStates;
mapping(ProposalType => VoteType) public proposalVoteTypes;
mapping(uint256 => mapping(address => bool)) public voted;
mapping(address => uint256) public lastYesVote;
enum ProposalType {
MINT, // add membership
BURN, // revoke membership
CALL, // call contracts
VPERIOD, // set `votingPeriod`
GPERIOD, // set `gracePeriod`
QUORUM, // set `quorum`
SUPERMAJORITY, // set `supermajority`
TYPE, // set `VoteType` to `ProposalType`
PAUSE, // flip membership transferability
EXTENSION, // flip `extensions` whitelisting
ESCAPE, // delete pending proposal in case of revert
DOCS // amend org docs
}
enum VoteType {
SIMPLE_MAJORITY,
SIMPLE_MAJORITY_QUORUM_REQUIRED,
SUPERMAJORITY,
SUPERMAJORITY_QUORUM_REQUIRED
}
struct Proposal {
ProposalType proposalType;
string description;
address[] accounts; // member(s) being added/kicked; account(s) receiving payload
uint256[] amounts; // value(s) to be minted/burned/spent; gov setting [0]
bytes[] payloads; // data for CALL proposals
uint256 prevProposal;
uint96 yesVotes;
uint96 noVotes;
uint32 creationTime;
address proposer;
}
struct ProposalState {
bool passed;
bool processed;
}
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
function init(
string memory name_,
string memory symbol_,
string memory docs_,
bool paused_,
address[] memory extensions_,
bytes[] memory extensionsData_,
address[] calldata voters_,
uint256[] calldata shares_,
uint32[16] memory govSettings_
) public payable nonReentrant virtual {
if (extensions_.length != extensionsData_.length) revert NoArrayParity();
if (votingPeriod != 0) revert Initialized();
if (govSettings_[0] == 0 || govSettings_[0] > 365 days) revert PeriodBounds();
if (govSettings_[1] > 365 days) revert PeriodBounds();
if (govSettings_[2] > 100) revert QuorumMax();
if (govSettings_[3] <= 51 || govSettings_[3] > 100) revert SupermajorityBounds();
KaliDAOtoken._init(name_, symbol_, paused_, voters_, shares_);
if (extensions_.length != 0) {
// cannot realistically overflow on human timescales
unchecked {
for (uint256 i; i < extensions_.length; i++) {
extensions[extensions_[i]] = true;
if (extensionsData_[i].length > 3) {
(bool success, ) = extensions_[i].call(extensionsData_[i]);
if (!success) revert InitCallFail();
}
}
}
}
docs = docs_;
votingPeriod = govSettings_[0];
gracePeriod = govSettings_[1];
quorum = govSettings_[2];
supermajority = govSettings_[3];
// set initial vote types
proposalVoteTypes[ProposalType.MINT] = VoteType(govSettings_[4]);
proposalVoteTypes[ProposalType.BURN] = VoteType(govSettings_[5]);
proposalVoteTypes[ProposalType.CALL] = VoteType(govSettings_[6]);
proposalVoteTypes[ProposalType.VPERIOD] = VoteType(govSettings_[7]);
proposalVoteTypes[ProposalType.GPERIOD] = VoteType(govSettings_[8]);
proposalVoteTypes[ProposalType.QUORUM] = VoteType(govSettings_[9]);
proposalVoteTypes[ProposalType.SUPERMAJORITY] = VoteType(govSettings_[10]);
proposalVoteTypes[ProposalType.TYPE] = VoteType(govSettings_[11]);
proposalVoteTypes[ProposalType.PAUSE] = VoteType(govSettings_[12]);
proposalVoteTypes[ProposalType.EXTENSION] = VoteType(govSettings_[13]);
proposalVoteTypes[ProposalType.ESCAPE] = VoteType(govSettings_[14]);
proposalVoteTypes[ProposalType.DOCS] = VoteType(govSettings_[15]);
}
/*///////////////////////////////////////////////////////////////
PROPOSAL LOGIC
//////////////////////////////////////////////////////////////*/
function getProposalArrays(uint256 proposal) public view virtual returns (
address[] memory accounts,
uint256[] memory amounts,
bytes[] memory payloads
) {
Proposal storage prop = proposals[proposal];
(accounts, amounts, payloads) = (prop.accounts, prop.amounts, prop.payloads);
}
function propose(
ProposalType proposalType,
string calldata description,
address[] calldata accounts,
uint256[] calldata amounts,
bytes[] calldata payloads
) public payable nonReentrant virtual returns (uint256 proposal) {
if (accounts.length != amounts.length || amounts.length != payloads.length) revert NoArrayParity();
if (proposalType == ProposalType.VPERIOD) if (amounts[0] == 0 || amounts[0] > 365 days) revert PeriodBounds();
if (proposalType == ProposalType.GPERIOD) if (amounts[0] > 365 days) revert PeriodBounds();
if (proposalType == ProposalType.QUORUM) if (amounts[0] > 100) revert QuorumMax();
if (proposalType == ProposalType.SUPERMAJORITY) if (amounts[0] <= 51 || amounts[0] > 100) revert SupermajorityBounds();
if (proposalType == ProposalType.TYPE) if (amounts[0] > 11 || amounts[1] > 3 || amounts.length != 2) revert TypeBounds();
bool selfSponsor;
// if member or extension is making proposal, include sponsorship
if (balanceOf[msg.sender] != 0 || extensions[msg.sender]) selfSponsor = true;
// cannot realistically overflow on human timescales
unchecked {
proposalCount++;
}
proposal = proposalCount;
proposals[proposal] = Proposal({
proposalType: proposalType,
description: description,
accounts: accounts,
amounts: amounts,
payloads: payloads,
prevProposal: selfSponsor ? currentSponsoredProposal : 0,
yesVotes: 0,
noVotes: 0,
creationTime: selfSponsor ? _safeCastTo32(block.timestamp) : 0,
proposer: msg.sender
});
if (selfSponsor) currentSponsoredProposal = proposal;
emit NewProposal(msg.sender, proposal, proposalType, description, accounts, amounts, payloads);
}
function cancelProposal(uint256 proposal) public payable nonReentrant virtual {
Proposal storage prop = proposals[proposal];
if (msg.sender != prop.proposer) revert NotProposer();
if (prop.creationTime != 0) revert Sponsored();
delete proposals[proposal];
emit ProposalCancelled(msg.sender, proposal);
}
function sponsorProposal(uint256 proposal) public payable nonReentrant virtual {
Proposal storage prop = proposals[proposal];
if (balanceOf[msg.sender] == 0) revert NotMember();
if (prop.proposer == address(0)) revert NotCurrentProposal();
if (prop.creationTime != 0) revert Sponsored();
prop.prevProposal = currentSponsoredProposal;
currentSponsoredProposal = proposal;
prop.creationTime = _safeCastTo32(block.timestamp);
emit ProposalSponsored(msg.sender, proposal);
}
function vote(uint256 proposal, bool approve) public payable nonReentrant virtual {
_vote(msg.sender, proposal, approve);
}
function voteBySig(
address signer,
uint256 proposal,
bool approve,
uint8 v,
bytes32 r,
bytes32 s
) public payable nonReentrant virtual {
bytes32 digest =
keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
VOTE_HASH,
signer,
proposal,
approve
)
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
if (recoveredAddress == address(0) || recoveredAddress != signer) revert InvalidSignature();
_vote(signer, proposal, approve);
}
function _vote(
address signer,
uint256 proposal,
bool approve
) internal virtual {
Proposal storage prop = proposals[proposal];
if (voted[proposal][signer]) revert AlreadyVoted();
// this is safe from overflow because `votingPeriod` is capped so it will not combine
// with unix time to exceed the max uint256 value
unchecked {
if (block.timestamp > prop.creationTime + votingPeriod) revert NotVoteable();
}
uint96 weight = getPriorVotes(signer, prop.creationTime);
// this is safe from overflow because `yesVotes` and `noVotes` are capped by `totalSupply`
// which is checked for overflow in `KaliDAOtoken` contract
unchecked {
if (approve) {
prop.yesVotes += weight;
lastYesVote[signer] = proposal;
} else {
prop.noVotes += weight;
}
}
voted[proposal][signer] = true;
emit VoteCast(signer, proposal, approve);
}
function processProposal(uint256 proposal) public payable nonReentrant virtual returns (
bool didProposalPass, bytes[] memory results
) {
Proposal storage prop = proposals[proposal];
VoteType voteType = proposalVoteTypes[prop.proposalType];
if (prop.creationTime == 0) revert NotCurrentProposal();
// this is safe from overflow because `votingPeriod` and `gracePeriod` are capped so they will not combine
// with unix time to exceed the max uint256 value
unchecked {
if (block.timestamp <= prop.creationTime + votingPeriod + gracePeriod) revert VotingNotEnded();
}
// skip previous proposal processing requirement in case of escape hatch
if (prop.proposalType != ProposalType.ESCAPE)
if (proposals[prop.prevProposal].creationTime != 0) revert PrevNotProcessed();
didProposalPass = _countVotes(voteType, prop.yesVotes, prop.noVotes);
if (didProposalPass) {
// cannot realistically overflow on human timescales
unchecked {
if (prop.proposalType == ProposalType.MINT)
for (uint256 i; i < prop.accounts.length; i++) {
_mint(prop.accounts[i], prop.amounts[i]);
}
if (prop.proposalType == ProposalType.BURN)
for (uint256 i; i < prop.accounts.length; i++) {
_burn(prop.accounts[i], prop.amounts[i]);
}
if (prop.proposalType == ProposalType.CALL)
for (uint256 i; i < prop.accounts.length; i++) {
results = new bytes[](prop.accounts.length);
(, bytes memory result) = prop.accounts[i].call{value: prop.amounts[i]}
(prop.payloads[i]);
results[i] = result;
}
// governance settings
if (prop.proposalType == ProposalType.VPERIOD)
if (prop.amounts[0] != 0) votingPeriod = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.GPERIOD)
if (prop.amounts[0] != 0) gracePeriod = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.QUORUM)
if (prop.amounts[0] != 0) quorum = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.SUPERMAJORITY)
if (prop.amounts[0] != 0) supermajority = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.TYPE)
proposalVoteTypes[ProposalType(prop.amounts[0])] = VoteType(prop.amounts[1]);
if (prop.proposalType == ProposalType.PAUSE)
_flipPause();
if (prop.proposalType == ProposalType.EXTENSION)
for (uint256 i; i < prop.accounts.length; i++) {
if (prop.amounts[i] != 0)
extensions[prop.accounts[i]] = !extensions[prop.accounts[i]];
if (prop.payloads[i].length > 3) IKaliDAOextension(prop.accounts[i])
.setExtension(prop.payloads[i]);
}
if (prop.proposalType == ProposalType.ESCAPE)
delete proposals[prop.amounts[0]];
if (prop.proposalType == ProposalType.DOCS)
docs = prop.description;
proposalStates[proposal].passed = true;
}
}
delete proposals[proposal];
proposalStates[proposal].processed = true;
emit ProposalProcessed(proposal, didProposalPass);
}
function _countVotes(
VoteType voteType,
uint256 yesVotes,
uint256 noVotes
) internal view virtual returns (bool didProposalPass) {
// fail proposal if no participation
if (yesVotes == 0 && noVotes == 0) return false;
// rule out any failed quorums
if (voteType == VoteType.SIMPLE_MAJORITY_QUORUM_REQUIRED || voteType == VoteType.SUPERMAJORITY_QUORUM_REQUIRED) {
uint256 minVotes = (totalSupply * quorum) / 100;
// this is safe from overflow because `yesVotes` and `noVotes`
// supply are checked in `KaliDAOtoken` contract
unchecked {
uint256 votes = yesVotes + noVotes;
if (votes < minVotes) return false;
}
}
// simple majority check
if (voteType == VoteType.SIMPLE_MAJORITY || voteType == VoteType.SIMPLE_MAJORITY_QUORUM_REQUIRED) {
if (yesVotes > noVotes) return true;
// supermajority check
} else {
// example: 7 yes, 2 no, supermajority = 66
// ((7+2) * 66) / 100 = 5.94; 7 yes will pass
uint256 minYes = ((yesVotes + noVotes) * supermajority) / 100;
if (yesVotes >= minYes) return true;
}
}
/*///////////////////////////////////////////////////////////////
EXTENSIONS
//////////////////////////////////////////////////////////////*/
receive() external payable virtual {}
modifier onlyExtension {
if (!extensions[msg.sender]) revert NotExtension();
_;
}
function callExtension(
address extension,
uint256 amount,
bytes calldata extensionData
) public payable nonReentrant virtual returns (bool mint, uint256 amountOut) {
if (!extensions[extension]) revert NotExtension();
(mint, amountOut) = IKaliDAOextension(extension).callExtension{value: msg.value}
(msg.sender, amount, extensionData);
if (mint) {
if (amountOut != 0) _mint(msg.sender, amountOut);
} else {
if (amountOut != 0) _burn(msg.sender, amount);
}
}
function mintShares(address to, uint256 amount) public payable onlyExtension virtual {
_mint(to, amount);
}
function burnShares(address from, uint256 amount) public payable onlyExtension virtual {
_burn(from, amount);
}
} | @notice Simple gas-optimized Kali DAO core module. | contract KaliDAO is KaliDAOtoken, Multicall, NFThelper, ReentrancyGuard {
EVENTS
event NewProposal(
address indexed proposer,
uint256 indexed proposal,
ProposalType indexed proposalType,
string description,
address[] accounts,
uint256[] amounts,
bytes[] payloads
);
event ProposalCancelled(address indexed proposer, uint256 indexed proposal);
event ProposalSponsored(address indexed sponsor, uint256 indexed proposal);
event VoteCast(address indexed voter, uint256 indexed proposal, bool indexed approve);
event ProposalProcessed(uint256 indexed proposal, bool indexed didProposalPass);
ERRORS
error Initialized();
error PeriodBounds();
error QuorumMax();
error SupermajorityBounds();
error InitCallFail();
error TypeBounds();
error NotProposer();
error Sponsored();
error NotMember();
error NotCurrentProposal();
error AlreadyVoted();
error NotVoteable();
error VotingNotEnded();
error PrevNotProcessed();
error NotExtension();
DAO STORAGE
string public docs;
uint256 private currentSponsoredProposal;
uint256 public proposalCount;
uint32 public votingPeriod;
uint32 public gracePeriod;
bytes32 public constant VOTE_HASH =
keccak256('SignVote(address signer,uint256 proposal,bool approve)');
mapping(address => bool) public extensions;
mapping(uint256 => Proposal) public proposals;
mapping(uint256 => ProposalState) public proposalStates;
mapping(ProposalType => VoteType) public proposalVoteTypes;
mapping(uint256 => mapping(address => bool)) public voted;
mapping(address => uint256) public lastYesVote;
enum ProposalType {
}
enum VoteType {
SIMPLE_MAJORITY,
SIMPLE_MAJORITY_QUORUM_REQUIRED,
SUPERMAJORITY,
SUPERMAJORITY_QUORUM_REQUIRED
}
struct Proposal {
ProposalType proposalType;
string description;
uint256 prevProposal;
uint96 yesVotes;
uint96 noVotes;
uint32 creationTime;
address proposer;
}
struct ProposalState {
bool passed;
bool processed;
}
CONSTRUCTOR
function init(
string memory name_,
string memory symbol_,
string memory docs_,
bool paused_,
address[] memory extensions_,
bytes[] memory extensionsData_,
address[] calldata voters_,
uint256[] calldata shares_,
uint32[16] memory govSettings_
) public payable nonReentrant virtual {
if (extensions_.length != extensionsData_.length) revert NoArrayParity();
if (votingPeriod != 0) revert Initialized();
if (govSettings_[0] == 0 || govSettings_[0] > 365 days) revert PeriodBounds();
if (govSettings_[1] > 365 days) revert PeriodBounds();
if (govSettings_[2] > 100) revert QuorumMax();
if (govSettings_[3] <= 51 || govSettings_[3] > 100) revert SupermajorityBounds();
KaliDAOtoken._init(name_, symbol_, paused_, voters_, shares_);
if (extensions_.length != 0) {
unchecked {
for (uint256 i; i < extensions_.length; i++) {
extensions[extensions_[i]] = true;
if (extensionsData_[i].length > 3) {
(bool success, ) = extensions_[i].call(extensionsData_[i]);
if (!success) revert InitCallFail();
}
}
}
}
docs = docs_;
votingPeriod = govSettings_[0];
gracePeriod = govSettings_[1];
quorum = govSettings_[2];
supermajority = govSettings_[3];
proposalVoteTypes[ProposalType.BURN] = VoteType(govSettings_[5]);
proposalVoteTypes[ProposalType.CALL] = VoteType(govSettings_[6]);
proposalVoteTypes[ProposalType.VPERIOD] = VoteType(govSettings_[7]);
proposalVoteTypes[ProposalType.GPERIOD] = VoteType(govSettings_[8]);
proposalVoteTypes[ProposalType.QUORUM] = VoteType(govSettings_[9]);
proposalVoteTypes[ProposalType.SUPERMAJORITY] = VoteType(govSettings_[10]);
proposalVoteTypes[ProposalType.TYPE] = VoteType(govSettings_[11]);
proposalVoteTypes[ProposalType.PAUSE] = VoteType(govSettings_[12]);
proposalVoteTypes[ProposalType.EXTENSION] = VoteType(govSettings_[13]);
proposalVoteTypes[ProposalType.ESCAPE] = VoteType(govSettings_[14]);
proposalVoteTypes[ProposalType.DOCS] = VoteType(govSettings_[15]);
}
PROPOSAL LOGIC
function init(
string memory name_,
string memory symbol_,
string memory docs_,
bool paused_,
address[] memory extensions_,
bytes[] memory extensionsData_,
address[] calldata voters_,
uint256[] calldata shares_,
uint32[16] memory govSettings_
) public payable nonReentrant virtual {
if (extensions_.length != extensionsData_.length) revert NoArrayParity();
if (votingPeriod != 0) revert Initialized();
if (govSettings_[0] == 0 || govSettings_[0] > 365 days) revert PeriodBounds();
if (govSettings_[1] > 365 days) revert PeriodBounds();
if (govSettings_[2] > 100) revert QuorumMax();
if (govSettings_[3] <= 51 || govSettings_[3] > 100) revert SupermajorityBounds();
KaliDAOtoken._init(name_, symbol_, paused_, voters_, shares_);
if (extensions_.length != 0) {
unchecked {
for (uint256 i; i < extensions_.length; i++) {
extensions[extensions_[i]] = true;
if (extensionsData_[i].length > 3) {
(bool success, ) = extensions_[i].call(extensionsData_[i]);
if (!success) revert InitCallFail();
}
}
}
}
docs = docs_;
votingPeriod = govSettings_[0];
gracePeriod = govSettings_[1];
quorum = govSettings_[2];
supermajority = govSettings_[3];
proposalVoteTypes[ProposalType.BURN] = VoteType(govSettings_[5]);
proposalVoteTypes[ProposalType.CALL] = VoteType(govSettings_[6]);
proposalVoteTypes[ProposalType.VPERIOD] = VoteType(govSettings_[7]);
proposalVoteTypes[ProposalType.GPERIOD] = VoteType(govSettings_[8]);
proposalVoteTypes[ProposalType.QUORUM] = VoteType(govSettings_[9]);
proposalVoteTypes[ProposalType.SUPERMAJORITY] = VoteType(govSettings_[10]);
proposalVoteTypes[ProposalType.TYPE] = VoteType(govSettings_[11]);
proposalVoteTypes[ProposalType.PAUSE] = VoteType(govSettings_[12]);
proposalVoteTypes[ProposalType.EXTENSION] = VoteType(govSettings_[13]);
proposalVoteTypes[ProposalType.ESCAPE] = VoteType(govSettings_[14]);
proposalVoteTypes[ProposalType.DOCS] = VoteType(govSettings_[15]);
}
PROPOSAL LOGIC
function init(
string memory name_,
string memory symbol_,
string memory docs_,
bool paused_,
address[] memory extensions_,
bytes[] memory extensionsData_,
address[] calldata voters_,
uint256[] calldata shares_,
uint32[16] memory govSettings_
) public payable nonReentrant virtual {
if (extensions_.length != extensionsData_.length) revert NoArrayParity();
if (votingPeriod != 0) revert Initialized();
if (govSettings_[0] == 0 || govSettings_[0] > 365 days) revert PeriodBounds();
if (govSettings_[1] > 365 days) revert PeriodBounds();
if (govSettings_[2] > 100) revert QuorumMax();
if (govSettings_[3] <= 51 || govSettings_[3] > 100) revert SupermajorityBounds();
KaliDAOtoken._init(name_, symbol_, paused_, voters_, shares_);
if (extensions_.length != 0) {
unchecked {
for (uint256 i; i < extensions_.length; i++) {
extensions[extensions_[i]] = true;
if (extensionsData_[i].length > 3) {
(bool success, ) = extensions_[i].call(extensionsData_[i]);
if (!success) revert InitCallFail();
}
}
}
}
docs = docs_;
votingPeriod = govSettings_[0];
gracePeriod = govSettings_[1];
quorum = govSettings_[2];
supermajority = govSettings_[3];
proposalVoteTypes[ProposalType.BURN] = VoteType(govSettings_[5]);
proposalVoteTypes[ProposalType.CALL] = VoteType(govSettings_[6]);
proposalVoteTypes[ProposalType.VPERIOD] = VoteType(govSettings_[7]);
proposalVoteTypes[ProposalType.GPERIOD] = VoteType(govSettings_[8]);
proposalVoteTypes[ProposalType.QUORUM] = VoteType(govSettings_[9]);
proposalVoteTypes[ProposalType.SUPERMAJORITY] = VoteType(govSettings_[10]);
proposalVoteTypes[ProposalType.TYPE] = VoteType(govSettings_[11]);
proposalVoteTypes[ProposalType.PAUSE] = VoteType(govSettings_[12]);
proposalVoteTypes[ProposalType.EXTENSION] = VoteType(govSettings_[13]);
proposalVoteTypes[ProposalType.ESCAPE] = VoteType(govSettings_[14]);
proposalVoteTypes[ProposalType.DOCS] = VoteType(govSettings_[15]);
}
PROPOSAL LOGIC
function init(
string memory name_,
string memory symbol_,
string memory docs_,
bool paused_,
address[] memory extensions_,
bytes[] memory extensionsData_,
address[] calldata voters_,
uint256[] calldata shares_,
uint32[16] memory govSettings_
) public payable nonReentrant virtual {
if (extensions_.length != extensionsData_.length) revert NoArrayParity();
if (votingPeriod != 0) revert Initialized();
if (govSettings_[0] == 0 || govSettings_[0] > 365 days) revert PeriodBounds();
if (govSettings_[1] > 365 days) revert PeriodBounds();
if (govSettings_[2] > 100) revert QuorumMax();
if (govSettings_[3] <= 51 || govSettings_[3] > 100) revert SupermajorityBounds();
KaliDAOtoken._init(name_, symbol_, paused_, voters_, shares_);
if (extensions_.length != 0) {
unchecked {
for (uint256 i; i < extensions_.length; i++) {
extensions[extensions_[i]] = true;
if (extensionsData_[i].length > 3) {
(bool success, ) = extensions_[i].call(extensionsData_[i]);
if (!success) revert InitCallFail();
}
}
}
}
docs = docs_;
votingPeriod = govSettings_[0];
gracePeriod = govSettings_[1];
quorum = govSettings_[2];
supermajority = govSettings_[3];
proposalVoteTypes[ProposalType.BURN] = VoteType(govSettings_[5]);
proposalVoteTypes[ProposalType.CALL] = VoteType(govSettings_[6]);
proposalVoteTypes[ProposalType.VPERIOD] = VoteType(govSettings_[7]);
proposalVoteTypes[ProposalType.GPERIOD] = VoteType(govSettings_[8]);
proposalVoteTypes[ProposalType.QUORUM] = VoteType(govSettings_[9]);
proposalVoteTypes[ProposalType.SUPERMAJORITY] = VoteType(govSettings_[10]);
proposalVoteTypes[ProposalType.TYPE] = VoteType(govSettings_[11]);
proposalVoteTypes[ProposalType.PAUSE] = VoteType(govSettings_[12]);
proposalVoteTypes[ProposalType.EXTENSION] = VoteType(govSettings_[13]);
proposalVoteTypes[ProposalType.ESCAPE] = VoteType(govSettings_[14]);
proposalVoteTypes[ProposalType.DOCS] = VoteType(govSettings_[15]);
}
PROPOSAL LOGIC
function init(
string memory name_,
string memory symbol_,
string memory docs_,
bool paused_,
address[] memory extensions_,
bytes[] memory extensionsData_,
address[] calldata voters_,
uint256[] calldata shares_,
uint32[16] memory govSettings_
) public payable nonReentrant virtual {
if (extensions_.length != extensionsData_.length) revert NoArrayParity();
if (votingPeriod != 0) revert Initialized();
if (govSettings_[0] == 0 || govSettings_[0] > 365 days) revert PeriodBounds();
if (govSettings_[1] > 365 days) revert PeriodBounds();
if (govSettings_[2] > 100) revert QuorumMax();
if (govSettings_[3] <= 51 || govSettings_[3] > 100) revert SupermajorityBounds();
KaliDAOtoken._init(name_, symbol_, paused_, voters_, shares_);
if (extensions_.length != 0) {
unchecked {
for (uint256 i; i < extensions_.length; i++) {
extensions[extensions_[i]] = true;
if (extensionsData_[i].length > 3) {
(bool success, ) = extensions_[i].call(extensionsData_[i]);
if (!success) revert InitCallFail();
}
}
}
}
docs = docs_;
votingPeriod = govSettings_[0];
gracePeriod = govSettings_[1];
quorum = govSettings_[2];
supermajority = govSettings_[3];
proposalVoteTypes[ProposalType.BURN] = VoteType(govSettings_[5]);
proposalVoteTypes[ProposalType.CALL] = VoteType(govSettings_[6]);
proposalVoteTypes[ProposalType.VPERIOD] = VoteType(govSettings_[7]);
proposalVoteTypes[ProposalType.GPERIOD] = VoteType(govSettings_[8]);
proposalVoteTypes[ProposalType.QUORUM] = VoteType(govSettings_[9]);
proposalVoteTypes[ProposalType.SUPERMAJORITY] = VoteType(govSettings_[10]);
proposalVoteTypes[ProposalType.TYPE] = VoteType(govSettings_[11]);
proposalVoteTypes[ProposalType.PAUSE] = VoteType(govSettings_[12]);
proposalVoteTypes[ProposalType.EXTENSION] = VoteType(govSettings_[13]);
proposalVoteTypes[ProposalType.ESCAPE] = VoteType(govSettings_[14]);
proposalVoteTypes[ProposalType.DOCS] = VoteType(govSettings_[15]);
}
PROPOSAL LOGIC
proposalVoteTypes[ProposalType.MINT] = VoteType(govSettings_[4]);
function getProposalArrays(uint256 proposal) public view virtual returns (
address[] memory accounts,
uint256[] memory amounts,
bytes[] memory payloads
) {
Proposal storage prop = proposals[proposal];
(accounts, amounts, payloads) = (prop.accounts, prop.amounts, prop.payloads);
}
function propose(
ProposalType proposalType,
string calldata description,
address[] calldata accounts,
uint256[] calldata amounts,
bytes[] calldata payloads
) public payable nonReentrant virtual returns (uint256 proposal) {
if (accounts.length != amounts.length || amounts.length != payloads.length) revert NoArrayParity();
if (proposalType == ProposalType.VPERIOD) if (amounts[0] == 0 || amounts[0] > 365 days) revert PeriodBounds();
if (proposalType == ProposalType.GPERIOD) if (amounts[0] > 365 days) revert PeriodBounds();
if (proposalType == ProposalType.QUORUM) if (amounts[0] > 100) revert QuorumMax();
if (proposalType == ProposalType.SUPERMAJORITY) if (amounts[0] <= 51 || amounts[0] > 100) revert SupermajorityBounds();
if (proposalType == ProposalType.TYPE) if (amounts[0] > 11 || amounts[1] > 3 || amounts.length != 2) revert TypeBounds();
bool selfSponsor;
if (balanceOf[msg.sender] != 0 || extensions[msg.sender]) selfSponsor = true;
unchecked {
proposalCount++;
}
proposal = proposalCount;
proposals[proposal] = Proposal({
proposalType: proposalType,
description: description,
accounts: accounts,
amounts: amounts,
payloads: payloads,
prevProposal: selfSponsor ? currentSponsoredProposal : 0,
yesVotes: 0,
noVotes: 0,
creationTime: selfSponsor ? _safeCastTo32(block.timestamp) : 0,
proposer: msg.sender
});
if (selfSponsor) currentSponsoredProposal = proposal;
emit NewProposal(msg.sender, proposal, proposalType, description, accounts, amounts, payloads);
}
function propose(
ProposalType proposalType,
string calldata description,
address[] calldata accounts,
uint256[] calldata amounts,
bytes[] calldata payloads
) public payable nonReentrant virtual returns (uint256 proposal) {
if (accounts.length != amounts.length || amounts.length != payloads.length) revert NoArrayParity();
if (proposalType == ProposalType.VPERIOD) if (amounts[0] == 0 || amounts[0] > 365 days) revert PeriodBounds();
if (proposalType == ProposalType.GPERIOD) if (amounts[0] > 365 days) revert PeriodBounds();
if (proposalType == ProposalType.QUORUM) if (amounts[0] > 100) revert QuorumMax();
if (proposalType == ProposalType.SUPERMAJORITY) if (amounts[0] <= 51 || amounts[0] > 100) revert SupermajorityBounds();
if (proposalType == ProposalType.TYPE) if (amounts[0] > 11 || amounts[1] > 3 || amounts.length != 2) revert TypeBounds();
bool selfSponsor;
if (balanceOf[msg.sender] != 0 || extensions[msg.sender]) selfSponsor = true;
unchecked {
proposalCount++;
}
proposal = proposalCount;
proposals[proposal] = Proposal({
proposalType: proposalType,
description: description,
accounts: accounts,
amounts: amounts,
payloads: payloads,
prevProposal: selfSponsor ? currentSponsoredProposal : 0,
yesVotes: 0,
noVotes: 0,
creationTime: selfSponsor ? _safeCastTo32(block.timestamp) : 0,
proposer: msg.sender
});
if (selfSponsor) currentSponsoredProposal = proposal;
emit NewProposal(msg.sender, proposal, proposalType, description, accounts, amounts, payloads);
}
function propose(
ProposalType proposalType,
string calldata description,
address[] calldata accounts,
uint256[] calldata amounts,
bytes[] calldata payloads
) public payable nonReentrant virtual returns (uint256 proposal) {
if (accounts.length != amounts.length || amounts.length != payloads.length) revert NoArrayParity();
if (proposalType == ProposalType.VPERIOD) if (amounts[0] == 0 || amounts[0] > 365 days) revert PeriodBounds();
if (proposalType == ProposalType.GPERIOD) if (amounts[0] > 365 days) revert PeriodBounds();
if (proposalType == ProposalType.QUORUM) if (amounts[0] > 100) revert QuorumMax();
if (proposalType == ProposalType.SUPERMAJORITY) if (amounts[0] <= 51 || amounts[0] > 100) revert SupermajorityBounds();
if (proposalType == ProposalType.TYPE) if (amounts[0] > 11 || amounts[1] > 3 || amounts.length != 2) revert TypeBounds();
bool selfSponsor;
if (balanceOf[msg.sender] != 0 || extensions[msg.sender]) selfSponsor = true;
unchecked {
proposalCount++;
}
proposal = proposalCount;
proposals[proposal] = Proposal({
proposalType: proposalType,
description: description,
accounts: accounts,
amounts: amounts,
payloads: payloads,
prevProposal: selfSponsor ? currentSponsoredProposal : 0,
yesVotes: 0,
noVotes: 0,
creationTime: selfSponsor ? _safeCastTo32(block.timestamp) : 0,
proposer: msg.sender
});
if (selfSponsor) currentSponsoredProposal = proposal;
emit NewProposal(msg.sender, proposal, proposalType, description, accounts, amounts, payloads);
}
function cancelProposal(uint256 proposal) public payable nonReentrant virtual {
Proposal storage prop = proposals[proposal];
if (msg.sender != prop.proposer) revert NotProposer();
if (prop.creationTime != 0) revert Sponsored();
delete proposals[proposal];
emit ProposalCancelled(msg.sender, proposal);
}
function sponsorProposal(uint256 proposal) public payable nonReentrant virtual {
Proposal storage prop = proposals[proposal];
if (balanceOf[msg.sender] == 0) revert NotMember();
if (prop.proposer == address(0)) revert NotCurrentProposal();
if (prop.creationTime != 0) revert Sponsored();
prop.prevProposal = currentSponsoredProposal;
currentSponsoredProposal = proposal;
prop.creationTime = _safeCastTo32(block.timestamp);
emit ProposalSponsored(msg.sender, proposal);
}
function vote(uint256 proposal, bool approve) public payable nonReentrant virtual {
_vote(msg.sender, proposal, approve);
}
function voteBySig(
address signer,
uint256 proposal,
bool approve,
uint8 v,
bytes32 r,
bytes32 s
) public payable nonReentrant virtual {
bytes32 digest =
keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
VOTE_HASH,
signer,
proposal,
approve
)
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
if (recoveredAddress == address(0) || recoveredAddress != signer) revert InvalidSignature();
_vote(signer, proposal, approve);
}
function _vote(
address signer,
uint256 proposal,
bool approve
) internal virtual {
Proposal storage prop = proposals[proposal];
if (voted[proposal][signer]) revert AlreadyVoted();
unchecked {
if (block.timestamp > prop.creationTime + votingPeriod) revert NotVoteable();
}
uint96 weight = getPriorVotes(signer, prop.creationTime);
unchecked {
if (approve) {
prop.yesVotes += weight;
lastYesVote[signer] = proposal;
prop.noVotes += weight;
}
}
voted[proposal][signer] = true;
emit VoteCast(signer, proposal, approve);
}
function _vote(
address signer,
uint256 proposal,
bool approve
) internal virtual {
Proposal storage prop = proposals[proposal];
if (voted[proposal][signer]) revert AlreadyVoted();
unchecked {
if (block.timestamp > prop.creationTime + votingPeriod) revert NotVoteable();
}
uint96 weight = getPriorVotes(signer, prop.creationTime);
unchecked {
if (approve) {
prop.yesVotes += weight;
lastYesVote[signer] = proposal;
prop.noVotes += weight;
}
}
voted[proposal][signer] = true;
emit VoteCast(signer, proposal, approve);
}
function _vote(
address signer,
uint256 proposal,
bool approve
) internal virtual {
Proposal storage prop = proposals[proposal];
if (voted[proposal][signer]) revert AlreadyVoted();
unchecked {
if (block.timestamp > prop.creationTime + votingPeriod) revert NotVoteable();
}
uint96 weight = getPriorVotes(signer, prop.creationTime);
unchecked {
if (approve) {
prop.yesVotes += weight;
lastYesVote[signer] = proposal;
prop.noVotes += weight;
}
}
voted[proposal][signer] = true;
emit VoteCast(signer, proposal, approve);
}
function _vote(
address signer,
uint256 proposal,
bool approve
) internal virtual {
Proposal storage prop = proposals[proposal];
if (voted[proposal][signer]) revert AlreadyVoted();
unchecked {
if (block.timestamp > prop.creationTime + votingPeriod) revert NotVoteable();
}
uint96 weight = getPriorVotes(signer, prop.creationTime);
unchecked {
if (approve) {
prop.yesVotes += weight;
lastYesVote[signer] = proposal;
prop.noVotes += weight;
}
}
voted[proposal][signer] = true;
emit VoteCast(signer, proposal, approve);
}
} else {
function processProposal(uint256 proposal) public payable nonReentrant virtual returns (
bool didProposalPass, bytes[] memory results
) {
Proposal storage prop = proposals[proposal];
VoteType voteType = proposalVoteTypes[prop.proposalType];
if (prop.creationTime == 0) revert NotCurrentProposal();
unchecked {
if (block.timestamp <= prop.creationTime + votingPeriod + gracePeriod) revert VotingNotEnded();
}
if (proposals[prop.prevProposal].creationTime != 0) revert PrevNotProcessed();
didProposalPass = _countVotes(voteType, prop.yesVotes, prop.noVotes);
if (didProposalPass) {
unchecked {
if (prop.proposalType == ProposalType.MINT)
for (uint256 i; i < prop.accounts.length; i++) {
_mint(prop.accounts[i], prop.amounts[i]);
}
if (prop.proposalType == ProposalType.BURN)
for (uint256 i; i < prop.accounts.length; i++) {
_burn(prop.accounts[i], prop.amounts[i]);
}
if (prop.proposalType == ProposalType.CALL)
for (uint256 i; i < prop.accounts.length; i++) {
results = new bytes[](prop.accounts.length);
(prop.payloads[i]);
results[i] = result;
}
if (prop.amounts[0] != 0) votingPeriod = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.GPERIOD)
if (prop.amounts[0] != 0) gracePeriod = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.QUORUM)
if (prop.amounts[0] != 0) quorum = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.SUPERMAJORITY)
if (prop.amounts[0] != 0) supermajority = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.TYPE)
proposalVoteTypes[ProposalType(prop.amounts[0])] = VoteType(prop.amounts[1]);
if (prop.proposalType == ProposalType.PAUSE)
_flipPause();
if (prop.proposalType == ProposalType.EXTENSION)
for (uint256 i; i < prop.accounts.length; i++) {
if (prop.amounts[i] != 0)
extensions[prop.accounts[i]] = !extensions[prop.accounts[i]];
if (prop.payloads[i].length > 3) IKaliDAOextension(prop.accounts[i])
.setExtension(prop.payloads[i]);
}
if (prop.proposalType == ProposalType.ESCAPE)
delete proposals[prop.amounts[0]];
if (prop.proposalType == ProposalType.DOCS)
docs = prop.description;
proposalStates[proposal].passed = true;
}
}
delete proposals[proposal];
proposalStates[proposal].processed = true;
emit ProposalProcessed(proposal, didProposalPass);
}
function processProposal(uint256 proposal) public payable nonReentrant virtual returns (
bool didProposalPass, bytes[] memory results
) {
Proposal storage prop = proposals[proposal];
VoteType voteType = proposalVoteTypes[prop.proposalType];
if (prop.creationTime == 0) revert NotCurrentProposal();
unchecked {
if (block.timestamp <= prop.creationTime + votingPeriod + gracePeriod) revert VotingNotEnded();
}
if (proposals[prop.prevProposal].creationTime != 0) revert PrevNotProcessed();
didProposalPass = _countVotes(voteType, prop.yesVotes, prop.noVotes);
if (didProposalPass) {
unchecked {
if (prop.proposalType == ProposalType.MINT)
for (uint256 i; i < prop.accounts.length; i++) {
_mint(prop.accounts[i], prop.amounts[i]);
}
if (prop.proposalType == ProposalType.BURN)
for (uint256 i; i < prop.accounts.length; i++) {
_burn(prop.accounts[i], prop.amounts[i]);
}
if (prop.proposalType == ProposalType.CALL)
for (uint256 i; i < prop.accounts.length; i++) {
results = new bytes[](prop.accounts.length);
(prop.payloads[i]);
results[i] = result;
}
if (prop.amounts[0] != 0) votingPeriod = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.GPERIOD)
if (prop.amounts[0] != 0) gracePeriod = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.QUORUM)
if (prop.amounts[0] != 0) quorum = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.SUPERMAJORITY)
if (prop.amounts[0] != 0) supermajority = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.TYPE)
proposalVoteTypes[ProposalType(prop.amounts[0])] = VoteType(prop.amounts[1]);
if (prop.proposalType == ProposalType.PAUSE)
_flipPause();
if (prop.proposalType == ProposalType.EXTENSION)
for (uint256 i; i < prop.accounts.length; i++) {
if (prop.amounts[i] != 0)
extensions[prop.accounts[i]] = !extensions[prop.accounts[i]];
if (prop.payloads[i].length > 3) IKaliDAOextension(prop.accounts[i])
.setExtension(prop.payloads[i]);
}
if (prop.proposalType == ProposalType.ESCAPE)
delete proposals[prop.amounts[0]];
if (prop.proposalType == ProposalType.DOCS)
docs = prop.description;
proposalStates[proposal].passed = true;
}
}
delete proposals[proposal];
proposalStates[proposal].processed = true;
emit ProposalProcessed(proposal, didProposalPass);
}
if (prop.proposalType != ProposalType.ESCAPE)
function processProposal(uint256 proposal) public payable nonReentrant virtual returns (
bool didProposalPass, bytes[] memory results
) {
Proposal storage prop = proposals[proposal];
VoteType voteType = proposalVoteTypes[prop.proposalType];
if (prop.creationTime == 0) revert NotCurrentProposal();
unchecked {
if (block.timestamp <= prop.creationTime + votingPeriod + gracePeriod) revert VotingNotEnded();
}
if (proposals[prop.prevProposal].creationTime != 0) revert PrevNotProcessed();
didProposalPass = _countVotes(voteType, prop.yesVotes, prop.noVotes);
if (didProposalPass) {
unchecked {
if (prop.proposalType == ProposalType.MINT)
for (uint256 i; i < prop.accounts.length; i++) {
_mint(prop.accounts[i], prop.amounts[i]);
}
if (prop.proposalType == ProposalType.BURN)
for (uint256 i; i < prop.accounts.length; i++) {
_burn(prop.accounts[i], prop.amounts[i]);
}
if (prop.proposalType == ProposalType.CALL)
for (uint256 i; i < prop.accounts.length; i++) {
results = new bytes[](prop.accounts.length);
(prop.payloads[i]);
results[i] = result;
}
if (prop.amounts[0] != 0) votingPeriod = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.GPERIOD)
if (prop.amounts[0] != 0) gracePeriod = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.QUORUM)
if (prop.amounts[0] != 0) quorum = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.SUPERMAJORITY)
if (prop.amounts[0] != 0) supermajority = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.TYPE)
proposalVoteTypes[ProposalType(prop.amounts[0])] = VoteType(prop.amounts[1]);
if (prop.proposalType == ProposalType.PAUSE)
_flipPause();
if (prop.proposalType == ProposalType.EXTENSION)
for (uint256 i; i < prop.accounts.length; i++) {
if (prop.amounts[i] != 0)
extensions[prop.accounts[i]] = !extensions[prop.accounts[i]];
if (prop.payloads[i].length > 3) IKaliDAOextension(prop.accounts[i])
.setExtension(prop.payloads[i]);
}
if (prop.proposalType == ProposalType.ESCAPE)
delete proposals[prop.amounts[0]];
if (prop.proposalType == ProposalType.DOCS)
docs = prop.description;
proposalStates[proposal].passed = true;
}
}
delete proposals[proposal];
proposalStates[proposal].processed = true;
emit ProposalProcessed(proposal, didProposalPass);
}
function processProposal(uint256 proposal) public payable nonReentrant virtual returns (
bool didProposalPass, bytes[] memory results
) {
Proposal storage prop = proposals[proposal];
VoteType voteType = proposalVoteTypes[prop.proposalType];
if (prop.creationTime == 0) revert NotCurrentProposal();
unchecked {
if (block.timestamp <= prop.creationTime + votingPeriod + gracePeriod) revert VotingNotEnded();
}
if (proposals[prop.prevProposal].creationTime != 0) revert PrevNotProcessed();
didProposalPass = _countVotes(voteType, prop.yesVotes, prop.noVotes);
if (didProposalPass) {
unchecked {
if (prop.proposalType == ProposalType.MINT)
for (uint256 i; i < prop.accounts.length; i++) {
_mint(prop.accounts[i], prop.amounts[i]);
}
if (prop.proposalType == ProposalType.BURN)
for (uint256 i; i < prop.accounts.length; i++) {
_burn(prop.accounts[i], prop.amounts[i]);
}
if (prop.proposalType == ProposalType.CALL)
for (uint256 i; i < prop.accounts.length; i++) {
results = new bytes[](prop.accounts.length);
(prop.payloads[i]);
results[i] = result;
}
if (prop.amounts[0] != 0) votingPeriod = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.GPERIOD)
if (prop.amounts[0] != 0) gracePeriod = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.QUORUM)
if (prop.amounts[0] != 0) quorum = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.SUPERMAJORITY)
if (prop.amounts[0] != 0) supermajority = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.TYPE)
proposalVoteTypes[ProposalType(prop.amounts[0])] = VoteType(prop.amounts[1]);
if (prop.proposalType == ProposalType.PAUSE)
_flipPause();
if (prop.proposalType == ProposalType.EXTENSION)
for (uint256 i; i < prop.accounts.length; i++) {
if (prop.amounts[i] != 0)
extensions[prop.accounts[i]] = !extensions[prop.accounts[i]];
if (prop.payloads[i].length > 3) IKaliDAOextension(prop.accounts[i])
.setExtension(prop.payloads[i]);
}
if (prop.proposalType == ProposalType.ESCAPE)
delete proposals[prop.amounts[0]];
if (prop.proposalType == ProposalType.DOCS)
docs = prop.description;
proposalStates[proposal].passed = true;
}
}
delete proposals[proposal];
proposalStates[proposal].processed = true;
emit ProposalProcessed(proposal, didProposalPass);
}
function processProposal(uint256 proposal) public payable nonReentrant virtual returns (
bool didProposalPass, bytes[] memory results
) {
Proposal storage prop = proposals[proposal];
VoteType voteType = proposalVoteTypes[prop.proposalType];
if (prop.creationTime == 0) revert NotCurrentProposal();
unchecked {
if (block.timestamp <= prop.creationTime + votingPeriod + gracePeriod) revert VotingNotEnded();
}
if (proposals[prop.prevProposal].creationTime != 0) revert PrevNotProcessed();
didProposalPass = _countVotes(voteType, prop.yesVotes, prop.noVotes);
if (didProposalPass) {
unchecked {
if (prop.proposalType == ProposalType.MINT)
for (uint256 i; i < prop.accounts.length; i++) {
_mint(prop.accounts[i], prop.amounts[i]);
}
if (prop.proposalType == ProposalType.BURN)
for (uint256 i; i < prop.accounts.length; i++) {
_burn(prop.accounts[i], prop.amounts[i]);
}
if (prop.proposalType == ProposalType.CALL)
for (uint256 i; i < prop.accounts.length; i++) {
results = new bytes[](prop.accounts.length);
(prop.payloads[i]);
results[i] = result;
}
if (prop.amounts[0] != 0) votingPeriod = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.GPERIOD)
if (prop.amounts[0] != 0) gracePeriod = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.QUORUM)
if (prop.amounts[0] != 0) quorum = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.SUPERMAJORITY)
if (prop.amounts[0] != 0) supermajority = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.TYPE)
proposalVoteTypes[ProposalType(prop.amounts[0])] = VoteType(prop.amounts[1]);
if (prop.proposalType == ProposalType.PAUSE)
_flipPause();
if (prop.proposalType == ProposalType.EXTENSION)
for (uint256 i; i < prop.accounts.length; i++) {
if (prop.amounts[i] != 0)
extensions[prop.accounts[i]] = !extensions[prop.accounts[i]];
if (prop.payloads[i].length > 3) IKaliDAOextension(prop.accounts[i])
.setExtension(prop.payloads[i]);
}
if (prop.proposalType == ProposalType.ESCAPE)
delete proposals[prop.amounts[0]];
if (prop.proposalType == ProposalType.DOCS)
docs = prop.description;
proposalStates[proposal].passed = true;
}
}
delete proposals[proposal];
proposalStates[proposal].processed = true;
emit ProposalProcessed(proposal, didProposalPass);
}
function processProposal(uint256 proposal) public payable nonReentrant virtual returns (
bool didProposalPass, bytes[] memory results
) {
Proposal storage prop = proposals[proposal];
VoteType voteType = proposalVoteTypes[prop.proposalType];
if (prop.creationTime == 0) revert NotCurrentProposal();
unchecked {
if (block.timestamp <= prop.creationTime + votingPeriod + gracePeriod) revert VotingNotEnded();
}
if (proposals[prop.prevProposal].creationTime != 0) revert PrevNotProcessed();
didProposalPass = _countVotes(voteType, prop.yesVotes, prop.noVotes);
if (didProposalPass) {
unchecked {
if (prop.proposalType == ProposalType.MINT)
for (uint256 i; i < prop.accounts.length; i++) {
_mint(prop.accounts[i], prop.amounts[i]);
}
if (prop.proposalType == ProposalType.BURN)
for (uint256 i; i < prop.accounts.length; i++) {
_burn(prop.accounts[i], prop.amounts[i]);
}
if (prop.proposalType == ProposalType.CALL)
for (uint256 i; i < prop.accounts.length; i++) {
results = new bytes[](prop.accounts.length);
(prop.payloads[i]);
results[i] = result;
}
if (prop.amounts[0] != 0) votingPeriod = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.GPERIOD)
if (prop.amounts[0] != 0) gracePeriod = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.QUORUM)
if (prop.amounts[0] != 0) quorum = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.SUPERMAJORITY)
if (prop.amounts[0] != 0) supermajority = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.TYPE)
proposalVoteTypes[ProposalType(prop.amounts[0])] = VoteType(prop.amounts[1]);
if (prop.proposalType == ProposalType.PAUSE)
_flipPause();
if (prop.proposalType == ProposalType.EXTENSION)
for (uint256 i; i < prop.accounts.length; i++) {
if (prop.amounts[i] != 0)
extensions[prop.accounts[i]] = !extensions[prop.accounts[i]];
if (prop.payloads[i].length > 3) IKaliDAOextension(prop.accounts[i])
.setExtension(prop.payloads[i]);
}
if (prop.proposalType == ProposalType.ESCAPE)
delete proposals[prop.amounts[0]];
if (prop.proposalType == ProposalType.DOCS)
docs = prop.description;
proposalStates[proposal].passed = true;
}
}
delete proposals[proposal];
proposalStates[proposal].processed = true;
emit ProposalProcessed(proposal, didProposalPass);
}
function processProposal(uint256 proposal) public payable nonReentrant virtual returns (
bool didProposalPass, bytes[] memory results
) {
Proposal storage prop = proposals[proposal];
VoteType voteType = proposalVoteTypes[prop.proposalType];
if (prop.creationTime == 0) revert NotCurrentProposal();
unchecked {
if (block.timestamp <= prop.creationTime + votingPeriod + gracePeriod) revert VotingNotEnded();
}
if (proposals[prop.prevProposal].creationTime != 0) revert PrevNotProcessed();
didProposalPass = _countVotes(voteType, prop.yesVotes, prop.noVotes);
if (didProposalPass) {
unchecked {
if (prop.proposalType == ProposalType.MINT)
for (uint256 i; i < prop.accounts.length; i++) {
_mint(prop.accounts[i], prop.amounts[i]);
}
if (prop.proposalType == ProposalType.BURN)
for (uint256 i; i < prop.accounts.length; i++) {
_burn(prop.accounts[i], prop.amounts[i]);
}
if (prop.proposalType == ProposalType.CALL)
for (uint256 i; i < prop.accounts.length; i++) {
results = new bytes[](prop.accounts.length);
(prop.payloads[i]);
results[i] = result;
}
if (prop.amounts[0] != 0) votingPeriod = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.GPERIOD)
if (prop.amounts[0] != 0) gracePeriod = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.QUORUM)
if (prop.amounts[0] != 0) quorum = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.SUPERMAJORITY)
if (prop.amounts[0] != 0) supermajority = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.TYPE)
proposalVoteTypes[ProposalType(prop.amounts[0])] = VoteType(prop.amounts[1]);
if (prop.proposalType == ProposalType.PAUSE)
_flipPause();
if (prop.proposalType == ProposalType.EXTENSION)
for (uint256 i; i < prop.accounts.length; i++) {
if (prop.amounts[i] != 0)
extensions[prop.accounts[i]] = !extensions[prop.accounts[i]];
if (prop.payloads[i].length > 3) IKaliDAOextension(prop.accounts[i])
.setExtension(prop.payloads[i]);
}
if (prop.proposalType == ProposalType.ESCAPE)
delete proposals[prop.amounts[0]];
if (prop.proposalType == ProposalType.DOCS)
docs = prop.description;
proposalStates[proposal].passed = true;
}
}
delete proposals[proposal];
proposalStates[proposal].processed = true;
emit ProposalProcessed(proposal, didProposalPass);
}
(, bytes memory result) = prop.accounts[i].call{value: prop.amounts[i]}
if (prop.proposalType == ProposalType.VPERIOD)
function processProposal(uint256 proposal) public payable nonReentrant virtual returns (
bool didProposalPass, bytes[] memory results
) {
Proposal storage prop = proposals[proposal];
VoteType voteType = proposalVoteTypes[prop.proposalType];
if (prop.creationTime == 0) revert NotCurrentProposal();
unchecked {
if (block.timestamp <= prop.creationTime + votingPeriod + gracePeriod) revert VotingNotEnded();
}
if (proposals[prop.prevProposal].creationTime != 0) revert PrevNotProcessed();
didProposalPass = _countVotes(voteType, prop.yesVotes, prop.noVotes);
if (didProposalPass) {
unchecked {
if (prop.proposalType == ProposalType.MINT)
for (uint256 i; i < prop.accounts.length; i++) {
_mint(prop.accounts[i], prop.amounts[i]);
}
if (prop.proposalType == ProposalType.BURN)
for (uint256 i; i < prop.accounts.length; i++) {
_burn(prop.accounts[i], prop.amounts[i]);
}
if (prop.proposalType == ProposalType.CALL)
for (uint256 i; i < prop.accounts.length; i++) {
results = new bytes[](prop.accounts.length);
(prop.payloads[i]);
results[i] = result;
}
if (prop.amounts[0] != 0) votingPeriod = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.GPERIOD)
if (prop.amounts[0] != 0) gracePeriod = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.QUORUM)
if (prop.amounts[0] != 0) quorum = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.SUPERMAJORITY)
if (prop.amounts[0] != 0) supermajority = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.TYPE)
proposalVoteTypes[ProposalType(prop.amounts[0])] = VoteType(prop.amounts[1]);
if (prop.proposalType == ProposalType.PAUSE)
_flipPause();
if (prop.proposalType == ProposalType.EXTENSION)
for (uint256 i; i < prop.accounts.length; i++) {
if (prop.amounts[i] != 0)
extensions[prop.accounts[i]] = !extensions[prop.accounts[i]];
if (prop.payloads[i].length > 3) IKaliDAOextension(prop.accounts[i])
.setExtension(prop.payloads[i]);
}
if (prop.proposalType == ProposalType.ESCAPE)
delete proposals[prop.amounts[0]];
if (prop.proposalType == ProposalType.DOCS)
docs = prop.description;
proposalStates[proposal].passed = true;
}
}
delete proposals[proposal];
proposalStates[proposal].processed = true;
emit ProposalProcessed(proposal, didProposalPass);
}
function _countVotes(
VoteType voteType,
uint256 yesVotes,
uint256 noVotes
) internal view virtual returns (bool didProposalPass) {
if (yesVotes == 0 && noVotes == 0) return false;
if (voteType == VoteType.SIMPLE_MAJORITY_QUORUM_REQUIRED || voteType == VoteType.SUPERMAJORITY_QUORUM_REQUIRED) {
uint256 minVotes = (totalSupply * quorum) / 100;
unchecked {
uint256 votes = yesVotes + noVotes;
if (votes < minVotes) return false;
}
}
if (voteType == VoteType.SIMPLE_MAJORITY || voteType == VoteType.SIMPLE_MAJORITY_QUORUM_REQUIRED) {
if (yesVotes > noVotes) return true;
uint256 minYes = ((yesVotes + noVotes) * supermajority) / 100;
if (yesVotes >= minYes) return true;
}
}
EXTENSIONS
function _countVotes(
VoteType voteType,
uint256 yesVotes,
uint256 noVotes
) internal view virtual returns (bool didProposalPass) {
if (yesVotes == 0 && noVotes == 0) return false;
if (voteType == VoteType.SIMPLE_MAJORITY_QUORUM_REQUIRED || voteType == VoteType.SUPERMAJORITY_QUORUM_REQUIRED) {
uint256 minVotes = (totalSupply * quorum) / 100;
unchecked {
uint256 votes = yesVotes + noVotes;
if (votes < minVotes) return false;
}
}
if (voteType == VoteType.SIMPLE_MAJORITY || voteType == VoteType.SIMPLE_MAJORITY_QUORUM_REQUIRED) {
if (yesVotes > noVotes) return true;
uint256 minYes = ((yesVotes + noVotes) * supermajority) / 100;
if (yesVotes >= minYes) return true;
}
}
EXTENSIONS
function _countVotes(
VoteType voteType,
uint256 yesVotes,
uint256 noVotes
) internal view virtual returns (bool didProposalPass) {
if (yesVotes == 0 && noVotes == 0) return false;
if (voteType == VoteType.SIMPLE_MAJORITY_QUORUM_REQUIRED || voteType == VoteType.SUPERMAJORITY_QUORUM_REQUIRED) {
uint256 minVotes = (totalSupply * quorum) / 100;
unchecked {
uint256 votes = yesVotes + noVotes;
if (votes < minVotes) return false;
}
}
if (voteType == VoteType.SIMPLE_MAJORITY || voteType == VoteType.SIMPLE_MAJORITY_QUORUM_REQUIRED) {
if (yesVotes > noVotes) return true;
uint256 minYes = ((yesVotes + noVotes) * supermajority) / 100;
if (yesVotes >= minYes) return true;
}
}
EXTENSIONS
function _countVotes(
VoteType voteType,
uint256 yesVotes,
uint256 noVotes
) internal view virtual returns (bool didProposalPass) {
if (yesVotes == 0 && noVotes == 0) return false;
if (voteType == VoteType.SIMPLE_MAJORITY_QUORUM_REQUIRED || voteType == VoteType.SUPERMAJORITY_QUORUM_REQUIRED) {
uint256 minVotes = (totalSupply * quorum) / 100;
unchecked {
uint256 votes = yesVotes + noVotes;
if (votes < minVotes) return false;
}
}
if (voteType == VoteType.SIMPLE_MAJORITY || voteType == VoteType.SIMPLE_MAJORITY_QUORUM_REQUIRED) {
if (yesVotes > noVotes) return true;
uint256 minYes = ((yesVotes + noVotes) * supermajority) / 100;
if (yesVotes >= minYes) return true;
}
}
EXTENSIONS
} else {
receive() external payable virtual {}
modifier onlyExtension {
if (!extensions[msg.sender]) revert NotExtension();
_;
}
function callExtension(
address extension,
uint256 amount,
bytes calldata extensionData
) public payable nonReentrant virtual returns (bool mint, uint256 amountOut) {
if (!extensions[extension]) revert NotExtension();
(msg.sender, amount, extensionData);
if (mint) {
if (amountOut != 0) _mint(msg.sender, amountOut);
if (amountOut != 0) _burn(msg.sender, amount);
}
}
(mint, amountOut) = IKaliDAOextension(extension).callExtension{value: msg.value}
function callExtension(
address extension,
uint256 amount,
bytes calldata extensionData
) public payable nonReentrant virtual returns (bool mint, uint256 amountOut) {
if (!extensions[extension]) revert NotExtension();
(msg.sender, amount, extensionData);
if (mint) {
if (amountOut != 0) _mint(msg.sender, amountOut);
if (amountOut != 0) _burn(msg.sender, amount);
}
}
} else {
function mintShares(address to, uint256 amount) public payable onlyExtension virtual {
_mint(to, amount);
}
function burnShares(address from, uint256 amount) public payable onlyExtension virtual {
_burn(from, amount);
}
} | 1,604,412 | [
1,
4625,
348,
7953,
560,
30,
225,
632,
20392,
4477,
16189,
17,
16689,
1235,
1475,
18083,
463,
20463,
2922,
1605,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1475,
18083,
18485,
353,
1475,
18083,
18485,
2316,
16,
7778,
335,
454,
16,
423,
42,
1315,
1602,
16,
868,
8230,
12514,
16709,
288,
203,
18701,
9964,
55,
203,
203,
565,
871,
1166,
14592,
12,
203,
3639,
1758,
8808,
450,
5607,
16,
7010,
3639,
2254,
5034,
8808,
14708,
16,
7010,
3639,
19945,
559,
8808,
14708,
559,
16,
7010,
3639,
533,
2477,
16,
7010,
3639,
1758,
8526,
9484,
16,
7010,
3639,
2254,
5034,
8526,
30980,
16,
7010,
3639,
1731,
8526,
22790,
203,
565,
11272,
203,
203,
565,
871,
19945,
21890,
12,
2867,
8808,
450,
5607,
16,
2254,
5034,
8808,
14708,
1769,
203,
203,
565,
871,
19945,
55,
500,
87,
7653,
12,
2867,
8808,
272,
500,
2467,
16,
2254,
5034,
8808,
14708,
1769,
203,
377,
203,
565,
871,
27540,
9735,
12,
2867,
8808,
331,
20005,
16,
2254,
5034,
8808,
14708,
16,
1426,
8808,
6617,
537,
1769,
203,
203,
565,
871,
19945,
13533,
12,
11890,
5034,
8808,
14708,
16,
1426,
8808,
5061,
14592,
6433,
1769,
203,
203,
18701,
5475,
55,
203,
203,
565,
555,
10188,
1235,
5621,
203,
203,
565,
555,
12698,
5694,
5621,
203,
203,
565,
555,
4783,
16105,
2747,
5621,
203,
203,
565,
555,
3425,
1035,
6284,
560,
5694,
5621,
203,
203,
565,
555,
4378,
1477,
3754,
5621,
203,
203,
565,
555,
1412,
5694,
5621,
203,
203,
565,
555,
2288,
626,
5607,
5621,
203,
203,
565,
555,
348,
500,
87,
7653,
5621,
203,
203,
565,
555,
2288,
4419,
5621,
203,
203,
565,
555,
2288,
3935,
14592,
5621,
203,
203,
565,
555,
17009,
58,
16474,
5621,
203,
203,
565,
555,
2288,
19338,
429,
5621,
203,
203,
565,
555,
776,
17128,
1248,
28362,
5621,
203,
203,
565,
555,
24825,
1248,
13533,
5621,
203,
203,
565,
555,
2288,
3625,
5621,
203,
203,
18701,
463,
20463,
2347,
15553,
203,
203,
565,
533,
1071,
3270,
31,
203,
203,
565,
2254,
5034,
3238,
783,
55,
500,
87,
7653,
14592,
31,
203,
377,
203,
565,
2254,
5034,
1071,
14708,
1380,
31,
203,
203,
565,
2254,
1578,
1071,
331,
17128,
5027,
31,
203,
203,
565,
2254,
1578,
1071,
13658,
5027,
31,
203,
203,
203,
377,
203,
565,
1731,
1578,
1071,
5381,
776,
51,
1448,
67,
15920,
273,
7010,
3639,
417,
24410,
581,
5034,
2668,
2766,
19338,
12,
2867,
10363,
16,
11890,
5034,
14708,
16,
6430,
6617,
537,
2506,
1769,
203,
377,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
4418,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
19945,
13,
1071,
450,
22536,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
19945,
1119,
13,
1071,
14708,
7629,
31,
203,
203,
565,
2874,
12,
14592,
559,
516,
27540,
559,
13,
1071,
14708,
19338,
2016,
31,
203,
377,
203,
565,
2874,
12,
11890,
5034,
516,
2874,
12,
2867,
516,
1426,
3719,
1071,
331,
16474,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
1142,
22352,
19338,
31,
203,
203,
565,
2792,
19945,
559,
288,
203,
565,
289,
203,
203,
565,
2792,
27540,
559,
288,
203,
3639,
19098,
67,
26976,
14751,
16,
203,
3639,
19098,
67,
26976,
14751,
67,
3500,
916,
2799,
67,
14977,
16,
203,
3639,
16459,
654,
26976,
14751,
16,
203,
3639,
16459,
654,
26976,
14751,
67,
3500,
916,
2799,
67,
14977,
203,
565,
289,
203,
203,
565,
1958,
19945,
288,
203,
3639,
19945,
559,
14708,
559,
31,
203,
3639,
533,
2477,
31,
203,
3639,
2254,
5034,
2807,
14592,
31,
203,
3639,
2254,
10525,
12465,
29637,
31,
203,
3639,
2254,
10525,
1158,
29637,
31,
203,
3639,
2254,
1578,
6710,
950,
31,
203,
3639,
1758,
450,
5607,
31,
203,
565,
289,
203,
203,
565,
1958,
19945,
1119,
288,
203,
3639,
1426,
2275,
31,
203,
3639,
1426,
5204,
31,
203,
565,
289,
203,
203,
18701,
3492,
13915,
916,
203,
203,
565,
445,
1208,
12,
203,
3639,
533,
3778,
508,
67,
16,
203,
3639,
533,
3778,
3273,
67,
16,
203,
3639,
533,
3778,
3270,
67,
16,
203,
3639,
1426,
17781,
67,
16,
203,
3639,
1758,
8526,
3778,
4418,
67,
16,
203,
3639,
1731,
8526,
3778,
4418,
751,
67,
16,
203,
3639,
1758,
8526,
745,
892,
331,
352,
414,
67,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
24123,
67,
16,
203,
3639,
2254,
1578,
63,
2313,
65,
3778,
31841,
2628,
67,
203,
565,
262,
1071,
8843,
429,
1661,
426,
8230,
970,
5024,
288,
203,
3639,
309,
261,
9489,
27799,
2469,
480,
4418,
751,
27799,
2469,
13,
15226,
2631,
1076,
1553,
560,
5621,
203,
203,
3639,
309,
261,
90,
17128,
5027,
480,
374,
13,
15226,
10188,
1235,
5621,
203,
203,
3639,
309,
261,
75,
1527,
2628,
67,
63,
20,
65,
422,
374,
747,
31841,
2628,
67,
63,
20,
65,
405,
21382,
4681,
13,
15226,
12698,
5694,
5621,
203,
203,
3639,
309,
261,
75,
1527,
2628,
67,
63,
21,
65,
405,
21382,
4681,
13,
15226,
12698,
5694,
5621,
203,
203,
3639,
309,
261,
75,
1527,
2628,
67,
63,
22,
65,
405,
2130,
13,
15226,
4783,
16105,
2747,
5621,
203,
203,
3639,
309,
261,
75,
1527,
2628,
67,
63,
23,
65,
1648,
21119,
747,
31841,
2628,
67,
63,
23,
65,
405,
2130,
13,
15226,
3425,
1035,
6284,
560,
5694,
5621,
203,
203,
3639,
1475,
18083,
18485,
2316,
6315,
2738,
12,
529,
67,
16,
3273,
67,
16,
17781,
67,
16,
331,
352,
414,
67,
16,
24123,
67,
1769,
203,
203,
3639,
309,
261,
9489,
27799,
2469,
480,
374,
13,
288,
203,
5411,
22893,
288,
203,
7734,
364,
261,
11890,
5034,
277,
31,
277,
411,
4418,
27799,
2469,
31,
277,
27245,
288,
203,
10792,
4418,
63,
9489,
67,
63,
77,
13563,
273,
638,
31,
203,
203,
10792,
309,
261,
9489,
751,
67,
63,
77,
8009,
2469,
405,
890,
13,
288,
203,
13491,
261,
6430,
2216,
16,
262,
273,
4418,
67,
63,
77,
8009,
1991,
12,
9489,
751,
67,
63,
77,
19226,
203,
203,
13491,
309,
16051,
4768,
13,
15226,
4378,
1477,
3754,
5621,
203,
10792,
289,
203,
7734,
289,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
3270,
273,
3270,
67,
31,
203,
540,
203,
3639,
331,
17128,
5027,
273,
31841,
2628,
67,
63,
20,
15533,
203,
203,
3639,
13658,
5027,
273,
31841,
2628,
67,
63,
21,
15533,
203,
540,
203,
3639,
31854,
273,
31841,
2628,
67,
63,
22,
15533,
203,
540,
203,
2
] |
./full_match/1/0x33C1ECCfC6C68AFE51B9C8fa15eC03b6e919D298/sources/contracts/CETokenMinter.sol | * Set CE Token contract. OnlyOwner can call it @param _addr CE ERC721A Token address/ | function setCEToken(address _addr) external onlyOwner {
ceToken = IERC721(_addr);
}
| 4,942,960 | [
1,
4625,
348,
7953,
560,
30,
380,
1000,
29538,
3155,
6835,
18,
5098,
5541,
848,
745,
518,
632,
891,
389,
4793,
29538,
4232,
39,
27,
5340,
37,
3155,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1441,
1345,
12,
2867,
389,
4793,
13,
3903,
1338,
5541,
288,
203,
3639,
5898,
1345,
273,
467,
654,
39,
27,
5340,
24899,
4793,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 "./DelegatesStorage.sol";
///////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @title ERCXXXXReceiverDelegate
* @dev Contract to test safe transfer behavior via proxy with future standard delegate.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////
contract ERCXXXXReceiverDelegate is ProxyReceiverStorage_002_ERCXXXXFuture {
bytes4 constant public ERCXXXX_RECEIVED = 0x1234AAAA;
bytes4 constant public ERCXXXX_BATCH_RECEIVED = 0x4321BBBB;
bytes4 constant public NOT_ERCXXXX_RECEIVED = 0xDEADF00D; // Some random value
function setShouldRejectClash(bool _value) external {
require(address(this) == proxy, "Direct call: setShouldRejectClash");
shouldReject = _value;
}
function setShouldRejectXXXX(bool _value) external {
require(address(this) == proxy, "Direct call: setShouldRejectXXXX");
shouldRejectXXXX = _value;
}
function onERCXXXXReceived(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external view returns(bytes4) {
(_operator); (_from); (_id); (_value); (_data); // solidity, be quiet please
require(address(this) == proxy, "Direct call: onERCXXXXReceived");
if (shouldRejectXXXX == true) {
return NOT_ERCXXXX_RECEIVED;
} else {
return ERCXXXX_RECEIVED;
}
}
function onERCXXXXBatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external view returns(bytes4) {
(_operator); (_from); (_ids); (_values); (_data); // solidity, be quiet please
require(address(this) == proxy, "Direct call: onERCXXXXBatchReceived");
if (shouldRejectXXXX == true) {
return NOT_ERCXXXX_RECEIVED;
} else {
return ERCXXXX_BATCH_RECEIVED;
}
}
}
| solidity, be quiet please
| (_operator); (_from); (_ids); (_values); (_data); | 7,309,454 | [
1,
4625,
348,
7953,
560,
30,
225,
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
9497,
1769,
261,
67,
2080,
1769,
261,
67,
2232,
1769,
261,
67,
2372,
1769,
261,
67,
892,
1769,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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-08
*/
// Sources flattened with hardhat v2.8.0 https://hardhat.org
// File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected]
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File @openzeppelin/contracts-upgradeable/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 AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (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 a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[44] private __gap;
}
// File @openzeppelin/contracts-upgradeable/security/[email protected]
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// File @openzeppelin/contracts-upgradeable/access/[email protected]
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable {
function __ERC721Burnable_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Burnable_init_unchained();
}
function __ERC721Burnable_init_unchained() internal onlyInitializing {
}
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/proxy/beacon/[email protected]
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// File @openzeppelin/contracts-upgradeable/proxy/ERC1967/[email protected]
// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal onlyInitializing {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File contracts/jbac.sol
pragma solidity ^0.8.2;
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
contract JailedBabyApeClubV3 is Initializable, ERC721Upgradeable, PausableUpgradeable, OwnableUpgradeable, ERC721BurnableUpgradeable, UUPSUpgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
address proxyRegistryAddress;
uint256 basePrice;
/// v3 makes this variable public
uint256 public totalSupply;
CountersUpgradeable.Counter private _tokenIdCounter;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function initialize() initializer public {
__ERC721_init("Jailed Baby Ape Club", "JBAC");
__Pausable_init();
__Ownable_init();
__ERC721Burnable_init();
__UUPSUpgradeable_init();
address _proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1;
proxyRegistryAddress = _proxyRegistryAddress;
basePrice = 30000000000000000;
totalSupply = 8989;
_tokenIdCounter.increment();
}
function batchMint(uint256 count) public payable {
require(msg.value >= basePrice * count, 'INCREASE PAYMENT TO MINT');
for(uint256 i=0; i< count; i++){
uint256 tokenId = _tokenIdCounter.current();
require(tokenId <= totalSupply);
_tokenIdCounter.increment();
_safeMint(msg.sender, tokenId);
}
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
function currentToken() public view returns (uint256) {
uint256 currentNFT = _tokenIdCounter.current();
return currentNFT;
}
function _baseURI() internal pure override returns (string memory) {
return "https://api.jailedbabyape.club/v1/metadata/";
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function safeMint(address to) public payable {
require(msg.value >= basePrice, 'INCREASE PAYMENT TO MINT');
uint256 tokenId = _tokenIdCounter.current();
require(tokenId <= totalSupply);
_tokenIdCounter.increment();
_safeMint(to, tokenId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
whenNotPaused
override
{
super._beforeTokenTransfer(from, to, tokenId);
}
function _authorizeUpgrade(address newImplementation)
internal
onlyOwner
override
{}
function withdrawAll() public {
uint256 amount = address(this).balance;
require(payable(owner()).send(amount));
}
} | * @dev This abstract contract provides getters and event emitting update functions for _Available since v4.1._ @custom:oz-upgrades-unsafe-allow delegatecall/ | abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal onlyInitializing {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
event Upgraded(address indexed implementation);
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
if (!rollbackTesting.value) {
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
_upgradeTo(newImplementation);
}
}
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
if (!rollbackTesting.value) {
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
_upgradeTo(newImplementation);
}
}
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
if (!rollbackTesting.value) {
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
_upgradeTo(newImplementation);
}
}
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
event AdminChanged(address previousAdmin, address newAdmin);
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
event BeaconUpgraded(address indexed beacon);
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
uint256[50] private __gap;
}
| 6,771,695 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
5206,
1220,
8770,
6835,
8121,
23849,
471,
871,
3626,
1787,
1089,
4186,
364,
389,
5268,
3241,
331,
24,
18,
21,
6315,
632,
3662,
30,
11142,
17,
416,
13088,
17,
318,
4626,
17,
5965,
7152,
1991,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
4232,
39,
3657,
9599,
10784,
10784,
429,
353,
10188,
6934,
288,
203,
203,
203,
565,
445,
1001,
654,
39,
3657,
9599,
10784,
67,
2738,
1435,
2713,
1338,
29782,
288,
203,
3639,
1001,
654,
39,
3657,
9599,
10784,
67,
2738,
67,
4384,
8707,
5621,
203,
565,
289,
203,
203,
565,
445,
1001,
654,
39,
3657,
9599,
10784,
67,
2738,
67,
4384,
8707,
1435,
2713,
1338,
29782,
288,
203,
565,
289,
203,
203,
203,
203,
565,
1731,
1578,
3238,
5381,
389,
14555,
8720,
67,
55,
1502,
56,
273,
374,
92,
7616,
2163,
8313,
507,
2313,
31835,
1578,
4848,
329,
20,
73,
27,
29488,
74,
27,
952,
26,
2414,
2499,
69,
26,
3103,
6840,
70,
25,
70,
29,
7132,
26,
72,
2138,
69,
4449,
4313,
3461,
1403,
72,
29,
28643,
31,
203,
565,
1731,
1578,
2713,
5381,
389,
9883,
7618,
2689,
67,
55,
1502,
56,
273,
374,
92,
29751,
6675,
24,
69,
3437,
12124,
21,
69,
1578,
2163,
6028,
27,
71,
11149,
5193,
9975,
1966,
10689,
72,
5353,
23,
73,
3462,
6669,
952,
6418,
4763,
69,
29,
3462,
69,
23,
5353,
3361,
25,
72,
7414,
22,
9897,
71,
31,
203,
565,
871,
1948,
19305,
12,
2867,
8808,
4471,
1769,
203,
565,
445,
389,
588,
13621,
1435,
2713,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
5235,
8764,
10784,
429,
18,
588,
1887,
8764,
24899,
9883,
7618,
2689,
67,
55,
1502,
56,
2934,
1132,
31,
203,
565,
289,
203,
203,
565,
445,
389,
542,
13621,
12,
2867,
394,
13621,
13,
3238,
288,
203,
3639,
2583,
12,
1887,
10784,
429,
18,
291,
8924,
12,
2704,
13621,
3631,
315,
654,
39,
3657,
9599,
30,
394,
4471,
353,
486,
279,
6835,
8863,
203,
3639,
5235,
8764,
10784,
429,
18,
588,
1887,
8764,
24899,
9883,
7618,
2689,
67,
55,
1502,
56,
2934,
1132,
273,
394,
13621,
31,
203,
565,
289,
203,
203,
565,
445,
389,
15097,
774,
12,
2867,
394,
13621,
13,
2713,
288,
203,
3639,
389,
542,
13621,
12,
2704,
13621,
1769,
203,
3639,
3626,
1948,
19305,
12,
2704,
13621,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
15097,
774,
1876,
1477,
12,
203,
3639,
1758,
394,
13621,
16,
203,
3639,
1731,
3778,
501,
16,
203,
3639,
1426,
2944,
1477,
203,
565,
262,
2713,
288,
203,
3639,
389,
15097,
774,
12,
2704,
13621,
1769,
203,
3639,
309,
261,
892,
18,
2469,
405,
374,
747,
2944,
1477,
13,
288,
203,
5411,
389,
915,
9586,
1477,
12,
2704,
13621,
16,
501,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
389,
15097,
774,
1876,
1477,
12,
203,
3639,
1758,
394,
13621,
16,
203,
3639,
1731,
3778,
501,
16,
203,
3639,
1426,
2944,
1477,
203,
565,
262,
2713,
288,
203,
3639,
389,
15097,
774,
12,
2704,
13621,
1769,
203,
3639,
309,
261,
892,
18,
2469,
405,
374,
747,
2944,
1477,
13,
288,
203,
5411,
389,
915,
9586,
1477,
12,
2704,
13621,
16,
501,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
389,
15097,
774,
1876,
1477,
12834,
12,
203,
3639,
1758,
394,
13621,
16,
203,
3639,
1731,
3778,
501,
16,
203,
3639,
1426,
2944,
1477,
203,
565,
262,
2713,
288,
203,
3639,
1758,
1592,
13621,
273,
389,
588,
13621,
5621,
203,
203,
3639,
389,
542,
13621,
12,
2704,
13621,
1769,
203,
3639,
309,
261,
892,
18,
2469,
405,
374,
747,
2944,
1477,
13,
288,
203,
5411,
389,
915,
9586,
1477,
12,
2704,
13621,
16,
501,
1769,
203,
3639,
289,
203,
203,
3639,
309,
16051,
20050,
22218,
18,
1132,
13,
288,
203,
5411,
8006,
22218,
18,
1132,
273,
638,
31,
203,
5411,
389,
915,
9586,
1477,
12,
203,
7734,
394,
13621,
16,
203,
7734,
24126,
18,
3015,
1190,
5374,
2932,
15097,
774,
12,
2867,
2225,
16,
1592,
13621,
13,
203,
5411,
11272,
203,
5411,
8006,
22218,
18,
1132,
273,
629,
31,
203,
5411,
2583,
12,
1673,
13621,
422,
389,
588,
13621,
9334,
315,
654,
39,
3657,
9599,
10784,
30,
8400,
16217,
9271,
28844,
8863,
203,
5411,
389,
15097,
774,
12,
2704,
13621,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
203,
203,
565,
445,
389,
15097,
774,
1876,
1477,
12834,
12,
203,
3639,
1758,
394,
13621,
16,
203,
3639,
1731,
3778,
501,
16,
203,
3639,
1426,
2944,
1477,
203,
565,
262,
2713,
288,
203,
3639,
1758,
1592,
13621,
273,
389,
588,
13621,
5621,
203,
203,
3639,
389,
542,
13621,
12,
2704,
13621,
1769,
203,
3639,
309,
261,
892,
18,
2469,
405,
374,
747,
2944,
1477,
13,
288,
203,
5411,
389,
915,
9586,
1477,
12,
2704,
13621,
16,
501,
1769,
203,
3639,
289,
203,
203,
3639,
309,
16051,
20050,
22218,
18,
1132,
13,
288,
203,
5411,
8006,
22218,
18,
1132,
273,
638,
31,
203,
5411,
389,
915,
9586,
1477,
12,
203,
7734,
394,
13621,
16,
203,
7734,
24126,
18,
3015,
1190,
5374,
2932,
15097,
774,
12,
2867,
2225,
16,
1592,
13621,
13,
203,
5411,
11272,
203,
5411,
8006,
22218,
18,
1132,
273,
629,
31,
203,
5411,
2583,
12,
1673,
13621,
422,
389,
588,
13621,
9334,
315,
654,
39,
3657,
9599,
10784,
30,
8400,
16217,
9271,
28844,
8863,
203,
5411,
389,
15097,
774,
12,
2704,
13621,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
203,
203,
3639,
5235,
8764,
10784,
429,
18,
5507,
8764,
2502,
8006,
22218,
273,
5235,
8764,
10784,
429,
18,
588,
5507,
8764,
24899,
14555,
8720,
67,
55,
1502,
56,
1769,
203,
565,
445,
389,
15097,
774,
1876,
1477,
12834,
12,
203,
3639,
1758,
394,
13621,
16,
203,
3639,
1731,
3778,
501,
16,
203,
3639,
1426,
2944,
1477,
203,
565,
262,
2713,
288,
203,
3639,
1758,
1592,
13621,
273,
389,
588,
13621,
5621,
203,
203,
3639,
389,
542,
13621,
12,
2704,
13621,
1769,
203,
3639,
309,
261,
892,
18,
2469,
405,
374,
747,
2944,
1477,
13,
288,
203,
5411,
389,
915,
9586,
1477,
12,
2704,
13621,
16,
501,
1769,
203,
3639,
289,
203,
203,
3639,
309,
16051,
20050,
22218,
18,
1132,
13,
288,
203,
5411,
8006,
22218,
18,
1132,
273,
638,
31,
203,
5411,
389,
915,
9586,
1477,
12,
203,
7734,
394,
13621,
16,
203,
7734,
24126,
18,
3015,
1190,
5374,
2932,
15097,
774,
12,
2867,
2225,
16,
1592,
13621,
13,
203,
5411,
11272,
203,
5411,
8006,
22218,
18,
1132,
273,
2
] |
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.10;
/// @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
//////////////////////////////////////////////////////////////*/
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 {
address recoveredAddress = ecrecover(
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
),
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
),
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);
}
}
/// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/Auth.sol)
/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
abstract contract Auth {
event OwnerUpdated(address indexed user, address indexed newOwner);
event AuthorityUpdated(address indexed user, Authority indexed newAuthority);
address public owner;
Authority public authority;
constructor(address _owner, Authority _authority) {
owner = _owner;
authority = _authority;
emit OwnerUpdated(msg.sender, _owner);
emit AuthorityUpdated(msg.sender, _authority);
}
modifier requiresAuth() {
require(isAuthorized(msg.sender, msg.sig), "UNAUTHORIZED");
_;
}
function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) {
Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas.
// Checking if the caller is the owner only after calling the authority saves gas in most cases, but be
// aware that this makes protected functions uncallable even to the owner if the authority is out of order.
return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner;
}
function setAuthority(Authority newAuthority) public virtual {
// We check if the caller is the owner first because we want to ensure they can
// always swap out the authority even if it's reverting or using up a lot of gas.
require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig));
authority = newAuthority;
emit AuthorityUpdated(msg.sender, newAuthority);
}
function setOwner(address newOwner) public virtual requiresAuth {
owner = newOwner;
emit OwnerUpdated(msg.sender, newOwner);
}
}
/// @notice A generic interface for a contract which provides authorization data to an Auth instance.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/Auth.sol)
/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
interface Authority {
function canCall(
address user,
address target,
bytes4 functionSig
) external view returns (bool);
}
/// @notice Flexible and target agnostic role based Authority that supports up to 256 roles.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/authorities/MultiRolesAuthority.sol)
contract MultiRolesAuthority is Auth, Authority {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event UserRoleUpdated(address indexed user, uint8 indexed role, bool enabled);
event PublicCapabilityUpdated(bytes4 indexed functionSig, bool enabled);
event RoleCapabilityUpdated(uint8 indexed role, bytes4 indexed functionSig, bool enabled);
event TargetCustomAuthorityUpdated(address indexed target, Authority indexed authority);
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(address _owner, Authority _authority) Auth(_owner, _authority) {}
/*///////////////////////////////////////////////////////////////
CUSTOM TARGET AUTHORITY STORAGE
//////////////////////////////////////////////////////////////*/
mapping(address => Authority) public getTargetCustomAuthority;
/*///////////////////////////////////////////////////////////////
ROLE/USER STORAGE
//////////////////////////////////////////////////////////////*/
mapping(address => bytes32) public getUserRoles;
mapping(bytes4 => bool) public isCapabilityPublic;
mapping(bytes4 => bytes32) public getRolesWithCapability;
function doesUserHaveRole(address user, uint8 role) public view virtual returns (bool) {
return (uint256(getUserRoles[user]) >> role) & 1 != 0;
}
function doesRoleHaveCapability(uint8 role, bytes4 functionSig) public view virtual returns (bool) {
return (uint256(getRolesWithCapability[functionSig]) >> role) & 1 != 0;
}
/*///////////////////////////////////////////////////////////////
AUTHORIZATION LOGIC
//////////////////////////////////////////////////////////////*/
function canCall(
address user,
address target,
bytes4 functionSig
) public view virtual override returns (bool) {
Authority customAuthority = getTargetCustomAuthority[target];
if (address(customAuthority) != address(0)) return customAuthority.canCall(user, target, functionSig);
return
isCapabilityPublic[functionSig] || bytes32(0) != getUserRoles[user] & getRolesWithCapability[functionSig];
}
/*///////////////////////////////////////////////////////////////
CUSTOM TARGET AUTHORITY CONFIGURATION LOGIC
//////////////////////////////////////////////////////////////*/
function setTargetCustomAuthority(address target, Authority customAuthority) public virtual requiresAuth {
getTargetCustomAuthority[target] = customAuthority;
emit TargetCustomAuthorityUpdated(target, customAuthority);
}
/*///////////////////////////////////////////////////////////////
PUBLIC CAPABILITY CONFIGURATION LOGIC
//////////////////////////////////////////////////////////////*/
function setPublicCapability(bytes4 functionSig, bool enabled) public virtual requiresAuth {
isCapabilityPublic[functionSig] = enabled;
emit PublicCapabilityUpdated(functionSig, enabled);
}
/*///////////////////////////////////////////////////////////////
USER ROLE ASSIGNMENT LOGIC
//////////////////////////////////////////////////////////////*/
function setUserRole(
address user,
uint8 role,
bool enabled
) public virtual requiresAuth {
if (enabled) {
getUserRoles[user] |= bytes32(1 << role);
} else {
getUserRoles[user] &= ~bytes32(1 << role);
}
emit UserRoleUpdated(user, role, enabled);
}
/*///////////////////////////////////////////////////////////////
ROLE CAPABILITY CONFIGURATION LOGIC
//////////////////////////////////////////////////////////////*/
function setRoleCapability(
uint8 role,
bytes4 functionSig,
bool enabled
) public virtual requiresAuth {
if (enabled) {
getRolesWithCapability[functionSig] |= bytes32(1 << role);
} else {
getRolesWithCapability[functionSig] &= ~bytes32(1 << role);
}
emit RoleCapabilityUpdated(role, functionSig, enabled);
}
}
/// @title CERC20
/// @author Compound Labs and Rari Capital
/// @notice Minimal Compound/Fuse Comptroller interface.
abstract contract CERC20 is ERC20 {
/// @notice Deposit an amount of underlying tokens to the CERC20.
/// @param underlyingAmount Amount of underlying tokens to deposit.
/// @return An error code or zero if there was no error in the deposit.
function mint(uint256 underlyingAmount) external virtual returns (uint256);
/// @notice Borrow an amount of underlying tokens from the CERC20.
/// @param underlyingAmount Amount of underlying tokens to borrow.
/// @return An error code or zero if there was no error in the borrow.
function borrow(uint256 underlyingAmount) external virtual returns (uint256);
/// @notice Repay an amount of underlying tokens to the CERC20.
/// @param underlyingAmount Amount of underlying tokens to repay.
/// @return An error code or zero if there was no error in the repay.
function repayBorrow(uint256 underlyingAmount) external virtual returns (uint256);
/// @notice Returns the underlying balance of a specific user.
/// @param user The user who's balance the CERC20 will retrieve.
/// @return The amount of underlying tokens the user is entitled to.
function balanceOfUnderlying(address user) external view virtual returns (uint256);
/// @notice Returns the amount of underlying tokens a cToken redeemable for.
/// @return The amount of underlying tokens a cToken is redeemable for.
function exchangeRateStored() external view virtual returns (uint256);
/// @notice Withdraw a specific amount of underlying tokens from the CERC20.
/// @param underlyingAmount Amount of underlying tokens to withdraw.
/// @return An error code or zero if there was no error in the withdraw.
function redeemUnderlying(uint256 underlyingAmount) external virtual returns (uint256);
/// @notice Return teh current borrow balance of a user in the CERC20.
/// @param user The user to get the borrow balance for.
/// @return The current borrow balance of the user.
function borrowBalanceCurrent(address user) external virtual returns (uint256);
/// @notice Repay a user's borrow on their behalf.
/// @param user The user who's borrow to repay.
/// @param underlyingAmount The amount of debt to repay.
/// @return An error code or zero if there was no error in the repayBorrowBehalf.
function repayBorrowBehalf(address user, uint256 underlyingAmount) external virtual returns (uint256);
}
/// @notice Price Feed
/// @author Compound Labs
/// @notice Minimal cToken price feed interface.
interface PriceFeed {
/// @notice Get the underlying price of the cToken's asset.
/// @param cToken The cToken to get the underlying price of.
/// @return The underlying asset price scaled by 1e18.
function getUnderlyingPrice(CERC20 cToken) external view returns (uint256);
function add(address[] calldata underlyings, address[] calldata _oracles) external;
function changeAdmin(address newAdmin) external;
}
/// @title Comptroller
/// @author Compound Labs and Rari Capital
/// @notice Minimal Compound/Fuse Comptroller interface.
interface Comptroller {
/// @notice Retrieves the admin of the Comptroller.
/// @return The current administrator of the Comptroller.
function admin() external view returns (address);
/// @notice Retrieves the price feed of the Comptroller.
/// @return The current price feed of the Comptroller.
function oracle() external view returns (PriceFeed);
/// @notice Maps underlying tokens to their equivalent cTokens in a pool.
/// @param token The underlying token to find the equivalent cToken for.
/// @return The equivalent cToken for the given underlying token.
function cTokensByUnderlying(ERC20 token) external view returns (CERC20);
/// @notice Get's data about a cToken.
/// @param cToken The cToken to get data about.
/// @return isListed Whether the cToken is listed in the Comptroller.
/// @return collateralFactor The collateral factor of the cToken.
function markets(CERC20 cToken) external view returns (bool isListed, uint256 collateralFactor);
/// @notice Enters into a list of cToken markets, enabling them as collateral.
/// @param cTokens The list of cTokens to enter into, enabling them as collateral.
/// @return A list of error codes, or 0 if there were no failures in entering the cTokens.
function enterMarkets(CERC20[] calldata cTokens) external returns (uint256[] memory);
function _setPendingAdmin(address newPendingAdmin)
external
returns (uint256);
function _setBorrowCapGuardian(address newBorrowCapGuardian) external;
function _setMarketSupplyCaps(
CERC20[] calldata cTokens,
uint256[] calldata newSupplyCaps
) external;
function _setMarketBorrowCaps(
CERC20[] calldata cTokens,
uint256[] calldata newBorrowCaps
) external;
function _setPauseGuardian(address newPauseGuardian)
external
returns (uint256);
function _setMintPaused(CERC20 cToken, bool state)
external
returns (bool);
function _setBorrowPaused(CERC20 cToken, bool borrowPaused)
external
returns (bool);
function _setTransferPaused(bool state) external returns (bool);
function _setSeizePaused(bool state) external returns (bool);
function _setPriceOracle(address newOracle)
external
returns (uint256);
function _setCloseFactor(uint256 newCloseFactorMantissa)
external
returns (uint256);
function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa)
external
returns (uint256);
function _setCollateralFactor(
CERC20 cToken,
uint256 newCollateralFactorMantissa
) external returns (uint256);
function _acceptAdmin() external virtual returns (uint256);
function _deployMarket(
bool isCEther,
bytes calldata constructionData,
uint256 collateralFactorMantissa
) external returns (uint256);
function borrowGuardianPaused(address cToken)
external
view
returns (bool);
function comptrollerImplementation()
external
view
returns (address);
function rewardsDistributors(uint256 index)
external
view
returns (address);
function _addRewardsDistributor(address distributor)
external
returns (uint256);
function _setWhitelistEnforcement(bool enforce)
external
returns (uint256);
function _setWhitelistStatuses(
address[] calldata suppliers,
bool[] calldata statuses
) external returns (uint256);
function _unsupportMarket(CERC20 cToken) external returns (uint256);
function _toggleAutoImplementations(bool enabled)
external
returns (uint256);
}
// OpenZeppelin Contracts v4.4.1 (governance/TimelockController.sol)
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with 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;
}
}
// 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);
}
}
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.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 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 Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
/**
* @dev Contract module which acts as a timelocked controller. When set as the
* owner of an `Ownable` smart contract, it enforces a timelock on all
* `onlyOwner` maintenance operations. This gives time for users of the
* controlled contract to exit before a potentially dangerous maintenance
* operation is applied.
*
* By default, this contract is self administered, meaning administration tasks
* have to go through the timelock process. The proposer (resp executor) role
* is in charge of proposing (resp executing) operations. A common use case is
* to position this {TimelockController} as the owner of a smart contract, with
* a multisig or a DAO as the sole proposer.
*
* _Available since v3.3._
*/
contract TimelockController is AccessControl {
bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256("TIMELOCK_ADMIN_ROLE");
bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE");
bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE");
bytes32 public constant CANCELLER_ROLE = keccak256("CANCELLER_ROLE");
uint256 internal constant _DONE_TIMESTAMP = uint256(1);
mapping(bytes32 => uint256) private _timestamps;
uint256 private _minDelay;
/**
* @dev Emitted when a call is scheduled as part of operation `id`.
*/
event CallScheduled(
bytes32 indexed id,
uint256 indexed index,
address target,
uint256 value,
bytes data,
bytes32 predecessor,
uint256 delay
);
/**
* @dev Emitted when a call is performed as part of operation `id`.
*/
event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data);
/**
* @dev Emitted when operation `id` is cancelled.
*/
event Cancelled(bytes32 indexed id);
/**
* @dev Emitted when the minimum delay for future operations is modified.
*/
event MinDelayChange(uint256 oldDuration, uint256 newDuration);
/**
* @dev Initializes the contract with a given `minDelay`, and a list of
* initial proposers and executors. The proposers receive both the
* proposer and the canceller role (for backward compatibility). The
* executors receive the executor role.
*
* NOTE: At construction, both the deployer and the timelock itself are
* administrators. This helps further configuration of the timelock by the
* deployer. After configuration is done, it is recommended that the
* deployer renounces its admin position and relies on timelocked
* operations to perform future maintenance.
*/
constructor(
uint256 minDelay,
address[] memory proposers,
address[] memory executors
) {
_setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(CANCELLER_ROLE, TIMELOCK_ADMIN_ROLE);
// deployer + self administration
_setupRole(TIMELOCK_ADMIN_ROLE, _msgSender());
_setupRole(TIMELOCK_ADMIN_ROLE, address(this));
// register proposers and cancellers
for (uint256 i = 0; i < proposers.length; ++i) {
_setupRole(PROPOSER_ROLE, proposers[i]);
_setupRole(CANCELLER_ROLE, proposers[i]);
}
// register executors
for (uint256 i = 0; i < executors.length; ++i) {
_setupRole(EXECUTOR_ROLE, executors[i]);
}
_minDelay = minDelay;
emit MinDelayChange(0, minDelay);
}
/**
* @dev Modifier to make a function callable only by a certain role. In
* addition to checking the sender's role, `address(0)` 's role is also
* considered. Granting a role to `address(0)` is equivalent to enabling
* this role for everyone.
*/
modifier onlyRoleOrOpenRole(bytes32 role) {
if (!hasRole(role, address(0))) {
_checkRole(role, _msgSender());
}
_;
}
/**
* @dev Contract might receive/hold ETH as part of the maintenance process.
*/
receive() external payable {}
/**
* @dev Returns whether an id correspond to a registered operation. This
* includes both Pending, Ready and Done operations.
*/
function isOperation(bytes32 id) public view virtual returns (bool pending) {
return getTimestamp(id) > 0;
}
/**
* @dev Returns whether an operation is pending or not.
*/
function isOperationPending(bytes32 id) public view virtual returns (bool pending) {
return getTimestamp(id) > _DONE_TIMESTAMP;
}
/**
* @dev Returns whether an operation is ready or not.
*/
function isOperationReady(bytes32 id) public view virtual returns (bool ready) {
uint256 timestamp = getTimestamp(id);
return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;
}
/**
* @dev Returns whether an operation is done or not.
*/
function isOperationDone(bytes32 id) public view virtual returns (bool done) {
return getTimestamp(id) == _DONE_TIMESTAMP;
}
/**
* @dev Returns the timestamp at with an operation becomes ready (0 for
* unset operations, 1 for done operations).
*/
function getTimestamp(bytes32 id) public view virtual returns (uint256 timestamp) {
return _timestamps[id];
}
/**
* @dev Returns the minimum delay for an operation to become valid.
*
* This value can be changed by executing an operation that calls `updateDelay`.
*/
function getMinDelay() public view virtual returns (uint256 duration) {
return _minDelay;
}
/**
* @dev Returns the identifier of an operation containing a single
* transaction.
*/
function hashOperation(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt
) public pure virtual returns (bytes32 hash) {
return keccak256(abi.encode(target, value, data, predecessor, salt));
}
/**
* @dev Returns the identifier of an operation containing a batch of
* transactions.
*/
function hashOperationBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
bytes32 predecessor,
bytes32 salt
) public pure virtual returns (bytes32 hash) {
return keccak256(abi.encode(targets, values, datas, predecessor, salt));
}
/**
* @dev Schedule an operation containing a single transaction.
*
* Emits a {CallScheduled} event.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function schedule(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt,
uint256 delay
) public virtual onlyRole(PROPOSER_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_schedule(id, delay);
emit CallScheduled(id, 0, target, value, data, predecessor, delay);
}
/**
* @dev Schedule an operation containing a batch of transactions.
*
* Emits one {CallScheduled} event per transaction in the batch.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function scheduleBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
bytes32 predecessor,
bytes32 salt,
uint256 delay
) public virtual onlyRole(PROPOSER_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == datas.length, "TimelockController: length mismatch");
bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt);
_schedule(id, delay);
for (uint256 i = 0; i < targets.length; ++i) {
emit CallScheduled(id, i, targets[i], values[i], datas[i], predecessor, delay);
}
}
/**
* @dev Schedule an operation that is to becomes valid after a given delay.
*/
function _schedule(bytes32 id, uint256 delay) private {
require(!isOperation(id), "TimelockController: operation already scheduled");
require(delay >= getMinDelay(), "TimelockController: insufficient delay");
_timestamps[id] = block.timestamp + delay;
}
/**
* @dev Cancel an operation.
*
* Requirements:
*
* - the caller must have the 'canceller' role.
*/
function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) {
require(isOperationPending(id), "TimelockController: operation cannot be cancelled");
delete _timestamps[id];
emit Cancelled(id);
}
/**
* @dev Execute an (ready) operation containing a single transaction.
*
* Emits a {CallExecuted} event.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
// This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,
// thus any modifications to the operation during reentrancy should be caught.
// slither-disable-next-line reentrancy-eth
function execute(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_beforeCall(id, predecessor);
_call(id, 0, target, value, data);
_afterCall(id);
}
/**
* @dev Execute an (ready) operation containing a batch of transactions.
*
* Emits one {CallExecuted} event per transaction in the batch.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
function executeBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == datas.length, "TimelockController: length mismatch");
bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt);
_beforeCall(id, predecessor);
for (uint256 i = 0; i < targets.length; ++i) {
_call(id, i, targets[i], values[i], datas[i]);
}
_afterCall(id);
}
/**
* @dev Checks before execution of an operation's calls.
*/
function _beforeCall(bytes32 id, bytes32 predecessor) private view {
require(isOperationReady(id), "TimelockController: operation is not ready");
require(predecessor == bytes32(0) || isOperationDone(predecessor), "TimelockController: missing dependency");
}
/**
* @dev Checks after execution of an operation's calls.
*/
function _afterCall(bytes32 id) private {
require(isOperationReady(id), "TimelockController: operation is not ready");
_timestamps[id] = _DONE_TIMESTAMP;
}
/**
* @dev Execute an operation's call.
*
* Emits a {CallExecuted} event.
*/
function _call(
bytes32 id,
uint256 index,
address target,
uint256 value,
bytes calldata data
) private {
(bool success, ) = target.call{value: value}(data);
require(success, "TimelockController: underlying transaction reverted");
emit CallExecuted(id, index, target, value, data);
}
/**
* @dev Changes the minimum timelock duration for future operations.
*
* Emits a {MinDelayChange} event.
*
* Requirements:
*
* - the caller must be the timelock itself. This can only be achieved by scheduling and later executing
* an operation where the timelock is the target and the data is the ABI-encoded call to this function.
*/
function updateDelay(uint256 newDelay) external virtual {
require(msg.sender == address(this), "TimelockController: caller must be timelock");
emit MinDelayChange(_minDelay, newDelay);
_minDelay = newDelay;
}
}
/// @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)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
library SafeTransferLib {
event Debug(bool one, bool two, uint256 retsize);
/*///////////////////////////////////////////////////////////////
ETH OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferETH(address to, uint256 amount) internal {
bool success;
assembly {
// Transfer the ETH and store if it succeeded or not.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
require(success, "ETH_TRANSFER_FAILED");
}
/*///////////////////////////////////////////////////////////////
ERC20 OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 amount
) internal {
bool success;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), from) // Append the "from" argument.
mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (not just any non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the addition in the
// order of operations or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
)
}
require(success, "TRANSFER_FROM_FAILED");
}
function safeTransfer(
ERC20 token,
address to,
uint256 amount
) internal {
bool success;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (not just any non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the addition in the
// order of operations or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
require(success, "TRANSFER_FAILED");
}
function safeApprove(
ERC20 token,
address to,
uint256 amount
) internal {
bool success;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (not just any non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the addition in the
// order of operations or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
require(success, "APPROVE_FAILED");
}
}
/// @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
}
}
}
}
/// @notice Minimal ERC4626 tokenized Vault implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/mixins/ERC4626.sol)
/// @dev Do not use in production! ERC-4626 is still in the last call stage and is subject to change.
abstract contract ERC4626 is ERC20 {
using SafeTransferLib for ERC20;
using FixedPointMathLib for uint256;
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed caller,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/*///////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
ERC20 public immutable asset;
constructor(
ERC20 _asset,
string memory _name,
string memory _symbol
) ERC20(_name, _symbol, _asset.decimals()) {
asset = _asset;
}
/*///////////////////////////////////////////////////////////////
DEPOSIT/WITHDRAWAL LOGIC
//////////////////////////////////////////////////////////////*/
function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) {
// Check for rounding error since we round down in previewDeposit.
require((shares = previewDeposit(assets)) != 0, "ZERO_SHARES");
// Need to transfer before minting or ERC777s could reenter.
asset.safeTransferFrom(msg.sender, address(this), assets);
_mint(receiver, shares);
emit Deposit(msg.sender, receiver, assets, shares);
afterDeposit(assets, shares);
}
function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) {
assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.
// Need to transfer before minting or ERC777s could reenter.
asset.safeTransferFrom(msg.sender, address(this), assets);
_mint(receiver, shares);
emit Deposit(msg.sender, receiver, assets, shares);
afterDeposit(assets, shares);
}
function withdraw(
uint256 assets,
address receiver,
address owner
) public virtual returns (uint256 shares) {
shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.
if (msg.sender != owner) {
uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
}
beforeWithdraw(assets, shares);
_burn(owner, shares);
emit Withdraw(msg.sender, receiver, owner, assets, shares);
asset.safeTransfer(receiver, assets);
}
function redeem(
uint256 shares,
address receiver,
address owner
) public virtual returns (uint256 assets) {
if (msg.sender != owner) {
uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
}
// Check for rounding error since we round down in previewRedeem.
require((assets = previewRedeem(shares)) != 0, "ZERO_ASSETS");
beforeWithdraw(assets, shares);
_burn(owner, shares);
emit Withdraw(msg.sender, receiver, owner, assets, shares);
asset.safeTransfer(receiver, assets);
}
/*///////////////////////////////////////////////////////////////
ACCOUNTING LOGIC
//////////////////////////////////////////////////////////////*/
function totalAssets() public view virtual returns (uint256);
function convertToShares(uint256 assets) public view returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());
}
function convertToAssets(uint256 shares) public view returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);
}
function previewDeposit(uint256 assets) public view virtual returns (uint256) {
return convertToShares(assets);
}
function previewMint(uint256 shares) public view virtual returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);
}
function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());
}
function previewRedeem(uint256 shares) public view virtual returns (uint256) {
return convertToAssets(shares);
}
/*///////////////////////////////////////////////////////////////
DEPOSIT/WITHDRAWAL LIMIT LOGIC
//////////////////////////////////////////////////////////////*/
function maxDeposit(address) public view virtual returns (uint256) {
return type(uint256).max;
}
function maxMint(address) public view virtual returns (uint256) {
return type(uint256).max;
}
function maxWithdraw(address owner) public view virtual returns (uint256) {
return convertToAssets(balanceOf[owner]);
}
function maxRedeem(address owner) public view virtual returns (uint256) {
return balanceOf[owner];
}
/*///////////////////////////////////////////////////////////////
INTERNAL HOOKS LOGIC
//////////////////////////////////////////////////////////////*/
function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}
function afterDeposit(uint256 assets, uint256 shares) internal virtual {}
}
/// @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;
}
}
/// @title Fuse Admin
/// @author Fei Protocol
/// @notice Minimal Fuse Admin interface.
interface FuseAdmin {
/// @notice Whitelists or blacklists a user from accessing the cTokens in the pool.
/// @param users The users to whitelist or blacklist.
/// @param enabled Whether to whitelist or blacklist each user.
function _setWhitelistStatuses(address[] calldata users, bool[] calldata enabled) external;
function _deployMarket(
address underlying,
address irm,
string calldata name,
string calldata symbol,
address impl,
bytes calldata data,
uint256 reserveFactor,
uint256 adminFee,
uint256 collateralFactorMantissa
) external;
}
interface IReverseRegistrar {
/**
@notice sets reverse ENS Record
@param name the ENS record to set
After calling this, a user has a fully configured reverse record claiming the provided name as that account's canonical name.
*/
function setName(string memory name) external returns (bytes32);
}
/**
@title helper contract to set reverse ens record with solmate Auth
@author joeysantoro
@notice sets reverse ENS record against canonical ReverseRegistrar https://docs.ens.domains/contract-api-reference/reverseregistrar.
*/
abstract contract ENSReverseRecordAuth is Auth {
/// @notice the ENS Reverse Registrar
IReverseRegistrar public constant REVERSE_REGISTRAR = IReverseRegistrar(0x084b1c3C81545d370f3634392De611CaaBFf8148);
function setENSName(string memory name) external requiresAuth {
REVERSE_REGISTRAR.setName(name);
}
}
/// @title Turbo Clerk
/// @author Transmissions11
/// @notice Fee determination module for Turbo Safes.
contract TurboClerk is Auth, ENSReverseRecordAuth {
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Creates a new Turbo Clerk contract.
/// @param _owner The owner of the Clerk.
/// @param _authority The Authority of the Clerk.
constructor(address _owner, Authority _authority) Auth(_owner, _authority) {}
/*///////////////////////////////////////////////////////////////
DEFAULT FEE CONFIGURATION
//////////////////////////////////////////////////////////////*/
/// @notice The default fee on Safe interest taken by the protocol.
/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
uint256 public defaultFeePercentage;
/// @notice Emitted when the default fee percentage is updated.
/// @param newDefaultFeePercentage The new default fee percentage.
event DefaultFeePercentageUpdated(address indexed user, uint256 newDefaultFeePercentage);
/// @notice Sets the default fee percentage.
/// @param newDefaultFeePercentage The new default fee percentage.
function setDefaultFeePercentage(uint256 newDefaultFeePercentage) external requiresAuth {
// A fee percentage over 100% makes no sense.
require(newDefaultFeePercentage <= 1e18, "FEE_TOO_HIGH");
// Update the default fee percentage.
defaultFeePercentage = newDefaultFeePercentage;
emit DefaultFeePercentageUpdated(msg.sender, newDefaultFeePercentage);
}
/*///////////////////////////////////////////////////////////////
CUSTOM FEE CONFIGURATION
//////////////////////////////////////////////////////////////*/
/// @notice Maps collaterals to their custom fees on interest taken by the protocol.
/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
mapping(ERC20 => uint256) public getCustomFeePercentageForCollateral;
/// @notice Maps Safes to their custom fees on interest taken by the protocol.
/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
mapping(TurboSafe => uint256) public getCustomFeePercentageForSafe;
/// @notice Emitted when a collateral's custom fee percentage is updated.
/// @param collateral The collateral who's custom fee percentage was updated.
/// @param newFeePercentage The new custom fee percentage.
event CustomFeePercentageUpdatedForCollateral(
address indexed user,
ERC20 indexed collateral,
uint256 newFeePercentage
);
/// @notice Sets a collateral's custom fee percentage.
/// @param collateral The collateral to set the custom fee percentage for.
/// @param newFeePercentage The new custom fee percentage for the collateral.
function setCustomFeePercentageForCollateral(ERC20 collateral, uint256 newFeePercentage) external requiresAuth {
// A fee percentage over 100% makes no sense.
require(newFeePercentage <= 1e18, "FEE_TOO_HIGH");
// Update the custom fee percentage for the Safe.
getCustomFeePercentageForCollateral[collateral] = newFeePercentage;
emit CustomFeePercentageUpdatedForCollateral(msg.sender, collateral, newFeePercentage);
}
/// @notice Emitted when a Safe's custom fee percentage is updated.
/// @param safe The Safe who's custom fee percentage was updated.
/// @param newFeePercentage The new custom fee percentage.
event CustomFeePercentageUpdatedForSafe(address indexed user, TurboSafe indexed safe, uint256 newFeePercentage);
/// @notice Sets a Safe's custom fee percentage.
/// @param safe The Safe to set the custom fee percentage for.
/// @param newFeePercentage The new custom fee percentage for the Safe.
function setCustomFeePercentageForSafe(TurboSafe safe, uint256 newFeePercentage) external requiresAuth {
// A fee percentage over 100% makes no sense.
require(newFeePercentage <= 1e18, "FEE_TOO_HIGH");
// Update the custom fee percentage for the Safe.
getCustomFeePercentageForSafe[safe] = newFeePercentage;
emit CustomFeePercentageUpdatedForSafe(msg.sender, safe, newFeePercentage);
}
/*///////////////////////////////////////////////////////////////
ACCOUNTING LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Returns the fee on interest taken by the protocol for a Safe.
/// @param safe The Safe to get the fee percentage for.
/// @param collateral The collateral/asset of the Safe.
/// @return The fee percentage for the Safe.
function getFeePercentageForSafe(TurboSafe safe, ERC20 collateral) external view returns (uint256) {
// Get the custom fee percentage for the Safe.
uint256 customFeePercentageForSafe = getCustomFeePercentageForSafe[safe];
// If a custom fee percentage is set for the Safe, return it.
if (customFeePercentageForSafe != 0) return customFeePercentageForSafe;
// Get the custom fee percentage for the collateral type.
uint256 customFeePercentageForCollateral = getCustomFeePercentageForCollateral[collateral];
// If a custom fee percentage is set for the collateral, return it.
if (customFeePercentageForCollateral != 0) return customFeePercentageForCollateral;
// Otherwise, return the default fee percentage.
return defaultFeePercentage;
}
}
/// @title Turbo Master
/// @author Transmissions11
/// @notice Factory for creating and managing Turbo Safes.
/// @dev Must be authorized to call the Turbo Fuse Pool's FuseAdmin.
contract TurboMaster is Auth, ENSReverseRecordAuth {
using SafeTransferLib for ERC20;
/*///////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
/// @notice The Turbo Fuse Pool the Safes will interact with.
Comptroller public immutable pool;
/// @notice The Fei token on the network.
ERC20 public immutable fei;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Creates a new Turbo Master contract.
/// @param _pool The Turbo Fuse Pool the Master will use.
/// @param _fei The Fei token on the network.
/// @param _owner The owner of the Master.
/// @param _authority The Authority of the Master.
constructor(
Comptroller _pool,
ERC20 _fei,
address _owner,
Authority _authority
) Auth(_owner, _authority) {
pool = _pool;
fei = _fei;
// Prevent the first safe from getting id 0.
safes.push(TurboSafe(address(0)));
}
/*///////////////////////////////////////////////////////////////
BOOSTER STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice The Booster module used by the Master and its Safes.
TurboBooster public booster;
/// @notice Emitted when the Booster is updated.
/// @param user The user who triggered the update of the Booster.
/// @param newBooster The new Booster contract used by the Master.
event BoosterUpdated(address indexed user, TurboBooster newBooster);
/// @notice Update the Booster used by the Master.
/// @param newBooster The new Booster contract to be used by the Master.
function setBooster(TurboBooster newBooster) external requiresAuth {
booster = newBooster;
emit BoosterUpdated(msg.sender, newBooster);
}
/*///////////////////////////////////////////////////////////////
CLERK STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice The Clerk module used by the Master and its Safes.
TurboClerk public clerk;
/// @notice Emitted when the Clerk is updated.
/// @param user The user who triggered the update of the Clerk.
/// @param newClerk The new Clerk contract used by the Master.
event ClerkUpdated(address indexed user, TurboClerk newClerk);
/// @notice Update the Clerk used by the Master.
/// @param newClerk The new Clerk contract to be used by the Master.
function setClerk(TurboClerk newClerk) external requiresAuth {
clerk = newClerk;
emit ClerkUpdated(msg.sender, newClerk);
}
/*///////////////////////////////////////////////////////////////
DEFAULT SAFE AUTHORITY CONFIGURATION
//////////////////////////////////////////////////////////////*/
/// @notice The default authority to be used by created Safes.
Authority public defaultSafeAuthority;
/// @notice Emitted when the default safe authority is updated.
/// @param user The user who triggered the update of the default safe authority.
/// @param newDefaultSafeAuthority The new default authority to be used by created Safes.
event DefaultSafeAuthorityUpdated(address indexed user, Authority newDefaultSafeAuthority);
/// @notice Set the default authority to be used by created Safes.
/// @param newDefaultSafeAuthority The new default safe authority.
function setDefaultSafeAuthority(Authority newDefaultSafeAuthority) external requiresAuth {
// Update the default safe authority.
defaultSafeAuthority = newDefaultSafeAuthority;
emit DefaultSafeAuthorityUpdated(msg.sender, newDefaultSafeAuthority);
}
/*///////////////////////////////////////////////////////////////
SAFE STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice The total Fei currently boosting Vaults.
uint256 public totalBoosted;
/// @notice Maps Safe addresses to the id they are stored under in the Safes array.
mapping(TurboSafe => uint256) public getSafeId;
/// @notice Maps Vault addresses to the total amount of Fei they've being boosted with.
mapping(ERC4626 => uint256) public getTotalBoostedForVault;
/// @notice Maps collateral types to the total amount of Fei boosted by Safes using it as collateral.
mapping(ERC20 => uint256) public getTotalBoostedAgainstCollateral;
/// @notice An array of all Safes created by the Master.
/// @dev The first Safe is purposely invalid to prevent any Safes from having an id of 0.
TurboSafe[] public safes;
/// @notice Returns all Safes created by the Master.
/// @return An array of all Safes created by the Master.
/// @dev This is provided because Solidity converts public arrays into index getters,
/// but we need a way to allow external contracts and users to access the whole array.
function getAllSafes() external view returns (TurboSafe[] memory) {
return safes;
}
/*///////////////////////////////////////////////////////////////
SAFE CREATION LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when a new Safe is created.
/// @param user The user who created the Safe.
/// @param asset The asset of the Safe.
/// @param safe The newly deployed Safe contract.
/// @param id The index of the Safe in the safes array.
event TurboSafeCreated(address indexed user, ERC20 indexed asset, TurboSafe safe, uint256 id);
/// @notice Creates a new Turbo Safe which supports a specific asset.
/// @param asset The ERC20 token that the Safe should accept.
/// @return safe The newly deployed Turbo Safe which accepts the provided asset.
function createSafe(ERC20 asset) external requiresAuth returns (TurboSafe safe, uint256 id) {
// Create a new Safe using the default authority and provided asset.
safe = new TurboSafe(msg.sender, defaultSafeAuthority, asset);
// Add the safe to the list of Safes.
safes.push(safe);
unchecked {
// Get the index/id of the new Safe.
// Cannot underflow, we just pushed to it.
id = safes.length - 1;
}
// Store the id/index of the new Safe.
getSafeId[safe] = id;
emit TurboSafeCreated(msg.sender, asset, safe, id);
// Prepare a users array to whitelist the Safe.
address[] memory users = new address[](1);
users[0] = address(safe);
// Prepare an enabled array to whitelist the Safe.
bool[] memory enabled = new bool[](1);
enabled[0] = true;
// Whitelist the Safe to access the Turbo Fuse Pool.
FuseAdmin(pool.admin())._setWhitelistStatuses(users, enabled);
}
/*///////////////////////////////////////////////////////////////
SAFE CALLBACK LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Callback triggered whenever a Safe boosts a Vault.
/// @param asset The asset of the Safe.
/// @param vault The Vault that was boosted.
/// @param feiAmount The amount of Fei used to boost the Vault.
function onSafeBoost(
ERC20 asset,
ERC4626 vault,
uint256 feiAmount
) external {
// Get the caller as a Safe instance.
TurboSafe safe = TurboSafe(msg.sender);
// Ensure the Safe was created by this Master.
require(getSafeId[safe] != 0, "INVALID_SAFE");
// Update the total amount of Fei being using to boost Vaults.
totalBoosted += feiAmount;
// Cache the new total boosted for the Vault.
uint256 newTotalBoostedForVault;
// Cache the new total boosted against the Vault's collateral.
uint256 newTotalBoostedAgainstCollateral;
// Update the total amount of Fei being using to boost the Vault.
getTotalBoostedForVault[vault] = (newTotalBoostedForVault = getTotalBoostedForVault[vault] + feiAmount);
// Update the total amount of Fei boosted against the collateral type.
getTotalBoostedAgainstCollateral[asset] = (newTotalBoostedAgainstCollateral =
getTotalBoostedAgainstCollateral[asset] +
feiAmount);
// Check with the booster that the Safe is allowed to boost the Vault using this amount of Fei.
require(
booster.canSafeBoostVault(
safe,
asset,
vault,
feiAmount,
newTotalBoostedForVault,
newTotalBoostedAgainstCollateral
),
"BOOSTER_REJECTED"
);
}
/// @notice Callback triggered whenever a Safe withdraws from a Vault.
/// @param asset The asset of the Safe.
/// @param vault The Vault that was withdrawn from.
/// @param feiAmount The amount of Fei withdrawn from the Vault.
function onSafeLess(
ERC20 asset,
ERC4626 vault,
uint256 feiAmount
) external {
// Get the caller as a Safe instance.
TurboSafe safe = TurboSafe(msg.sender);
// Ensure the Safe was created by this Master.
require(getSafeId[safe] != 0, "INVALID_SAFE");
// Update the total amount of Fei being using to boost the Vault.
getTotalBoostedForVault[vault] -= feiAmount;
// Update the total amount of Fei being using to boost Vaults.
totalBoosted -= feiAmount;
// Update the total amount of Fei boosted against the collateral type.
getTotalBoostedAgainstCollateral[asset] -= feiAmount;
}
/*///////////////////////////////////////////////////////////////
SWEEP LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted a token is sweeped from the Master.
/// @param user The user who sweeped the token from the Master.
/// @param to The recipient of the sweeped tokens.
/// @param amount The amount of the token that was sweeped.
event TokenSweeped(address indexed user, address indexed to, ERC20 indexed token, uint256 amount);
/// @notice Claim tokens sitting idly in the Master.
/// @param to The recipient of the sweeped tokens.
/// @param token The token to sweep and send.
/// @param amount The amount of the token to sweep.
function sweep(
address to,
ERC20 token,
uint256 amount
) external requiresAuth {
emit TokenSweeped(msg.sender, to, token, amount);
// Transfer the sweeped tokens to the recipient.
token.safeTransfer(to, amount);
}
}
/// @title Turbo Safe
/// @author Transmissions11
/// @notice Fuse liquidity accelerator.
contract TurboSafe is Auth, ERC4626, ReentrancyGuard {
using SafeTransferLib for ERC20;
using FixedPointMathLib for uint256;
/*///////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
/// @notice The Master contract that created the Safe.
/// @dev Fees are paid directly to the Master, where they can be swept.
TurboMaster public immutable master;
/// @notice The Fei token on the network.
ERC20 public immutable fei;
/// @notice The Turbo Fuse Pool contract that collateral is held in and Fei is borrowed from.
Comptroller public immutable pool;
/// @notice The Fei cToken in the Turbo Fuse Pool that Fei is borrowed from.
CERC20 public immutable feiTurboCToken;
/// @notice The cToken that accepts the asset in the Turbo Fuse Pool.
CERC20 public immutable assetTurboCToken;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Creates a new Safe that accepts a specific asset.
/// @param _owner The owner of the Safe.
/// @param _authority The Authority of the Safe.
/// @param _asset The ERC20 compliant token the Safe should accept.
constructor(
address _owner,
Authority _authority,
ERC20 _asset
)
Auth(_owner, _authority)
ERC4626(
_asset,
// ex: Dai Stablecoin Turbo Safe
string(abi.encodePacked(_asset.name(), " Turbo Safe")),
// ex: tsDAI
string(abi.encodePacked("ts", _asset.symbol()))
)
{
master = TurboMaster(msg.sender);
fei = master.fei();
// An asset of Fei makes no sense.
require(asset != fei, "INVALID_ASSET");
pool = master.pool();
feiTurboCToken = pool.cTokensByUnderlying(fei);
assetTurboCToken = pool.cTokensByUnderlying(asset);
// If the provided asset is not supported by the Turbo Fuse Pool, revert.
require(address(assetTurboCToken) != address(0), "UNSUPPORTED_ASSET");
// Construct an array of market(s) to enable as collateral.
CERC20[] memory marketsToEnter = new CERC20[](1);
marketsToEnter[0] = assetTurboCToken;
// Enter the market(s) and ensure to properly revert if there is an error.
require(pool.enterMarkets(marketsToEnter)[0] == 0, "ENTER_MARKETS_FAILED");
// Preemptively approve the asset to the Turbo Fuse Pool's corresponding cToken.
asset.safeApprove(address(assetTurboCToken), type(uint256).max);
// Preemptively approve Fei to the Turbo Fuse Pool's Fei cToken.
fei.safeApprove(address(feiTurboCToken), type(uint256).max);
}
/*///////////////////////////////////////////////////////////////
SAFE STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice The current total amount of Fei the Safe is using to boost Vaults.
uint256 public totalFeiBoosted;
/// @notice Maps Vaults to the total amount of Fei they've being boosted with.
/// @dev Used to determine the fees to be paid back to the Master.
mapping(ERC4626 => uint256) public getTotalFeiBoostedForVault;
/*///////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////*/
/// @dev Checks the caller is authorized using either the Master's Authority or the Safe's local Authority.
modifier requiresLocalOrMasterAuth() {
// Check if the caller is the owner first:
if (msg.sender != owner) {
Authority masterAuth = master.authority(); // Avoid wasting gas calling the Master twice.
// If the Master's Authority does not exist or does not accept upfront:
if (address(masterAuth) == address(0) || !masterAuth.canCall(msg.sender, address(this), msg.sig)) {
Authority auth = authority; // Memoizing saves us a warm SLOAD, around 100 gas.
// The only authorization option left is via the local Authority, otherwise revert.
require(
address(auth) != address(0) && auth.canCall(msg.sender, address(this), msg.sig),
"UNAUTHORIZED"
);
}
}
_;
}
/// @dev Checks the caller is authorized using the Master's Authority.
modifier requiresMasterAuth() {
Authority masterAuth = master.authority(); // Avoid wasting gas calling the Master twice.
// Revert if the Master's Authority does not approve of the call and the caller is not the Master's owner.
require(
(address(masterAuth) != address(0) && masterAuth.canCall(msg.sender, address(this), msg.sig)) ||
msg.sender == master.owner(),
"UNAUTHORIZED"
);
_;
}
/*///////////////////////////////////////////////////////////////
ERC4626 LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Called after any type of deposit occurs.
/// @param assetAmount The amount of assets being deposited.
/// @dev Using requiresAuth here prevents unauthorized users from depositing.
function afterDeposit(uint256 assetAmount, uint256) internal override nonReentrant requiresAuth {
// Collateralize the assets in the Turbo Fuse Pool.
require(assetTurboCToken.mint(assetAmount) == 0, "MINT_FAILED");
}
/// @notice Called before any type of withdrawal occurs.
/// @param assetAmount The amount of assets being withdrawn.
/// @dev Using requiresAuth here prevents unauthorized users from withdrawing.
function beforeWithdraw(uint256 assetAmount, uint256) internal override nonReentrant requiresAuth {
// Withdraw the assets from the Turbo Fuse Pool.
require(assetTurboCToken.redeemUnderlying(assetAmount) == 0, "REDEEM_FAILED");
}
/// @notice Returns the total amount of assets held in the Safe.
/// @return The total amount of assets held in the Safe.
function totalAssets() public view override returns (uint256) {
return assetTurboCToken.balanceOf(address(this)).mulWadDown(assetTurboCToken.exchangeRateStored());
}
/*///////////////////////////////////////////////////////////////
BOOST/LESS LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when a Vault is boosted by the Safe.
/// @param user The user who boosted the Vault.
/// @param vault The Vault that was boosted.
/// @param feiAmount The amount of Fei that was boosted to the Vault.
event VaultBoosted(address indexed user, ERC4626 indexed vault, uint256 feiAmount);
/// @notice Borrow Fei from the Turbo Fuse Pool and deposit it into an authorized Vault.
/// @param vault The Vault to deposit the borrowed Fei into.
/// @param feiAmount The amount of Fei to borrow and supply into the Vault.
function boost(ERC4626 vault, uint256 feiAmount) external nonReentrant requiresAuth {
// Ensure the Vault accepts Fei asset.
require(vault.asset() == fei, "NOT_FEI");
// Call the Master where it will do extra validation
// and update it's total count of funds used for boosting.
master.onSafeBoost(asset, vault, feiAmount);
// Increase the boost total proportionately.
totalFeiBoosted += feiAmount;
// Update the total Fei deposited into the Vault proportionately.
getTotalFeiBoostedForVault[vault] += feiAmount;
emit VaultBoosted(msg.sender, vault, feiAmount);
// Borrow the Fei amount from the Fei cToken in the Turbo Fuse Pool.
require(feiTurboCToken.borrow(feiAmount) == 0, "BORROW_FAILED");
// Approve the borrowed Fei to the specified Vault.
fei.safeApprove(address(vault), feiAmount);
// Deposit the Fei into the specified Vault.
vault.deposit(feiAmount, address(this));
}
/// @notice Emitted when a Vault is withdrawn from by the Safe.
/// @param user The user who lessed the Vault.
/// @param vault The Vault that was withdrawn from.
/// @param feiAmount The amount of Fei that was withdrawn from the Vault.
event VaultLessened(address indexed user, ERC4626 indexed vault, uint256 feiAmount);
/// @notice Withdraw Fei from a deposited Vault and use it to repay debt in the Turbo Fuse Pool.
/// @param vault The Vault to withdraw the Fei from.
/// @param feiAmount The amount of Fei to withdraw from the Vault and repay in the Turbo Fuse Pool.
function less(ERC4626 vault, uint256 feiAmount) external nonReentrant requiresLocalOrMasterAuth {
// Update the total Fei deposited into the Vault proportionately.
getTotalFeiBoostedForVault[vault] -= feiAmount;
// Decrease the boost total proportionately.
totalFeiBoosted -= feiAmount;
emit VaultLessened(msg.sender, vault, feiAmount);
// Withdraw the specified amount of Fei from the Vault.
vault.withdraw(feiAmount, address(this), address(this));
// Get out current amount of Fei debt in the Turbo Fuse Pool.
uint256 feiDebt = feiTurboCToken.borrowBalanceCurrent(address(this));
// Call the Master to allow it to update its accounting.
master.onSafeLess(asset, vault, feiAmount);
// If our debt balance decreased, repay the minimum.
// The surplus Fei will accrue as fees and can be sweeped.
if (feiAmount > feiDebt) feiAmount = feiDebt;
// Repay Fei debt in the Turbo Fuse Pool, unless we would repay nothing.
if (feiAmount != 0) require(feiTurboCToken.repayBorrow(feiAmount) == 0, "REPAY_FAILED");
}
/*///////////////////////////////////////////////////////////////
SLURP LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when a Vault is slurped from by the Safe.
/// @param user The user who slurped the Vault.
/// @param vault The Vault that was slurped.
/// @param protocolFeeAmount The amount of Fei accrued as fees to the Master.
/// @param safeInterestAmount The amount of Fei accrued as interest to the Safe.
event VaultSlurped(
address indexed user,
ERC4626 indexed vault,
uint256 protocolFeeAmount,
uint256 safeInterestAmount
);
/// @notice Accrue any interest earned by the Safe in the Vault.
/// @param vault The Vault to accrue interest from, if any.
/// @dev Sends a portion of the interest to the Master, as determined by the Clerk.
function slurp(ERC4626 vault) external nonReentrant requiresLocalOrMasterAuth returns(uint256 safeInterestAmount) {
// Cache the total Fei currently boosting the Vault.
uint256 totalFeiBoostedForVault = getTotalFeiBoostedForVault[vault];
// Ensure the Safe has Fei currently boosting the Vault.
require(totalFeiBoostedForVault != 0, "NO_FEI_BOOSTED");
// Compute the amount of Fei interest the Safe generated by boosting the Vault.
uint256 interestEarned = vault.previewRedeem(vault.balanceOf(address(this))) - totalFeiBoostedForVault;
// Compute what percentage of the interest earned will go back to the Safe.
uint256 protocolFeePercent = master.clerk().getFeePercentageForSafe(this, asset);
// Compute the amount of Fei the protocol will retain as fees.
uint256 protocolFeeAmount = interestEarned.mulWadDown(protocolFeePercent);
// Compute the amount of Fei the Safe will retain as interest.
safeInterestAmount = interestEarned - protocolFeeAmount;
emit VaultSlurped(msg.sender, vault, protocolFeeAmount, safeInterestAmount);
vault.withdraw(interestEarned, address(this), address(this));
// If we have unaccrued fees, withdraw them from the Vault and transfer them to the Master.
if (protocolFeeAmount != 0) fei.transfer(address(master), protocolFeeAmount);
}
/*///////////////////////////////////////////////////////////////
SWEEP LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted a token is sweeped from the Safe.
/// @param user The user who sweeped the token from the Safe.
/// @param to The recipient of the sweeped tokens.
/// @param amount The amount of the token that was sweeped.
event TokenSweeped(address indexed user, address indexed to, ERC20 indexed token, uint256 amount);
/// @notice Claim tokens sitting idly in the Safe.
/// @param to The recipient of the sweeped tokens.
/// @param token The token to sweep and send.
/// @param amount The amount of the token to sweep.
function sweep(
address to,
ERC20 token,
uint256 amount
) external requiresAuth {
// Ensure the caller is not trying to steal Vault shares or collateral cTokens.
require(getTotalFeiBoostedForVault[ERC4626(address(token))] == 0 && token != assetTurboCToken, "INVALID_TOKEN");
emit TokenSweeped(msg.sender, to, token, amount);
// Transfer the sweeped tokens to the recipient.
token.safeTransfer(to, amount);
}
/*///////////////////////////////////////////////////////////////
GIB LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when a Safe is gibbed.
/// @param user The user who gibbed the Safe.
/// @param to The recipient of the impounded collateral.
/// @param assetAmount The amount of underling tokens impounded.
event SafeGibbed(address indexed user, address indexed to, uint256 assetAmount);
/// @notice Impound a specific amount of a Safe's collateral.
/// @param to The address to send the impounded collateral to.
/// @param assetAmount The amount of the asset to impound.
/// @dev Debt must be repaid in advance, or the redemption will fail.
function gib(address to, uint256 assetAmount) external nonReentrant requiresMasterAuth {
emit SafeGibbed(msg.sender, to, assetAmount);
// Withdraw the specified amount of assets from the Turbo Fuse Pool.
require(assetTurboCToken.redeemUnderlying(assetAmount) == 0, "REDEEM_FAILED");
// Transfer the assets to the authorized caller.
asset.safeTransfer(to, assetAmount);
}
}
/// @title Turbo Booster
/// @author Transmissions11
/// @notice Boost authorization module.
contract TurboBooster is Auth, ENSReverseRecordAuth {
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Creates a new Turbo Booster contract.
/// @param _owner The owner of the Booster.
/// @param _authority The Authority of the Booster.
constructor(address _owner, Authority _authority) Auth(_owner, _authority) {}
/*///////////////////////////////////////////////////////////////
GLOBAL FREEZE CONFIGURATION
//////////////////////////////////////////////////////////////*/
/// @notice Whether boosting is currently frozen.
bool public frozen;
/// @notice Emitted when boosting is frozen or unfrozen.
/// @param user The user who froze or unfroze boosting.
/// @param frozen Whether boosting is now frozen.
event FreezeStatusUpdated(address indexed user, bool frozen);
/// @notice Sets whether boosting is frozen.
/// @param freeze Whether boosting will be frozen.
function setFreezeStatus(bool freeze) external requiresAuth {
// Update freeze status.
frozen = freeze;
emit FreezeStatusUpdated(msg.sender, freeze);
}
/*///////////////////////////////////////////////////////////////
VAULT BOOST CAP CONFIGURATION
//////////////////////////////////////////////////////////////*/
ERC4626[] public boostableVaults;
/// @notice exposes an array of boostable vaults. Only used for visibility.
function getBoostableVaults() external view returns(ERC4626[] memory) {
return boostableVaults;
}
/// @notice Maps Vaults to the cap on the amount of Fei used to boost them.
mapping(ERC4626 => uint256) public getBoostCapForVault;
/// @notice Emitted when a Vault's boost cap is updated.
/// @param vault The Vault who's boost cap was updated.
/// @param newBoostCap The new boost cap for the Vault.
event BoostCapUpdatedForVault(address indexed user, ERC4626 indexed vault, uint256 newBoostCap);
/// @notice Sets a Vault's boost cap.
/// @param vault The Vault to set the boost cap for.
/// @param newBoostCap The new boost cap for the Vault.
function setBoostCapForVault(ERC4626 vault, uint256 newBoostCap) external requiresAuth {
require(newBoostCap != 0, "cap is zero");
// Add to boostable vaults array
if (getBoostCapForVault[vault] == 0) {
boostableVaults.push(vault);
}
// Update the boost cap for the Vault.
getBoostCapForVault[vault] = newBoostCap;
emit BoostCapUpdatedForVault(msg.sender, vault, newBoostCap);
}
/*///////////////////////////////////////////////////////////////
COLLATERAL BOOST CAP CONFIGURATION
//////////////////////////////////////////////////////////////*/
/// @notice Maps collateral types to the cap on the amount of Fei boosted against them.
mapping(ERC20 => uint256) public getBoostCapForCollateral;
/// @notice Emitted when a collateral type's boost cap is updated.
/// @param collateral The collateral type who's boost cap was updated.
/// @param newBoostCap The new boost cap for the collateral type.
event BoostCapUpdatedForCollateral(address indexed user, ERC20 indexed collateral, uint256 newBoostCap);
/// @notice Sets a collateral type's boost cap.
/// @param collateral The collateral type to set the boost cap for.
/// @param newBoostCap The new boost cap for the collateral type.
function setBoostCapForCollateral(ERC20 collateral, uint256 newBoostCap) external requiresAuth {
// Update the boost cap for the collateral type.
getBoostCapForCollateral[collateral] = newBoostCap;
emit BoostCapUpdatedForCollateral(msg.sender, collateral, newBoostCap);
}
/*///////////////////////////////////////////////////////////////
AUTHORIZATION LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Returns whether a Safe is authorized to boost a Vault.
/// @param safe The Safe to check is authorized to boost the Vault.
/// @param collateral The collateral/asset of the Safe.
/// @param vault The Vault to check the Safe is authorized to boost.
/// @param feiAmount The amount of Fei asset to check the Safe is authorized boost the Vault with.
/// @param newTotalBoostedForVault The total amount of Fei that will boosted to the Vault after boost (if it is not rejected).
/// @param newTotalBoostedAgainstCollateral The total amount of Fei that will be boosted against the Safe's collateral type after this boost.
/// @return Whether the Safe is authorized to boost the Vault with the given amount of Fei asset.
function canSafeBoostVault(
TurboSafe safe,
ERC20 collateral,
ERC4626 vault,
uint256 feiAmount,
uint256 newTotalBoostedForVault,
uint256 newTotalBoostedAgainstCollateral
) external view returns (bool) {
return
!frozen &&
getBoostCapForVault[vault] >= newTotalBoostedForVault &&
getBoostCapForCollateral[collateral] >= newTotalBoostedAgainstCollateral;
}
}
/**
@title Turbo Admin of Turbo Fuse Pool and Turbo Timelock
*/
contract TurboAdmin is Auth, ENSReverseRecordAuth {
/// @notice generic error thrown when comptroller call fails
error ComptrollerError();
/// @notice the fuse comptroller associated with the TurboAdmin
Comptroller public immutable comptroller;
/// @notice the turbo timelock
TimelockController public immutable timelock;
/// @notice constant zero interest rate model
address public constant ZERO_IRM = 0xC9dB5A1034BcBcca3f59dD61dbeE31b78CeFD126;
/// @notice cToken implementation
address public constant CTOKEN_IMPL = 0x67Db14E73C2Dce786B5bbBfa4D010dEab4BBFCF9;
/// @param _comptroller the fuse comptroller
constructor(Comptroller _comptroller, TimelockController _timelock, Authority _authority) Auth(address(0), _authority) {
comptroller = _comptroller;
timelock = _timelock;
}
// ************ TURBO ADMIN FUNCTIONS ************
function addCollateral(
address underlying,
string calldata name,
string calldata symbol,
uint256 collateralFactorMantissa,
uint256 supplyCap
) external requiresAuth {
bytes memory constructorData = abi.encode(
underlying,
address(comptroller),
ZERO_IRM,
name,
symbol,
CTOKEN_IMPL,
new bytes(0),
0, // zero admin fee
0 // zero reserve factor
);
if (
comptroller._deployMarket(
false,
constructorData,
collateralFactorMantissa
) != 0
) revert ComptrollerError();
// set borrow paused
CERC20 cToken = comptroller.cTokensByUnderlying(ERC20(underlying));
_setBorrowPausedInternal(cToken, true);
CERC20[] memory markets = new CERC20[](1);
markets[0] = cToken;
uint256[] memory caps = new uint256[](1);
caps[0] = supplyCap;
comptroller._setMarketSupplyCaps(markets, caps);
}
// ************ BORROW GUARDIAN FUNCTIONS ************
/**
* @notice Set the given supply caps for the given cToken markets. Supplying that brings total underlying supply to or above supply cap will revert.
* @dev Admin or borrowCapGuardian function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying.
* @param cTokens The addresses of the markets (tokens) to change the supply caps for
* @param newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying.
*/
function _setMarketSupplyCaps(
CERC20[] memory cTokens,
uint256[] calldata newSupplyCaps
) external requiresAuth {
_setMarketSupplyCapsInternal(cTokens, newSupplyCaps);
}
function _setMarketSupplyCapsByUnderlying(
address[] calldata underlyings,
uint256[] calldata newSupplyCaps
) external requiresAuth {
_setMarketSupplyCapsInternal(
_underlyingToCTokens(underlyings),
newSupplyCaps
);
}
function _setMarketSupplyCapsInternal(
CERC20[] memory cTokens,
uint256[] calldata newSupplyCaps
) internal {
comptroller._setMarketSupplyCaps(cTokens, newSupplyCaps);
}
function _underlyingToCTokens(address[] calldata underlyings)
internal
view
returns (CERC20[] memory)
{
CERC20[] memory cTokens = new CERC20[](underlyings.length);
for (uint256 i = 0; i < underlyings.length; i++) {
CERC20 cToken = comptroller.cTokensByUnderlying(ERC20(underlyings[i]));
require(address(cToken) != address(0), "cToken doesn't exist");
cTokens[i] = CERC20(cToken);
}
return cTokens;
}
/**
* @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param cTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(
CERC20[] memory cTokens,
uint256[] calldata newBorrowCaps
) external requiresAuth {
_setMarketBorrowCapsInternal(cTokens, newBorrowCaps);
}
function _setMarketBorrowCapsInternal(
CERC20[] memory cTokens,
uint256[] calldata newBorrowCaps
) internal {
comptroller._setMarketBorrowCaps(cTokens, newBorrowCaps);
}
function _setMarketBorrowCapsByUnderlying(
address[] calldata underlyings,
uint256[] calldata newBorrowCaps
) external requiresAuth {
_setMarketBorrowCapsInternal(
_underlyingToCTokens(underlyings),
newBorrowCaps
);
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian)
external
requiresAuth
{
comptroller._setBorrowCapGuardian(newBorrowCapGuardian);
}
// ************ PAUSE GUARDIAN FUNCTIONS ************
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian)
external
requiresAuth
returns (uint256)
{
return comptroller._setPauseGuardian(newPauseGuardian);
}
function _setMintPausedByUnderlying(ERC20 underlying, bool state)
external
requiresAuth
returns (bool)
{
CERC20 cToken = comptroller.cTokensByUnderlying(underlying);
require(address(cToken) != address(0), "cToken doesn't exist");
return _setMintPausedInternal(cToken, state);
}
function _setMintPaused(CERC20 cToken, bool state)
external
requiresAuth
returns (bool)
{
return _setMintPausedInternal(cToken, state);
}
function _setMintPausedInternal(CERC20 cToken, bool state)
internal
returns (bool)
{
return comptroller._setMintPaused(cToken, state);
}
function _setBorrowPausedByUnderlying(ERC20 underlying, bool state)
external
requiresAuth
returns (bool)
{
CERC20 cToken = comptroller.cTokensByUnderlying(underlying);
require(address(cToken) != address(0), "cToken doesn't exist");
return _setBorrowPausedInternal(cToken, state);
}
function _setBorrowPausedInternal(CERC20 cToken, bool state)
internal
returns (bool)
{
return comptroller._setBorrowPaused(cToken, state);
}
function _setBorrowPaused(CERC20 cToken, bool state)
external
requiresAuth
returns (bool)
{
return _setBorrowPausedInternal(CERC20(cToken), state);
}
function _setTransferPaused(bool state)
external
requiresAuth
returns (bool)
{
return comptroller._setTransferPaused(state);
}
function _setSeizePaused(bool state)
external
requiresAuth
returns (bool)
{
return comptroller._setSeizePaused(state);
}
// ************ FUSE ADMIN FUNCTIONS ************
function oracleAdd(
address[] calldata underlyings,
address[] calldata _oracles
) external requiresAuth {
comptroller.oracle().add(underlyings, _oracles);
}
function oracleChangeAdmin(address newAdmin) external requiresAuth {
comptroller.oracle().changeAdmin(newAdmin);
}
function _addRewardsDistributor(address distributor)
external
requiresAuth
{
if (comptroller._addRewardsDistributor(distributor) != 0)
revert ComptrollerError();
}
function _setWhitelistEnforcement(bool enforce)
external
requiresAuth
{
if (comptroller._setWhitelistEnforcement(enforce) != 0)
revert ComptrollerError();
}
function _setWhitelistStatuses(
address[] calldata suppliers,
bool[] calldata statuses
) external requiresAuth {
if (comptroller._setWhitelistStatuses(suppliers, statuses) != 0)
revert ComptrollerError();
}
function _setPriceOracle(address newOracle) public requiresAuth {
if (comptroller._setPriceOracle(newOracle) != 0)
revert ComptrollerError();
}
function _setCloseFactor(uint256 newCloseFactorMantissa)
external
requiresAuth
{
if (comptroller._setCloseFactor(newCloseFactorMantissa) != 0)
revert ComptrollerError();
}
function _setCollateralFactor(
CERC20 cToken,
uint256 newCollateralFactorMantissa
) public requiresAuth {
if (
comptroller._setCollateralFactor(
cToken,
newCollateralFactorMantissa
) != 0
) revert ComptrollerError();
}
function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa)
external
requiresAuth
{
if (
comptroller._setLiquidationIncentive(
newLiquidationIncentiveMantissa
) != 0
) revert ComptrollerError();
}
function _deployMarket(
address underlying,
address irm,
string calldata name,
string calldata symbol,
address impl,
bytes calldata data,
uint256 reserveFactor,
uint256 adminFee,
uint256 collateralFactorMantissa
) external requiresAuth {
bytes memory constructorData = abi.encode(
underlying,
address(comptroller),
irm,
name,
symbol,
impl,
data,
reserveFactor,
adminFee
);
if (
comptroller._deployMarket(
false,
constructorData,
collateralFactorMantissa
) != 0
) revert ComptrollerError();
}
function _unsupportMarket(CERC20 cToken) external requiresAuth {
if (comptroller._unsupportMarket(cToken) != 0)
revert ComptrollerError();
}
function _toggleAutoImplementations(bool enabled)
public
requiresAuth
{
if (comptroller._toggleAutoImplementations(enabled) != 0)
revert ComptrollerError();
}
function scheduleSetPendingAdmin(address newPendingAdmin) public requiresAuth {
_schedule(address(this), abi.encodeWithSelector(this._setPendingAdmin.selector, newPendingAdmin));
}
function _setPendingAdmin(address newPendingAdmin)
public
{
require(msg.sender == address(timelock), "timelock");
if (comptroller._setPendingAdmin(newPendingAdmin) != 0)
revert ComptrollerError();
}
function _acceptAdmin() public {
if (comptroller._acceptAdmin() != 0) revert ComptrollerError();
}
// ************ TIMELOCK ADMIN FUNCTIONS ************
function schedule(address target, bytes memory data) public requiresAuth {
_schedule(target, data);
}
function _schedule(address target, bytes memory data) internal {
timelock.schedule(target, 0, data, bytes32(0), keccak256(abi.encodePacked(block.timestamp)), 15 days);
}
function cancel(bytes32 id) public requiresAuth {
timelock.cancel(id);
}
function execute(address target, bytes memory data, bytes32 salt) public requiresAuth {
timelock.execute(target, 0, data, bytes32(0), salt);
}
}
/// @title Fei
/// @author Fei Protocol
/// @notice Minimal interface for the Fei token.
abstract contract Fei is ERC20 {
function mint(address to, uint256 amount) external virtual;
}
/// @title Turbo Gibber
/// @author Transmissions11
/// @notice Atomic impounder module.
contract TurboGibber is Auth, ReentrancyGuard, ENSReverseRecordAuth {
using SafeTransferLib for Fei;
/*///////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
/// @notice The Master contract.
/// @dev Used to validate Safes are legitimate.
TurboMaster public immutable master;
/// @notice The Fei token on the network.
Fei public immutable fei;
/// @notice The Fei cToken in the Turbo Fuse Pool.
CERC20 public immutable feiTurboCToken;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Creates a new Turbo Gibber contract.
/// @param _master The Master of the Gibber.
/// @param _owner The owner of the Gibber.
/// @param _authority The Authority of the Gibber.
constructor(
TurboMaster _master,
address _owner,
Authority _authority
) Auth(_owner, _authority) {
master = _master;
fei = Fei(address(master.fei()));
feiTurboCToken = master.pool().cTokensByUnderlying(fei);
// Preemptively approve to the Fei cToken in the Turbo Fuse Pool.
fei.safeApprove(address(feiTurboCToken), type(uint256).max);
}
/*///////////////////////////////////////////////////////////////
ATOMIC IMPOUND LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted an impound is executed.
/// @param user The user who executed the impound.
/// @param safe The Safe that was impounded.
/// @param feiAmount The amount of Fei that was repaid.
/// @param assetAmount The amount of assets impounded.
event ImpoundExecuted(address indexed user, TurboSafe indexed safe, uint256 feiAmount, uint256 assetAmount);
/// @notice Impound a safe.
/// @param safe The Safe to be impounded.
/// @param feiAmount The amount of Fei to repay the Safe's debt with.
/// @param assetAmount The amount of assets to impound.
/// @param to The recipient of the impounded collateral tokens.
function impound(
TurboSafe safe,
uint256 feiAmount,
uint256 assetAmount,
address to
) external requiresAuth nonReentrant {
// Ensure the Safe is registered with the Master.
require(master.getSafeId(safe) != 0);
emit ImpoundExecuted(msg.sender, safe, feiAmount, assetAmount);
// Mint the Fei amount requested.
fei.mint(address(this), feiAmount);
// Repay the safe's Fei debt with the minted Fei, ensuring to catch cToken errors.
require(feiTurboCToken.repayBorrowBehalf(address(safe), feiAmount) == 0, "REPAY_FAILED");
// Impound some of the safe's collateral and send it to the chosen recipient.
safe.gib(to, assetAmount);
}
/// @notice Impound all of a safe's collateral.
/// @param safe The Safe to be impounded.
/// @param to The recipient of the impounded collateral tokens.
function impoundAll(TurboSafe safe, address to) external requiresAuth nonReentrant {
// Ensure the Safe is registered with the Master.
require(master.getSafeId(safe) != 0);
// Get the asset cToken in the Turbo Fuse Pool.
CERC20 assetTurboCToken = safe.assetTurboCToken();
// Get the amount of assets to impound from the Safe.
uint256 assetAmount = assetTurboCToken.balanceOfUnderlying(address(safe));
// Get the amount of Fei debt to repay for the Safe.
uint256 feiAmount = feiTurboCToken.borrowBalanceCurrent(address(safe));
emit ImpoundExecuted(msg.sender, safe, feiAmount, assetAmount);
// Mint the Fei amount requested.
fei.mint(address(this), feiAmount);
// Repay the safe's Fei debt with the minted Fei, ensuring to catch cToken errors.
require(feiTurboCToken.repayBorrowBehalf(address(safe), feiAmount) == 0, "REPAY_FAILED");
// Impound all of the safe's collateral and send it to the chosen recipient.
safe.gib(to, assetAmount);
}
}
/// @title Turbo Savior
/// @author Transmissions11
/// @notice Safe repayment module.
contract TurboSavior is Auth, ReentrancyGuard, ENSReverseRecordAuth {
using FixedPointMathLib for uint256;
/*///////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
/// @notice The Master contract.
/// @dev Used to validate Safes are legitimate.
TurboMaster public immutable master;
/// @notice The Fei token on the network.
Fei public immutable fei;
/// @notice The Turbo Fuse Pool used by the Master.
Comptroller public immutable pool;
/// @notice The Fei cToken in the Turbo Fuse Pool.
CERC20 public immutable feiTurboCToken;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Creates a new Turbo Savior contract.
/// @param _master The Master of the Savior.
/// @param _owner The owner of the Savior.
/// @param _authority The Authority of the Savior.
constructor(
TurboMaster _master,
address _owner,
Authority _authority
) Auth(_owner, _authority) {
master = _master;
fei = Fei(address(master.fei()));
pool = master.pool();
feiTurboCToken = pool.cTokensByUnderlying(fei);
}
/*///////////////////////////////////////////////////////////////
LINE LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice The minimum percentage debt must make up of the borrow limit for a Safe to be saved.
/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
uint256 public minDebtPercentageForSaving;
/// @notice Emitted when the minimum debt percentage for saving is updated.
/// @param newDefaultFeePercentage The new minimum debt percentage for saving.
event MinDebtPercentageForSavingUpdated(address indexed user, uint256 newDefaultFeePercentage);
/// @notice Sets the minimum debt percentage.
/// @param newMinDebtPercentageForSaving The new minimum debt percentage.
function setMinDebtPercentageForSaving(uint256 newMinDebtPercentageForSaving) external requiresAuth {
// A minimum debt percentage over 100% makes no sense.
require(newMinDebtPercentageForSaving <= 1e18, "PERCENT_TOO_HIGH");
// Update the minimum debt percentage.
minDebtPercentageForSaving = newMinDebtPercentageForSaving;
emit MinDebtPercentageForSavingUpdated(msg.sender, newMinDebtPercentageForSaving);
}
/*///////////////////////////////////////////////////////////////
SAVE LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted a save is executed.
/// @param user The user who executed the save.
/// @param safe The Safe that was saved.
/// @param vault The Vault that was lessed.
/// @param feiAmount The amount of Fei that was lessed.
event SafeSaved(address indexed user, TurboSafe indexed safe, ERC4626 indexed vault, uint256 feiAmount);
/// @notice Save a Safe (call less on owner's behalf to prevent liquidation).
/// @param safe The Safe to be saved.
/// @param vault The Vault to less from.
/// @param feiAmount The amount of Fei to less from the Safe.
function save(
TurboSafe safe,
ERC4626 vault,
uint256 feiAmount
) external requiresAuth nonReentrant {
// Ensure the Safe is registered with the Master.
require(master.getSafeId(safe) != 0);
emit SafeSaved(msg.sender, safe, vault, feiAmount);
// Cache the Safe's collateral asset.
CERC20 assetTurboCToken = safe.assetTurboCToken();
// Cache the pool's current oracle.
PriceFeed oracle = pool.oracle();
// Get the Safe's asset's collateral factor in the Turbo Fuse Pool.
(, uint256 collateralFactor) = pool.markets(assetTurboCToken);
// Compute the value of the Safe's collateral. Rounded down to favor saving.
uint256 borrowLimit = assetTurboCToken
.balanceOf(address(safe))
.mulWadDown(assetTurboCToken.exchangeRateStored())
.mulWadDown(collateralFactor)
.mulWadDown(oracle.getUnderlyingPrice(assetTurboCToken));
// Compute the value of the Safe's debt. Rounding up to favor saving them.
uint256 debtValue = feiTurboCToken.borrowBalanceCurrent(address(safe)).mulWadUp(
oracle.getUnderlyingPrice(feiTurboCToken)
);
// Ensure the Safe's debt percentage is high enough to justify saving, otherwise revert.
require(
borrowLimit != 0 && debtValue.divWadUp(borrowLimit) >= minDebtPercentageForSaving,
"DEBT_PERCENT_TOO_LOW"
);
// Less the Fei from the Safe.
safe.less(vault, feiAmount);
}
}
/// @title ERC4626 interface
/// @author Fei Protocol
/// See: https://eips.ethereum.org/EIPS/eip-4626
abstract contract IERC4626 is ERC20 {
/*////////////////////////////////////////////////////////
Events
////////////////////////////////////////////////////////*/
/// @notice `sender` has exchanged `assets` for `shares`,
/// and transferred those `shares` to `receiver`.
event Deposit(
address indexed sender,
address indexed receiver,
uint256 assets,
uint256 shares
);
/// @notice `sender` has exchanged `shares` for `assets`,
/// and transferred those `assets` to `receiver`.
event Withdraw(
address indexed sender,
address indexed receiver,
uint256 assets,
uint256 shares
);
/*////////////////////////////////////////////////////////
Vault properties
////////////////////////////////////////////////////////*/
/// @notice The address of the underlying ERC20 token used for
/// the Vault for accounting, depositing, and withdrawing.
function asset() external view virtual returns(address asset);
/// @notice Total amount of the underlying asset that
/// is "managed" by Vault.
function totalAssets() external view virtual returns(uint256 totalAssets);
/*////////////////////////////////////////////////////////
Deposit/Withdrawal Logic
////////////////////////////////////////////////////////*/
/// @notice Mints `shares` Vault shares to `receiver` by
/// depositing exactly `assets` of underlying tokens.
function deposit(uint256 assets, address receiver) external virtual returns(uint256 shares);
/// @notice Mints exactly `shares` Vault shares to `receiver`
/// by depositing `assets` of underlying tokens.
function mint(uint256 shares, address receiver) external virtual returns(uint256 assets);
/// @notice Redeems `shares` from `owner` and sends `assets`
/// of underlying tokens to `receiver`.
function withdraw(uint256 assets, address receiver, address owner) external virtual returns(uint256 shares);
/// @notice Redeems `shares` from `owner` and sends `assets`
/// of underlying tokens to `receiver`.
function redeem(uint256 shares, address receiver, address owner) external virtual returns(uint256 assets);
/*////////////////////////////////////////////////////////
Vault Accounting Logic
////////////////////////////////////////////////////////*/
/// @notice The amount of shares that the vault would
/// exchange for the amount of assets provided, in an
/// ideal scenario where all the conditions are met.
function convertToShares(uint256 assets) external view virtual returns(uint256 shares);
/// @notice The amount of assets that the vault would
/// exchange for the amount of shares provided, in an
/// ideal scenario where all the conditions are met.
function convertToAssets(uint256 shares) external view virtual returns(uint256 assets);
/// @notice Total number of underlying assets that can
/// be deposited by `owner` into the Vault, where `owner`
/// corresponds to the input parameter `receiver` of a
/// `deposit` call.
function maxDeposit(address owner) external view virtual returns(uint256 maxAssets);
/// @notice Allows an on-chain or off-chain user to simulate
/// the effects of their deposit at the current block, given
/// current on-chain conditions.
function previewDeposit(uint256 assets) external view virtual returns(uint256 shares);
/// @notice Total number of underlying shares that can be minted
/// for `owner`, where `owner` corresponds to the input
/// parameter `receiver` of a `mint` call.
function maxMint(address owner) external view virtual returns(uint256 maxShares);
/// @notice Allows an on-chain or off-chain user to simulate
/// the effects of their mint at the current block, given
/// current on-chain conditions.
function previewMint(uint256 shares) external view virtual returns(uint256 assets);
/// @notice Total number of underlying assets that can be
/// withdrawn from the Vault by `owner`, where `owner`
/// corresponds to the input parameter of a `withdraw` call.
function maxWithdraw(address owner) external view virtual returns(uint256 maxAssets);
/// @notice Allows an on-chain or off-chain user to simulate
/// the effects of their withdrawal at the current block,
/// given current on-chain conditions.
function previewWithdraw(uint256 assets) external view virtual returns(uint256 shares);
/// @notice Total number of underlying shares that can be
/// redeemed from the Vault by `owner`, where `owner` corresponds
/// to the input parameter of a `redeem` call.
function maxRedeem(address owner) external view virtual returns(uint256 maxShares);
/// @notice Allows an on-chain or off-chain user to simulate
/// the effects of their redeemption at the current block,
/// given current on-chain conditions.
function previewRedeem(uint256 shares) external view virtual returns(uint256 assets);
}
/**
@title ERC4626Router Base Interface
@author joeysantoro
@notice A canonical router between ERC4626 Vaults https://eips.ethereum.org/EIPS/eip-4626
The base router is a multicall style router inspired by Uniswap v3 with built-in features for permit, WETH9 wrap/unwrap, and ERC20 token pulling/sweeping/approving.
It includes methods for the four mutable ERC4626 functions deposit/mint/withdraw/redeem as well.
These can all be arbitrarily composed using the multicall functionality of the router.
NOTE the router is capable of pulling any approved token from your wallet. This is only possible when your address is msg.sender, but regardless be careful when interacting with the router or ERC4626 Vaults.
The router makes no special considerations for unique ERC20 implementations such as fee on transfer.
There are no built in protections for unexpected behavior beyond enforcing the minSharesOut is received.
*/
interface IERC4626RouterBase {
/************************** Errors **************************/
/// @notice thrown when amount of assets received is below the min set by caller
error MinAmountError();
/// @notice thrown when amount of shares received is below the min set by caller
error MinSharesError();
/// @notice thrown when amount of assets received is above the max set by caller
error MaxAmountError();
/// @notice thrown when amount of shares received is above the max set by caller
error MaxSharesError();
/************************** Mint **************************/
/**
@notice mint `shares` from an ERC4626 vault.
@param vault The ERC4626 vault to mint shares from.
@param to The destination of ownership shares.
@param shares The amount of shares to mint from `vault`.
@param maxAmountIn The max amount of assets used to mint.
@return amountIn the amount of assets used to mint by `to`.
@dev throws MaxAmountError
*/
function mint(
IERC4626 vault,
address to,
uint256 shares,
uint256 maxAmountIn
) external payable returns (uint256 amountIn);
/************************** Deposit **************************/
/**
@notice deposit `amount` to an ERC4626 vault.
@param vault The ERC4626 vault to deposit assets to.
@param to The destination of ownership shares.
@param amount The amount of assets to deposit to `vault`.
@param minSharesOut The min amount of `vault` shares received by `to`.
@return sharesOut the amount of shares received by `to`.
@dev throws MinSharesError
*/
function deposit(
IERC4626 vault,
address to,
uint256 amount,
uint256 minSharesOut
) external payable returns (uint256 sharesOut);
/************************** Withdraw **************************/
/**
@notice withdraw `amount` from an ERC4626 vault.
@param vault The ERC4626 vault to withdraw assets from.
@param to The destination of assets.
@param amount The amount of assets to withdraw from vault.
@param minSharesOut The min amount of shares received by `to`.
@return sharesOut the amount of shares received by `to`.
@dev throws MaxSharesError
*/
function withdraw(
IERC4626 vault,
address to,
uint256 amount,
uint256 minSharesOut
) external payable returns (uint256 sharesOut);
/************************** Redeem **************************/
/**
@notice redeem `shares` shares from an ERC4626 vault.
@param vault The ERC4626 vault to redeem shares from.
@param to The destination of assets.
@param shares The amount of shares to redeem from vault.
@param minAmountOut The min amount of assets received by `to`.
@return amountOut the amount of assets received by `to`.
@dev throws MinAmountError
*/
function redeem(
IERC4626 vault,
address to,
uint256 shares,
uint256 minAmountOut
) external payable returns (uint256 amountOut);
}
// forked from https://github.com/Uniswap/v3-periphery/blob/main/contracts/interfaces/ISelfPermit.sol
/// @title Self Permit
/// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route
interface ISelfPermit {
/// @notice Permits this contract to spend a given token from `msg.sender`
/// @dev The `owner` is always msg.sender and the `spender` is always address(this).
/// @param token The address of the token spent
/// @param value The amount that can be spent of token
/// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function selfPermit(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
/// @notice Permits this contract to spend a given token from `msg.sender`
/// @dev The `owner` is always msg.sender and the `spender` is always address(this).
/// Can be used instead of #selfPermit to prevent calls from failing due to a frontrun of a call to #selfPermit
/// @param token The address of the token spent
/// @param value The amount that can be spent of token
/// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function selfPermitIfNecessary(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
/// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter
/// @dev The `owner` is always msg.sender and the `spender` is always address(this)
/// @param token The address of the token spent
/// @param nonce The current nonce of the owner
/// @param expiry The timestamp at which the permit is no longer valid
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function selfPermitAllowed(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
/// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter
/// @dev The `owner` is always msg.sender and the `spender` is always address(this)
/// Can be used instead of #selfPermitAllowed to prevent calls from failing due to a frontrun of a call to #selfPermitAllowed.
/// @param token The address of the token spent
/// @param nonce The current nonce of the owner
/// @param expiry The timestamp at which the permit is no longer valid
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function selfPermitAllowedIfNecessary(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
// forked from https://github.com/Uniswap/v3-periphery/blob/main/contracts/interfaces/external/IERC20PermitAllowed.sol
/// @title Interface for permit
/// @notice Interface used by DAI/CHAI for permit
interface IERC20PermitAllowed {
/// @notice Approve the spender to spend some tokens via the holder signature
/// @dev This is the permit interface used by DAI and CHAI
/// @param holder The address of the token holder, the token owner
/// @param spender The address of the token spender
/// @param nonce The holder's nonce, increases at each call to permit
/// @param expiry The timestamp at which the permit is no longer valid
/// @param allowed Boolean that sets approval amount, true for type(uint256).max and false for 0
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
/// @title Self Permit
/// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route
/// @dev These functions are expected to be embedded in multicalls to allow EOAs to approve a contract and call a function
/// that requires an approval in a single transaction.
abstract contract SelfPermit is ISelfPermit {
/// @inheritdoc ISelfPermit
function selfPermit(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public payable override {
ERC20(token).permit(msg.sender, address(this), value, deadline, v, r, s);
}
/// @inheritdoc ISelfPermit
function selfPermitIfNecessary(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable override {
if (ERC20(token).allowance(msg.sender, address(this)) < value) selfPermit(token, value, deadline, v, r, s);
}
/// @inheritdoc ISelfPermit
function selfPermitAllowed(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public payable override {
IERC20PermitAllowed(token).permit(msg.sender, address(this), nonce, expiry, true, v, r, s);
}
/// @inheritdoc ISelfPermit
function selfPermitAllowedIfNecessary(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external payable override {
if (ERC20(token).allowance(msg.sender, address(this)) < type(uint256).max)
selfPermitAllowed(token, nonce, expiry, v, r, s);
}
}// forked from https://github.com/Uniswap/v3-periphery/blob/main/contracts/base/Multicall.sol
// forked from https://github.com/Uniswap/v3-periphery/blob/main/contracts/interfaces/IMulticall.sol
/// @title Multicall interface
/// @notice Enables calling multiple methods in a single call to the contract
interface IMulticall {
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @dev The `msg.value` should not be trusted for any method callable from multicall.
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
/// @title Multicall
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall is IMulticall {
/// @inheritdoc IMulticall
function multicall(bytes[] calldata data) public payable override returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
// Next 5 lines from https://ethereum.stackexchange.com/a/83577
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}
}/**
@title Periphery Payments
@notice Immutable state used by periphery contracts
Largely Forked from https://github.com/Uniswap/v3-periphery/blob/main/contracts/base/PeripheryPayments.sol
Changes:
* no interface
* no inheritdoc
* add immutable WETH9 in constructor instead of PeripheryImmutableState
* receive from any address
* Solmate interfaces and transfer lib
* casting
* add approve, wrapWETH9 and pullToken
*/
abstract contract PeripheryPayments {
using SafeTransferLib for *;
IWETH9 public immutable WETH9;
constructor(IWETH9 _WETH9) {
WETH9 = _WETH9;
}
receive() external payable {}
function approve(ERC20 token, address to, uint256 amount) public payable {
token.safeApprove(to, amount);
}
function unwrapWETH9(uint256 amountMinimum, address recipient) public payable {
uint256 balanceWETH9 = WETH9.balanceOf(address(this));
require(balanceWETH9 >= amountMinimum, 'Insufficient WETH9');
if (balanceWETH9 > 0) {
WETH9.withdraw(balanceWETH9);
recipient.safeTransferETH(balanceWETH9);
}
}
function wrapWETH9() public payable {
if (address(this).balance > 0) WETH9.deposit{value: address(this).balance}(); // wrap everything
}
function pullToken(ERC20 token, uint256 amount, address recipient) public payable {
token.safeTransferFrom(msg.sender, recipient, amount);
}
function sweepToken(
ERC20 token,
uint256 amountMinimum,
address recipient
) public payable {
uint256 balanceToken = token.balanceOf(address(this));
require(balanceToken >= amountMinimum, 'Insufficient token');
if (balanceToken > 0) {
token.safeTransfer(recipient, balanceToken);
}
}
function refundETH() external payable {
if (address(this).balance > 0) SafeTransferLib.safeTransferETH(msg.sender, address(this).balance);
}
}
abstract contract IWETH9 is ERC20 {
/// @notice Deposit ether to get wrapped ether
function deposit() external payable virtual;
/// @notice Withdraw wrapped ether to get ether
function withdraw(uint256) external virtual;
}
/// @title ERC4626 Router Base Contract
/// @author joeysantoro
abstract contract ERC4626RouterBase is IERC4626RouterBase, SelfPermit, Multicall, PeripheryPayments {
using SafeTransferLib for ERC20;
/// @inheritdoc IERC4626RouterBase
function mint(
IERC4626 vault,
address to,
uint256 shares,
uint256 maxAmountIn
) public payable virtual override returns (uint256 amountIn) {
if ((amountIn = vault.mint(shares, to)) > maxAmountIn) {
revert MaxAmountError();
}
}
/// @inheritdoc IERC4626RouterBase
function deposit(
IERC4626 vault,
address to,
uint256 amount,
uint256 minSharesOut
) public payable virtual override returns (uint256 sharesOut) {
if ((sharesOut = vault.deposit(amount, to)) < minSharesOut) {
revert MinSharesError();
}
}
/// @inheritdoc IERC4626RouterBase
function withdraw(
IERC4626 vault,
address to,
uint256 amount,
uint256 maxSharesOut
) public payable virtual override returns (uint256 sharesOut) {
if ((sharesOut = vault.withdraw(amount, to, msg.sender)) > maxSharesOut) {
revert MaxSharesError();
}
}
/// @inheritdoc IERC4626RouterBase
function redeem(
IERC4626 vault,
address to,
uint256 shares,
uint256 minAmountOut
) public payable virtual override returns (uint256 amountOut) {
if ((amountOut = vault.redeem(shares, to, msg.sender)) < minAmountOut) {
revert MinAmountError();
}
}
}
/**
@title a router which can perform multiple Turbo actions between Master and the Safes
@notice routes custom users flows between actions on the master and safes.
Extends the ERC4626RouterBase to allow for flexible combinations of actions involving ERC4626 and permit, weth, and Turbo specific actions.
Safe Creation has functions bundled with deposit (and optionally boost) because a newly created Safe address can only be known at runtime.
The caller is always atomically given the owner role of a new safe.
Authentication requires the caller to be the owner of the Safe to perform any ERC4626 method or TurboSafe requiresAuth method.
Assumes the Safe's authority gives permission to call these functions to the TurboRouter.
*/
contract TurboRouter is ERC4626RouterBase, ENSReverseRecordAuth {
using SafeTransferLib for ERC20;
TurboMaster public immutable master;
constructor (TurboMaster _master, address _owner, Authority _authority, IWETH9 weth) Auth(_owner, _authority) PeripheryPayments(weth) {
master = _master;
}
modifier authenticate(address target) {
require(msg.sender == Auth(target).owner() || Auth(target).authority().canCall(msg.sender, target, msg.sig), "NOT_AUTHED");
_;
}
function createSafe(ERC20 underlying) external returns (TurboSafe safe) {
(safe, ) = master.createSafe(underlying);
safe.setOwner(msg.sender);
}
function createSafeAndDeposit(ERC20 underlying, address to, uint256 amount, uint256 minSharesOut) external returns (TurboSafe safe) {
(safe, ) = master.createSafe(underlying);
// approve max from router to save depositor gas in future.
approve(underlying, address(safe), type(uint256).max);
super.deposit(IERC4626(address(safe)), to, amount, minSharesOut);
safe.setOwner(msg.sender);
}
function createSafeAndDepositAndBoost(
ERC20 underlying,
address to,
uint256 amount,
uint256 minSharesOut,
ERC4626 boostedVault,
uint256 boostedFeiAmount
) public returns (TurboSafe safe) {
(safe, ) = master.createSafe(underlying);
// approve max from router to save depositor gas in future.
approve(underlying, address(safe), type(uint256).max);
super.deposit(IERC4626(address(safe)), to, amount, minSharesOut);
safe.boost(boostedVault, boostedFeiAmount);
safe.setOwner(msg.sender);
}
function createSafeAndDepositAndBoostMany(
ERC20 underlying,
address to,
uint256 amount,
uint256 minSharesOut,
ERC4626[] calldata boostedVaults,
uint256[] calldata boostedFeiAmounts
) public returns (TurboSafe safe) {
(safe, ) = master.createSafe(underlying);
// approve max from router to save depositor gas in future.
approve(underlying, address(safe), type(uint256).max);
super.deposit(IERC4626(address(safe)), to, amount, minSharesOut);
unchecked {
require(boostedVaults.length == boostedFeiAmounts.length, "length");
for (uint256 i = 0; i < boostedVaults.length; i++) {
safe.boost(boostedVaults[i], boostedFeiAmounts[i]);
}
}
safe.setOwner(msg.sender);
}
function deposit(IERC4626 safe, address to, uint256 amount, uint256 minSharesOut)
public
payable
override
authenticate(address(safe))
returns (uint256)
{
return super.deposit(safe, to, amount, minSharesOut);
}
function mint(IERC4626 safe, address to, uint256 shares, uint256 maxAmountIn)
public
payable
override
authenticate(address(safe))
returns (uint256)
{
return super.mint(safe, to, shares, maxAmountIn);
}
function withdraw(IERC4626 safe, address to, uint256 amount, uint256 maxSharesOut)
public
payable
override
authenticate(address(safe))
returns (uint256)
{
return super.withdraw(safe, to, amount, maxSharesOut);
}
function redeem(IERC4626 safe, address to, uint256 shares, uint256 minAmountOut)
public
payable
override
authenticate(address(safe))
returns (uint256)
{
return super.redeem(safe, to, shares, minAmountOut);
}
function slurp(TurboSafe safe, ERC4626 vault) external authenticate(address(safe)) {
safe.slurp(vault);
}
function boost(TurboSafe safe, ERC4626 vault, uint256 feiAmount) public authenticate(address(safe)) {
safe.boost(vault, feiAmount);
}
function less(TurboSafe safe, ERC4626 vault, uint256 feiAmount) external authenticate(address(safe)) {
safe.less(vault, feiAmount);
}
function lessAll(TurboSafe safe, ERC4626 vault) external authenticate(address(safe)) {
safe.less(vault, vault.maxWithdraw(address(safe)));
}
function sweep(TurboSafe safe, address to, ERC20 token, uint256 amount) external authenticate(address(safe)) {
safe.sweep(to, token, amount);
}
function sweepAll(TurboSafe safe, address to, ERC20 token) external authenticate(address(safe)) {
safe.sweep(to, token, token.balanceOf(address(safe)));
}
function slurpAndLessAll(TurboSafe safe, ERC4626 vault) external authenticate(address(safe)) {
safe.slurp(vault);
safe.less(vault, vault.maxWithdraw(address(safe)));
}
}
/**
@title Turbo Configurer
IS INTENDED FOR MAINNET DEPLOYMENT
This contract is a helper utility to completely configure the turbo system, assuming the contracts are deployed.
The deployment should follow the logic in Deployer.sol.
Each function details its access control assumptions.
*/
contract Configurer {
/// @notice Fei DAO Timelock, to be granted TURBO_ADMIN_ROLE and GOVERN_ROLE
address constant feiDAOTimelock = 0xd51dbA7a94e1adEa403553A8235C302cEbF41a3c;
/// @notice Tribe Guardian, to be granted GUARDIAN_ROLE
address constant guardian = 0xB8f482539F2d3Ae2C9ea6076894df36D1f632775;
ERC20 fei = ERC20(0x956F47F50A910163D8BF957Cf5846D573E7f87CA);
ERC20 tribe = ERC20(0xc7283b66Eb1EB5FB86327f08e1B5816b0720212B);
/******************** ROLES ********************/
/// @notice HIGH CLEARANCE. capable of calling `gib` to impound collateral.
uint8 public constant GIBBER_ROLE = 1;
/// @notice HIGH CLEARANCE. Optional module which can interact with any user's vault by default.
uint8 public constant ROUTER_ROLE = 2;
/// @notice Capable of lessing any vault. Exposed on optional TurboSavior module.
uint8 public constant SAVIOR_ROLE = 3;
/// @notice Operational admin of Turbo, can whitelist collaterals, strategies, and configure most parameters.
uint8 public constant TURBO_ADMIN_ROLE = 4;
/// @notice Pause and security Guardian role
uint8 public constant GUARDIAN_ROLE = 5;
/// @notice HIGH CLEARANCE. Capable of critical governance functionality on TurboAdmin such as oracle upgrades.
uint8 public constant GOVERN_ROLE = 6;
/// @notice limited version of TURBO_ADMIN_ROLE which can manage collateral and vault parameters.
uint8 public constant TURBO_STRATEGIST_ROLE = 7;
/******************** CONFIGURATION ********************/
/// @notice configure the turbo timelock. Requires TIMELOCK_ADMIN_ROLE over timelock.
function configureTimelock(TimelockController turboTimelock, TurboAdmin admin) public {
turboTimelock.grantRole(turboTimelock.TIMELOCK_ADMIN_ROLE(), address(admin));
turboTimelock.grantRole(turboTimelock.EXECUTOR_ROLE(), address(admin));
turboTimelock.grantRole(turboTimelock.PROPOSER_ROLE(), address(admin));
turboTimelock.revokeRole(turboTimelock.TIMELOCK_ADMIN_ROLE(), address(this));
}
/// @notice configure the turbo authority. Requires ownership over turbo authority.
function configureAuthority(MultiRolesAuthority turboAuthority) public {
// GIBBER_ROLE
turboAuthority.setRoleCapability(GIBBER_ROLE, TurboSafe.gib.selector, true);
// TURBO_ADMIN_ROLE
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboSafe.slurp.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboSafe.less.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboMaster.createSafe.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboMaster.setBooster.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboMaster.setClerk.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboMaster.setDefaultSafeAuthority.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboMaster.sweep.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboClerk.setDefaultFeePercentage.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboClerk.setCustomFeePercentageForCollateral.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboClerk.setCustomFeePercentageForSafe.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboBooster.setFreezeStatus.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboBooster.setBoostCapForVault.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboBooster.setBoostCapForCollateral.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboSavior.setMinDebtPercentageForSaving.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setMarketSupplyCaps.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setMarketSupplyCapsByUnderlying.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setMarketBorrowCaps.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setMarketBorrowCapsByUnderlying.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setMintPausedByUnderlying.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setMintPaused.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setBorrowPausedByUnderlying.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setBorrowPaused.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin.oracleAdd.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin.addCollateral.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._deployMarket.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._addRewardsDistributor.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setWhitelistStatuses.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setCloseFactor.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setCollateralFactor.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setLiquidationIncentive.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin.schedule.selector, true);
// GUARDIAN_ROLE
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboSafe.less.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboBooster.setFreezeStatus.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setMarketSupplyCaps.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setMarketSupplyCapsByUnderlying.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setMarketBorrowCaps.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setMarketBorrowCapsByUnderlying.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setMintPausedByUnderlying.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setMintPaused.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setBorrowPausedByUnderlying.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setBorrowPaused.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setTransferPaused.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setSeizePaused.selector, true);
// GOVERN_ROLE
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin._setBorrowCapGuardian.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin._setPauseGuardian.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin.oracleChangeAdmin.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin._setWhitelistEnforcement.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin._setPriceOracle.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin._unsupportMarket.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin._toggleAutoImplementations.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin.scheduleSetPendingAdmin.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin.schedule.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin.cancel.selector, true);
turboAuthority.setPublicCapability(TurboAdmin.execute.selector, true);
// TURBO_STRATEGIST_ROLE
turboAuthority.setRoleCapability(TURBO_STRATEGIST_ROLE, TurboAdmin.addCollateral.selector, true);
turboAuthority.setRoleCapability(TURBO_STRATEGIST_ROLE, TurboAdmin._setMarketSupplyCaps.selector, true);
turboAuthority.setRoleCapability(TURBO_STRATEGIST_ROLE, TurboAdmin._setMarketSupplyCapsByUnderlying.selector, true);
turboAuthority.setRoleCapability(TURBO_STRATEGIST_ROLE, TurboBooster.setBoostCapForVault.selector, true);
turboAuthority.setRoleCapability(TURBO_STRATEGIST_ROLE, TurboBooster.setBoostCapForCollateral.selector, true);
turboAuthority.setPublicCapability(TurboSavior.save.selector, true);
}
/// @notice configure the default authority. Requires ownership over default authority.
function configureDefaultAuthority(MultiRolesAuthority defaultAuthority) public {
// ROUTER_ROLE
defaultAuthority.setRoleCapability(ROUTER_ROLE, TurboSafe.boost.selector, true);
defaultAuthority.setRoleCapability(ROUTER_ROLE, TurboSafe.less.selector, true);
defaultAuthority.setRoleCapability(ROUTER_ROLE, TurboSafe.slurp.selector, true);
defaultAuthority.setRoleCapability(ROUTER_ROLE, TurboSafe.sweep.selector, true);
defaultAuthority.setRoleCapability(ROUTER_ROLE, ERC4626.deposit.selector, true);
defaultAuthority.setRoleCapability(ROUTER_ROLE, ERC4626.mint.selector, true);
defaultAuthority.setRoleCapability(ROUTER_ROLE, ERC4626.withdraw.selector, true);
defaultAuthority.setRoleCapability(ROUTER_ROLE, ERC4626.redeem.selector, true);
// SAVIOR_ROLE
defaultAuthority.setRoleCapability(SAVIOR_ROLE, TurboSafe.less.selector, true);
}
/// @notice configure the turbo pool through turboAdmin. TurboAdmin requires pool ownership, and Configurer requires TURBO_ADMIN_ROLE.
function configurePool(TurboAdmin turboAdmin, TurboBooster booster) public {
turboAdmin._deployMarket(
address(fei),
turboAdmin.ZERO_IRM(),
"Turbo Fei",
"fFEI",
turboAdmin.CTOKEN_IMPL(),
new bytes(0),
0,
0,
0
);
turboAdmin.addCollateral(
address(tribe),
"Turbo Tribe",
"fTRIBE",
60e16,
50_000_000e18
);
booster.setBoostCapForCollateral(tribe, 2_000_000e18); // 1M boost cap TRIBE
address[] memory users = new address[](1);
users[0] = feiDAOTimelock;
bool[] memory enabled = new bool[](1);
enabled[0] = true;
turboAdmin._setWhitelistStatuses(users, enabled);
}
/// @notice requires TURBO_ADMIN_ROLE.
function configureClerk(TurboClerk clerk) public {
clerk.setDefaultFeePercentage(75e16); // 75% default revenue split
}
/// @notice requires TURBO_ADMIN_ROLE.
function configureSavior(TurboSavior savior) public {
savior.setMinDebtPercentageForSaving(80e16); // 80%
}
/// @notice requires ownership of Turbo Authority and default authority.
function configureRoles(
MultiRolesAuthority turboAuthority,
MultiRolesAuthority defaultAuthority,
TurboRouter router,
TurboSavior savior,
TurboGibber gibber
) public {
defaultAuthority.setUserRole(address(router), ROUTER_ROLE, true);
defaultAuthority.setUserRole(address(savior), SAVIOR_ROLE, true);
turboAuthority.setUserRole(address(gibber), GIBBER_ROLE, true);
}
/// @notice requires TURBO_ADMIN_ROLE and ownership over Turbo Authority.
function configureMaster(
TurboMaster master,
TurboClerk clerk,
TurboBooster booster,
TurboAdmin admin,
MultiRolesAuthority defaultAuthority
) public {
MultiRolesAuthority turboAuthority = MultiRolesAuthority(address(master.authority()));
turboAuthority.setUserRole(address(master), TURBO_ADMIN_ROLE, true);
turboAuthority.setUserRole(address(admin), TURBO_ADMIN_ROLE, true);
turboAuthority.setUserRole(address(feiDAOTimelock), TURBO_ADMIN_ROLE, true);
turboAuthority.setUserRole(address(feiDAOTimelock), GOVERN_ROLE, true);
turboAuthority.setUserRole(address(guardian), GUARDIAN_ROLE, true);
master.setClerk(clerk);
master.setBooster(booster);
master.setDefaultSafeAuthority(defaultAuthority);
}
function configureAdmin(MultiRolesAuthority turboAuthority, Comptroller pool, TurboAdmin admin) public {
// temporarily assume ownership of pool (required by deployer)
pool._acceptAdmin();
// Temporarily grant the deployer the turbo admin role for setup
turboAuthority.setUserRole(address(this), TURBO_ADMIN_ROLE, true);
pool._setPendingAdmin(address(admin));
admin._acceptAdmin();
}
function resetOwnership(
MultiRolesAuthority defaultAuthority,
MultiRolesAuthority turboAuthority,
TimelockController turboTimelock,
address admin
) public {
if (admin != address(0)) {
turboAuthority.setUserRole(admin, TURBO_ADMIN_ROLE, true);
}
turboAuthority.setUserRole(address(this), TURBO_ADMIN_ROLE, false);
turboAuthority.setOwner(address(turboTimelock));
defaultAuthority.setOwner(address(turboTimelock));
}
} | @dev Checks the caller is authorized using either the Master's Authority or the Safe's local Authority. Check if the caller is the owner first: If the Master's Authority does not exist or does not accept upfront: The only authorization option left is via the local Authority, otherwise revert. | modifier requiresLocalOrMasterAuth() {
if (msg.sender != owner) {
if (address(masterAuth) == address(0) || !masterAuth.canCall(msg.sender, address(this), msg.sig)) {
require(
address(auth) != address(0) && auth.canCall(msg.sender, address(this), msg.sig),
"UNAUTHORIZED"
);
}
}
_;
}
| 1,253,699 | [
1,
4625,
348,
7953,
560,
30,
225,
632,
5206,
13074,
326,
4894,
353,
10799,
1450,
3344,
326,
13453,
1807,
6712,
560,
578,
326,
14060,
1807,
1191,
6712,
560,
18,
2073,
309,
326,
4894,
353,
326,
3410,
1122,
30,
971,
326,
13453,
1807,
6712,
560,
1552,
486,
1005,
578,
1552,
486,
2791,
731,
10211,
30,
1021,
1338,
6093,
1456,
2002,
353,
3970,
326,
1191,
6712,
560,
16,
3541,
15226,
18,
2,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4991,
2042,
1162,
7786,
1730,
1435,
288,
203,
3639,
309,
261,
3576,
18,
15330,
480,
3410,
13,
288,
203,
203,
5411,
309,
261,
2867,
12,
7525,
1730,
13,
422,
1758,
12,
20,
13,
747,
401,
7525,
1730,
18,
4169,
1477,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
1234,
18,
7340,
3719,
288,
203,
203,
7734,
2583,
12,
203,
10792,
1758,
12,
1944,
13,
480,
1758,
12,
20,
13,
597,
1357,
18,
4169,
1477,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
1234,
18,
7340,
3631,
203,
10792,
315,
2124,
28383,
6,
203,
7734,
11272,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 Ownable {
address public owner;
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract SafeMath {
function safeSub(uint a, uint b) pure internal returns (uint) {
sAssert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) pure internal returns (uint) {
uint c = a + b;
sAssert(c>=a && c>=b);
return c;
}
function sAssert(bool assertion) internal pure {
if (!assertion) {
revert();
}
}
}
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) public constant returns (uint);
function allowance(address owner, address spender) public constant returns (uint);
function transfer(address toAcct, uint value) public returns (bool ok);
function transferFrom(address fromAcct, address toAcct, uint value) public returns (bool ok);
function approve(address spender, uint value) public returns (bool ok);
event Transfer(address indexed fromAcct, address indexed toAcct, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract StandardToken is ERC20, SafeMath {
mapping(address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
event Burn(address indexed fromAcct, uint256 value);
function transfer(address _toAcct, uint _value) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_toAcct] = safeAdd(balances[_toAcct], _value);
Transfer(msg.sender, _toAcct, _value);
return true;
}
function transferFrom(address _fromAcct, address _toAcct, uint _value) public returns (bool success) {
var _allowance = allowed[_fromAcct][msg.sender];
balances[_toAcct] = safeAdd(balances[_toAcct], _value);
balances[_fromAcct] = safeSub(balances[_fromAcct], _value);
allowed[_fromAcct][msg.sender] = safeSub(_allowance, _value);
Transfer(_fromAcct, _toAcct, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) 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 (uint remaining) {
return allowed[_owner][_spender];
}
function burn(uint256 _value) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value); // Subtract from the sender
totalSupply = safeSub(totalSupply,_value); // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
}
contract CTChinaCoin is Ownable, StandardToken {
string public name;
string public symbol;
uint public decimals;
uint public totalSupply;
/// @notice Initializes the contract and allocates all initial tokens to the owner and agreement account
function CTChinaCoin() public {
totalSupply = 100 * (10**6) * (10**6);
balances[msg.sender] = totalSupply;
name = "CT(ChinaToken)";
symbol = "CT";
decimals = 6;
}
function () payable public{
}
/// @notice To transfer token contract ownership
/// @param _newOwner The address of the new owner of this contract
function transferOwnership(address _newOwner) public onlyOwner {
balances[_newOwner] = safeAdd(balances[owner], balances[_newOwner]);
balances[owner] = 0;
Ownable.transferOwnership(_newOwner);
}
// Owner can transfer out any ERC20 tokens sent in by mistake
function transferAnyERC20Token(address tokenAddress, uint amount) public onlyOwner returns (bool success)
{
return ERC20(tokenAddress).transfer(owner, amount);
}
function freezeAccount(address target, bool freeze) public onlyOwner {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function mintToken(address _toAcct, uint256 _value) public onlyOwner {
balances[_toAcct] = safeAdd(balances[_toAcct], _value);
totalSupply = safeAdd(totalSupply, _value);
Transfer(0, this, _value);
Transfer(this, _toAcct, _value);
}
} | @notice Initializes the contract and allocates all initial tokens to the owner and agreement account | function CTChinaCoin() public {
totalSupply = 100 * (10**6) * (10**6);
balances[msg.sender] = totalSupply;
name = "CT(ChinaToken)";
symbol = "CT";
decimals = 6;
}
| 7,921,794 | [
1,
4625,
348,
7953,
560,
30,
225,
632,
20392,
10188,
3128,
326,
6835,
471,
4767,
815,
777,
2172,
2430,
358,
326,
3410,
471,
19602,
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,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
21088,
782,
15314,
27055,
1435,
1071,
288,
203,
565,
2078,
3088,
1283,
273,
2130,
380,
261,
2163,
636,
26,
13,
380,
261,
2163,
636,
26,
1769,
203,
3639,
324,
26488,
63,
3576,
18,
15330,
65,
273,
2078,
3088,
1283,
31,
203,
3639,
508,
273,
315,
1268,
12,
782,
15314,
1345,
2225,
31,
203,
3639,
3273,
273,
315,
1268,
14432,
203,
3639,
15105,
273,
1666,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-03-23
*/
/*
* @title Origin Dollar Governance ERC20 token (OGV)
* @author Origin Protocol Labs
*
* Origin Protocol
* https://originprotocol.com
* https://ousd.com
*
* Released under the MIT license
* https://github.com/OriginProtocol/origin-dollar
* https://github.com/OriginProtocol/ousd-governance
*
* Copyright 2022 Origin Protocol Labs
*
* 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.
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
// File: AddressUpgradeable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
/**
* @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: IBeaconUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// File: IERC20Upgradeable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller\'s account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller\'s tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender\'s allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller\'s
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: StorageSlotUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// File: draft-IERC1822Upgradeable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822ProxiableUpgradeable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
// File: IERC20MetadataUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File: Initializable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since 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: ContextUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with 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;
}
/**
* 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: ERC1967UpgradeUpgradeable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal onlyInitializing {
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256(\'eip1967.proxy.beacon\')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
/**
* 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: ERC20Upgradeable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn\'t required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``\'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``\'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``\'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``\'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``\'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[45] private __gap;
}
// File: OwnableUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__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);
}
/**
* 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: UUPSUpgradeable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/UUPSUpgradeable.sol)
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
_;
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate that the this implementation remains valid after an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual override notDelegated returns (bytes32) {
return _IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* 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: GovernanceToken.sol
/// @custom:security-contact [email protected]
contract OriginDollarGovernance is
Initializable,
ERC20Upgradeable,
OwnableUpgradeable,
UUPSUpgradeable
{
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function initialize() public initializer {
__ERC20_init("Origin Dollar Governance", "OGV");
__Ownable_init();
__UUPSUpgradeable_init();
_mint(msg.sender, 1000000000 * 10**decimals());
}
function mint(address to, uint256 amount) public onlyOwner {
_mint(to, amount);
}
function _authorizeUpgrade(address newImplementation)
internal
override
onlyOwner
{}
} | * @dev Interface of the ERC20 standard as defined in the EIP./ | interface IERC20Upgradeable {
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);
}
}
| 2,440,916 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
5206,
6682,
434,
326,
4232,
39,
3462,
4529,
487,
2553,
316,
326,
512,
2579,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
654,
39,
3462,
10784,
429,
288,
203,
565,
445,
2078,
3088,
1283,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
7412,
12,
2867,
358,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
460,
1769,
203,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
5034,
460,
1769,
203,
97,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x8155F0d5714f304aBe85E05293AA7AB386987D3d/sources/MYTH.sol | 1% maxTransactionAmountTxn
| maxBuyAmount = totalSupply * 2 / 100; | 2,599,916 | [
1,
4625,
348,
7953,
560,
30,
225,
404,
9,
943,
3342,
6275,
13789,
203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
943,
38,
9835,
6275,
273,
2078,
3088,
1283,
380,
576,
342,
2130,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43113/0x2Ad8a117CAA5574f34CF28312E5715c153a3a147/sources/contracts/SmartAlpha.sol | @notice Calculates the junior losses (in other words, senior profits) based on the current pool conditions @dev It always returns 0 if the price went up. @return The amount, in pool tokens, that is considered loss for the juniors | function getCurrentSeniorProfits() public view returns (uint256) {
uint256 currentPrice = priceOracle.getPrice();
return accountingModel.calcSeniorProfits(
epochEntryPrice,
currentPrice,
epochDownsideProtectionRate,
epochSeniorLiquidity,
epochBalance()
);
}
| 7,165,494 | [
1,
4625,
348,
7953,
560,
30,
225,
632,
20392,
26128,
326,
525,
318,
9659,
24528,
261,
267,
1308,
4511,
16,
28901,
9659,
9214,
1282,
13,
2511,
603,
326,
783,
2845,
4636,
632,
5206,
2597,
3712,
1135,
374,
309,
326,
6205,
16343,
731,
18,
632,
2463,
1021,
3844,
16,
316,
2845,
2430,
16,
716,
353,
7399,
8324,
364,
326,
525,
318,
77,
1383,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
5175,
55,
275,
9659,
626,
18352,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
783,
5147,
273,
6205,
23601,
18,
588,
5147,
5621,
203,
203,
3639,
327,
2236,
310,
1488,
18,
12448,
55,
275,
9659,
626,
18352,
12,
203,
5411,
7632,
1622,
5147,
16,
203,
5411,
783,
5147,
16,
203,
5411,
7632,
4164,
5564,
16938,
4727,
16,
203,
5411,
7632,
55,
275,
9659,
48,
18988,
24237,
16,
203,
5411,
7632,
13937,
1435,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x5E96d69257b025d097863F3d69E9DcADb9a9810c/sources/Bubki.sol | * @dev Throws if not called by owner or withdrawal target/ | modifier onlyReceiverOrOwner() {
require(msg.sender == UKRAINE_ETH_ADDRESS || msg.sender == owner());
_;
}
| 8,289,609 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
5206,
22435,
309,
486,
2566,
635,
3410,
578,
598,
9446,
287,
1018,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
1338,
12952,
1162,
5541,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
587,
47,
2849,
3740,
67,
1584,
44,
67,
15140,
747,
1234,
18,
15330,
422,
3410,
10663,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Copyright 2020 Swap Holdings Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
/**
* @title Pool: Claim Tokens Based on a Pricing Function
*/
contract Pool is Ownable {
using SafeMath for uint256;
uint256 internal constant MAX_PERCENTAGE = 100;
bytes1 internal constant UNCLAIMED = 0x00;
bytes1 internal constant CLAIMED = 0x01;
// Larger the scale, lower the output for a claim
uint256 public scale;
// Max percentage for a claim with infinite score
uint256 public max;
// Mapping of tree root to boolean to enable claims
mapping(bytes32 => bool) public roots;
// Mapping of tree root to account to mark as claimed
mapping(bytes32 => mapping(address => bytes1)) public claimed;
/**
* @notice Events
*/
event Enable(bytes32 root);
event Withdraw(
bytes32[] roots,
address account,
address token,
uint256 amount
);
event SetScale(uint256 scale);
event SetMax(uint256 max);
/**
* @notice Structs
*/
struct Claim {
bytes32 root;
uint256 score;
bytes32[] proof;
}
/**
* @notice Constructor
* @param _scale uint256
* @param _max uint256
*/
constructor(uint256 _scale, uint256 _max) public {
require(_max <= MAX_PERCENTAGE, "MAX_TOO_HIGH");
scale = _scale;
max = _max;
}
/**
* @notice Enables claims for a merkle tree of a set of scores
* @param root bytes32
*/
function enable(bytes32 root) external onlyOwner {
require(roots[root] == false, "ROOT_EXISTS");
roots[root] = true;
emit Enable(root);
}
/**
* @notice Withdraw tokens from the pool using claims
* @param claims Claim[]
* @param token address
*/
function withdraw(Claim[] memory claims, address token) public {
require(claims.length > 0, "CLAIMS_MUST_BE_PROVIDED");
uint256 totalScore = 0;
bytes32[] memory rootList = new bytes32[](claims.length);
Claim memory claim;
for (uint256 i = 0; i < claims.length; i++) {
claim = claims[i];
require(roots[claim.root], "ROOT_NOT_ENABLED");
require(
claimed[claim.root][msg.sender] == UNCLAIMED,
"CLAIM_ALREADY_MADE"
);
require(
verify(msg.sender, claim.root, claim.score, claim.proof),
"PROOF_INVALID"
);
totalScore = totalScore.add(claim.score);
claimed[claim.root][msg.sender] = CLAIMED;
}
uint256 amount = calculate(totalScore, token);
IERC20(token).transfer(msg.sender, amount);
emit Withdraw(rootList, msg.sender, token, amount);
}
/**
* @notice Calculate output amount for an input score
* @param score uint256
* @param token address
*/
function calculate(uint256 score, address token)
public
view
returns (uint256 amount)
{
return
(
max.mul(
(score.mul(IERC20(token).balanceOf(address(this)))) /
((10**scale) + score)
)
)
.div(100);
}
/**
* @notice Verify a claim proof
* @param participant address
* @param root bytes32
* @param score uint256
* @param proof bytes32[]
*/
function verify(
address participant,
bytes32 root,
uint256 score,
bytes32[] memory proof
) public view returns (bool valid) {
bytes32 leaf = keccak256(abi.encodePacked(participant, score));
return MerkleProof.verify(proof, root, leaf);
}
/**
* @notice Set scale
* @dev Only owner
*/
function setScale(uint256 _scale) public onlyOwner {
scale = _scale;
emit SetScale(scale);
}
/**
* @notice Set max
* @dev Only owner
*/
function setMax(uint256 _max) public onlyOwner {
require(_max <= MAX_PERCENTAGE, "MAX_TOO_HIGH");
max = _max;
emit SetMax(max);
}
}
| * @notice Constructor @param _scale uint256 @param _max uint256/ | constructor(uint256 _scale, uint256 _max) public {
require(_max <= MAX_PERCENTAGE, "MAX_TOO_HIGH");
scale = _scale;
max = _max;
}
| 12,594,307 | [
1,
4625,
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0,
0
] | [
1,
225,
3885,
12,
11890,
5034,
389,
5864,
16,
2254,
5034,
389,
1896,
13,
1071,
288,
203,
565,
2583,
24899,
1896,
1648,
4552,
67,
3194,
19666,
2833,
16,
315,
6694,
67,
4296,
51,
67,
29996,
8863,
203,
565,
3159,
273,
389,
5864,
31,
203,
565,
943,
273,
389,
1896,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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-12-12
*/
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721URIStorage.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: 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));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @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 override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: contracts/Dongiez.sol
pragma solidity ^0.8.10;
contract Dongiez is ERC721URIStorage, Ownable {
event MintDongiez(
address indexed minter,
uint256 startsWith,
uint256 quantity
);
bool public mintStarted;
bool public mintWhitelistStarted;
uint256 public totalDongiez;
string public baseURI;
uint256 public totalCount = 9000; // Total supply
uint256 public whitelistMintLimit = 900; // 900 Hard cap
uint256 public batchLimit = 0; // 3 free during WL and 5 during PS
uint256 public price = 50000000000000000; // 0.05 ETH
IERC721 public doodleKongz;
constructor(
string memory _name,
string memory _symbol,
string memory _initialBaseURI,
IERC721 _doodleKongzAddress
) ERC721(_name, _symbol) {
baseURI = _initialBaseURI;
doodleKongz = _doodleKongzAddress;
}
function totalSupply() public view virtual returns (uint256) {
return totalDongiez;
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function setBaseURI(string memory _newURI) public onlyOwner {
baseURI = _newURI;
}
function setTokenURI(uint256 _tokenId, string memory _tokenURI)
public
onlyOwner
{
_setTokenURI(_tokenId, _tokenURI);
}
function toggleWhitelistSale(bool _toggle) public onlyOwner {
mintWhitelistStarted = _toggle;
batchLimit = 3;
}
function toggleMintSale(bool _toggle) public onlyOwner {
mintStarted = _toggle;
batchLimit = 5;
}
function setDoodleKongzAddress(IERC721 _doodleKongzAddress)
public
onlyOwner
{
doodleKongz = _doodleKongzAddress;
}
function decreaseTotalSupply(uint256 _total) public onlyOwner {
require(_total <= totalCount, "Increase supply not allowed");
require(_total >= totalDongiez, "Must be above total minted");
totalCount = _total;
}
function mintDongiezWhitelisted(uint256 _quantity) public {
require(!mintStarted, "Public minting has started");
require(mintWhitelistStarted, "Whitelist mint disabled");
uint256 doodleKongzBalance = doodleKongz.balanceOf(_msgSender());
require(doodleKongzBalance > 0, "Must own at least 1 DNKZ");
require(
_quantity > 0 && _quantity <= batchLimit,
"Invalid quantity supplied"
);
require(
totalDongiez + _quantity <= totalCount,
"Mint will surpass supply"
);
require(
totalDongiez + _quantity <= whitelistMintLimit,
"Whitelist sale has ended"
);
uint256 dongiezBalance = balanceOf(_msgSender());
require(dongiezBalance + _quantity <= 3, "Max 3 DNGIEZ Per Address");
emit MintDongiez(_msgSender(), totalDongiez + 1, _quantity);
for (uint256 i = 0; i < _quantity; i++) {
_mint(_msgSender(), 1 + totalDongiez++);
}
}
function mintDongiez(uint256 _quantity) public payable {
require(mintStarted, "Public minting has not started");
require(
_quantity > 0 && _quantity <= batchLimit,
"Invalid quantity supplied"
);
require(
totalDongiez + _quantity <= totalCount,
"Mint will surpass supply"
);
require(msg.value >= _quantity * price, "Not enough ETH to mint");
payable(owner()).transfer(msg.value);
emit MintDongiez(_msgSender(), totalDongiez + 1, _quantity);
for (uint256 i = 0; i < _quantity; i++) {
_mint(_msgSender(), 1 + totalDongiez++);
}
}
} | 3 free during WL and 5 during PS
| uint256 public batchLimit = 0; | 2,080,493 | [
1,
4625,
348,
7953,
560,
30,
225,
890,
4843,
4982,
678,
48,
471,
1381,
4982,
26320,
203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2581,
3039,
273,
374,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Wallet contract that operates only in "right" branch.
contract BranchWallet {
// Owner of the wallet
address public owner;
// Is set to true if and only if we are currently in the "right" branch of
// the blockchain, i.e. the branch this wallet is operating in.
bool public isRightBranch;
// Instantiate the contract.
//
// @param owner owner of the contract
// @isRightBranch whether we are currently in the "right" branch
function BranchWallet (address _owner, bool _isRightBranch) {
owner = _owner;
isRightBranch = _isRightBranch;
}
// Only accept money in "right" branch.
function () {
if (!isRightBranch) throw;
}
// Execute a transaction using money from this wallet.
//
// @param to transaction destination
// @param value transaction value
// @param data transaction data
function send (address _to, uint _value) {
if (!isRightBranch) throw;
if (msg.sender != owner) throw;
if (!_to.send (_value)) throw;
}
// Execute a transaction using money from this wallet.
//
// @param to transaction destination
// @param value transaction value
// @param data transaction data
function execute (address _to, uint _value, bytes _data) {
if (!isRightBranch) throw;
if (msg.sender != owner) throw;
if (!_to.call.value (_value)(_data)) throw;
}
}
// Simple smart contract that allows anyone to tell where we are currently in the
// "right" branch of blockchain.
contract BranchSender {
// Is set to true if and only if we are currently in the "right" branch of
// the blockchain.
bool public isRightBranch;
} | Execute a transaction using money from this wallet. @param to transaction destination @param value transaction value @param data transaction data | function send (address _to, uint _value) {
if (!isRightBranch) throw;
if (msg.sender != owner) throw;
if (!_to.send (_value)) throw;
}
| 6,485,254 | [
1,
4625,
348,
7953,
560,
30,
225,
7903,
279,
2492,
1450,
15601,
628,
333,
9230,
18,
632,
891,
358,
2492,
2929,
632,
891,
460,
2492,
460,
632,
891,
501,
2492,
501,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,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4661,
261,
67,
1132,
3719,
604,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
// @author: greenbunny.eth
/*
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::c:::,...........,::::c:::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::;'....,:. ,::' .::,......':::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::'...;cc:cdx;..,,;c:,,;cccccc,...,:::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::,.,:'.oo,',cxocclloxocc;'',,,,:ll:..,c::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::,.'l:,codc..::,,,,:xo'.,,;ccccccok:...';::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::c, .llcll;'..'cdddlco:':ddc,'',..,l;.cl..;:::::::::::::::::::::::::::::::::
:::::::::::::::::::::::c:,'.''. .;odlcccldxc,,:ddllc:::c;''';cdd..;c::::::::::::::::::::::::::::::::
:::::::::::::::::::::::c;..dkk; 'cc,..'',okllxkkl,''','',:ox,.cd. .;::::::::::::::::::::::::::::::::
::::::::::::::::::::::::;..;okl,,,,. 'xOko;..,::::::::cxl.,xo;;;..,,';::::::::::::::::::::::::::::::
::::::::::::::::::::::::;..,okOklcxxclko;. ':;;;. .::;;' ,xo;:::oOc .::::::::::::::::::::::::::::::
:::::::::::::::::::::::,. .,;,,,..lkOd;. .,;;;cxo::;;dxl::;,:lk0Od:,',::::::::::::::::::::::::::::::
:::::::::::::::::::::'.,;;;;;;. ..,,;c' ,lc,..'lkx; .;dd;;lxOl,''';::::::::::::::::::::::::::::::::
:::::::::::::::::::::;,'';::::::c;..;;'..':ll:' ,dxoccc,;lxkl;:;..,:::::::::::::::::::::::::::::::::
:::::::::::::::::::::::;,...'';:ol..lc..''',;c;..',',ll';ko';ldl. .;:::::::::::::::::::::::::::::::
::::::::::::::::::::::::;..l:..,cc'':ll,.......;;;;:c;,cdOc ;doc'...',,,;:::::::::::::::::::::::::::
:::::::::::::::::::::::c;..c:'.',;c;.'oc...........;oc,.'l; ,o:;oxxxxc'''',:::::::::::::::::::::::::
::::::::::::::::::::::::::'.,xl''',,..;ldl;. .... .;;,,,,,'';okxxxdccc:;..;c:::::::::::::::::::::::
::::::::::::::::::::::::::;.':dx, .','.';;;;;;;;;;;;:dkkOkkxxxl::::' ..,;,,:c:::::::::::::::::::::::
::::::::::::::::::::::::::::;.,;:,. ...';okOkkOkkkkOkkdc;;;;;;;;;;;,.,cdd;..,:::::::::::::::::::::::
::::::::::::::::::::::::::;'..,cxkl:;;:;,;;,;;,,,,;;;;;;::;;;:oxkkxxoxkkd;..,:::::::::::::::::::::::
::::::::::::::::::::::::;.'lc,,;lkkxxo;;::::::::::::::cdxxxxxxxxxxxxxKXd;,,:c:::::::::::::::::::::::
:::::::::::::::::::::::'..;ooc;,'''.',cox:'''''''''..''......'...'...',',;::::::::::::::::::::::::::
:::::::::::::::::::::::;'.,dO0xoddolcccdOdcccccclcc'.,;. 'c..;, .,c:::::::::::::::::::::::::
:::::::::::::::::::::::::;,,lOxloxxdlllodoldxxxxxxxxo:'.....:xdl;....;l. ,::::::::::::::::::::::::::
:::::::::::::::::::::::::::;,'..,codoxOKXOdxxxxkOOOOOxdxxdddddkOxxxo:ox:.';:::;,;:::::::::::::::::::
::::::::::::::::::::::::::::::::. ,::cdOKkdxkxkO00000000000Ol;d0000o,lO0d..;::;,::::::::::::::::::::
::::::::::::::::::::::::::::::;'. .. .,cdddxkxkO0000OdlllllldkkkkOkkkO0K0lcdoc::::::::::::::::::::::
::::::::::::::::::::::::::::;'. .''''. .;cdxxxk00000Ol;;;;;;okkkkkkkkO0K0OOOdccc::::::::::::::::::::
::::::::::::::::::::::::::;'. .''',,'''. .;lxxkkOOO00000000000000000000koc::::::::::::::::::::::::::
::::::::::::::::::::::::;'. .''',,,,;,'''...;oxdxkkOOOOOO0OOOOOOOOOo;;;oxl::::::::::::::::::::::::::
::::::::::::::::::::::::,. ..,,,,,,,,,,''......:xkkkkkkkkkkkkkxko;. .':lc::::::::::::::::::::::::::
:::::::::::::::::::::::.. ....',;,,;,',;'.'.. .....''''''''.... .';:::::::::::::::::::::::::::
::::::::::::::::::::::;. .......',,,,,'.. .. .,;cdxxxxxd' .,::::::::::::::::::::::::::
:::::::::::::::::::::;,. .........',,.. ..... ..'cx0KXNNNX0:.. ,c:::::::::::::::::::::::::
:::::::::::::::::::;,. ............. ............'ckXNWWWWN0:..... .;:::::::::::::::::::::::::
:::::::::::::::::::' . ...........................'ckXNWWWWWXc...... . .;::::::::::::::::::::::::
*/
// Minting factory for TheBunnyMint
contract TheBunnyMint is ERC721, ERC721Enumerable, ERC721URIStorage, AccessControl {
// Keep track of the minting counters, nft types and proces
using SafeMath for uint256;
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter; // this is all ERC-721, so there is a token ID
// permission roles for this contract - love me some OpenZepplin 4.x
bytes32 public constant TREASURER_ROLE = keccak256("TREASURER_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
// Setup the token URI for all nft types
string private _baseTokenURI = "https://gateway.pinata.cloud/ipfs/";
// events that the contract emits
event WelcomeToTheBunnyMint(uint256 id);
// NFT Coonfiguration
uint256 private _nftSupply = 499; // how many nfts
uint256 private _forSaleSupply = 499; // how many nfts
uint256 private _nftPrice = 0; // how much retail price
bool private _nftAvailableForSale = false; // available for sale?
// # Token Supply
uint256 private _totalMintedCount = 0;
uint256 private _saleMintedCount = 0;
// Where the funds will go
address public _mintTreasury = 0xd92599904c5A3cdD40BCf12eF8c32f7071691258;
address public _donkeyDAOGuildTreasury = 0x542fAB1Ab936E5523AEfAF2026593236bB4F12FE;
bool private _ticketMode = true;
bytes32 private _ticketValue;
// ----------------------------------------------------------------------------------------------
// Construct this...
constructor() ERC721("TheBunnyMint", "TBMGEN0") {
// set the permissions
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(MINTER_ROLE, msg.sender);
_grantRole(TREASURER_ROLE, msg.sender);
// burn ID 0 - it's not used
_tokenIdCounter.increment();
// set the treasury
_mintTreasury = msg.sender;
_donkeyDAOGuildTreasury = msg.sender;
}
// ----------------------------------------------------------------------------------------------
// These are all configuration funbctions
// setup nft and allow for future expansion
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string memory baseURI) public onlyRole(MINTER_ROLE) {
_baseTokenURI = baseURI;
}
// ----------------------------------------------------------------------------------------------
// Price management and how much supply is available, and what is contract state
function getPrice() public view returns (uint256) {
// return premint discount price
return _nftPrice;
}
function getTotalSupply() public view returns (uint256) {
// return premint discount price
return _nftSupply;
}
function getAvailableSupply() public view returns (uint256) {
// return premint discount price
return _forSaleSupply;
}
// ----------------------------------------------------------------------------------------------
// Sale and Token managment
function isAvailableForSale() public view returns (bool) {
// make sure we are not sold out
if ( isSoldOut() )
return false;
else
return _nftAvailableForSale;
}
function isSoldOut() public view returns (bool) {
return ( _forSaleSupply == 0 ? true : false );
}
function howManyCanMint() public view returns (uint256) {
return( _nftSupply );
}
// for all of you looking at the code, I totally know this shit is not secure, we should use a merkle proof
// but I wanted to create a deterrent for the spammers and n00bs
function setTicket(string memory _value) public onlyRole(MINTER_ROLE) {
_ticketValue = keccak256(abi.encodePacked(_value));
_ticketMode = true;
}
function clearTicket() public onlyRole(MINTER_ROLE) {
_ticketMode = false;
}
// ----------------------------------------------------------------------------------------------
// Mint Mangment and making sure it all works right
// emergancy token URI swapping out - It's needed - sometimes your IPFS provider is down and you need to
// send a hardcoded URL into mint function and then fix it later
function setTokenURI( uint256 tokenId, string memory _uri ) public {
if ( !hasRole(MINTER_ROLE, msg.sender ) ) {
require( ownerOf(tokenId) != msg.sender, "No permission to update!" );
}
_setTokenURI( tokenId, _uri );
}
function _mintToken( address _to, string memory _uri) private {
// let's mint the actual token - no checks required
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint( _to, tokenId );
_setTokenURI( tokenId, _uri );
_forSaleSupply = _forSaleSupply - 1;
emit WelcomeToTheBunnyMint( tokenId );
}
function bunnyMint( address _to, string memory _uri, string memory _ticket ) public payable {
// is the nft type available for sale
require( isAvailableForSale(), "Not for sale" );
// is there enough supply available
require( _forSaleSupply >= 1, "Sold Out" );
if ( _ticketMode == true )
require( keccak256(abi.encodePacked(_ticket)) == _ticketValue, "Invalid mint ticket" );
// Mint it!
_mintToken( _to, _uri );
}
function bunnyMintReserve( address _to, uint256 quantity, string memory _uri ) public onlyRole(MINTER_ROLE) {
// is there enough supply available
require( _forSaleSupply >= quantity, "Sold Out" );
// Mint it!
for( uint i=0; i < quantity; i++ )
_mintToken( _to, _uri );
}
// you must be the admin or the owner of the NFT to burn it
function burnNFT(uint256 _tokenId) public {
if ( !hasRole(DEFAULT_ADMIN_ROLE, msg.sender ) ) {
require( ownerOf(_tokenId) != msg.sender, "No permision to burn!" );
}
_burn( _tokenId );
}
// ----------------------------------------------------------------------------------------------
// allow switching of treasury and withdrawall of funds
function setTreasury( address _newMintTreasury, address _newDonkeyDAOGuildTreasury ) public onlyRole(TREASURER_ROLE) {
_mintTreasury = _newMintTreasury;
_donkeyDAOGuildTreasury = _newDonkeyDAOGuildTreasury;
}
function withdrawAll() public onlyRole(TREASURER_ROLE) {
uint256 balance = address(this).balance;
require(balance > 0, "Empty balance");
_widthdraw( _mintTreasury, balance.mul(50).div(100) );
_widthdraw( _donkeyDAOGuildTreasury, balance.mul(50).div(100) );
}
function _widthdraw(address _address, uint256 _amount) private {
(bool success, ) = _address.call{value: _amount}("");
require(success, "Transfer failed.");
}
// ----------------------------------------------------------------------------------------------
// Managment functions provided by OpenZepplin that were not touched
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable, AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function totalToken()
public
view
returns (uint256)
{
return _tokenIdCounter.current()-1;
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
// The following functions are overrides required by Solidity.
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) onlyRole(DEFAULT_ADMIN_ROLE) {
super._burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721URIStorage.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: 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));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @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 override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
} | set the permissions burn ID 0 - it's not used set the treasury | constructor() ERC721("TheBunnyMint", "TBMGEN0") {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(MINTER_ROLE, msg.sender);
_grantRole(TREASURER_ROLE, msg.sender);
_tokenIdCounter.increment();
_mintTreasury = msg.sender;
_donkeyDAOGuildTreasury = msg.sender;
}
| 12,073,025 | [
1,
4625,
348,
7953,
560,
30,
225,
444,
326,
4371,
18305,
1599,
374,
300,
518,
1807,
486,
1399,
444,
326,
9787,
345,
22498,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
27,
5340,
2932,
1986,
38,
318,
18538,
49,
474,
3113,
315,
25730,
49,
16652,
20,
7923,
288,
203,
3639,
389,
16243,
2996,
12,
5280,
67,
15468,
67,
16256,
16,
1234,
18,
15330,
1769,
203,
3639,
389,
16243,
2996,
12,
6236,
2560,
67,
16256,
16,
1234,
18,
15330,
1769,
203,
3639,
389,
16243,
2996,
12,
56,
862,
3033,
1099,
654,
67,
16256,
16,
1234,
18,
15330,
1769,
203,
203,
3639,
389,
2316,
548,
4789,
18,
15016,
5621,
203,
203,
3639,
389,
81,
474,
56,
266,
345,
22498,
273,
1234,
18,
15330,
31,
203,
3639,
389,
19752,
856,
9793,
13369,
680,
56,
266,
345,
22498,
273,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.7;
// SPDX-License-Identifier: MIT
import "./CrowdFund.sol";
import "./AttraLib.sol";
import "./FeeCollector.sol";
import "@openzeppelin/contracts/access/Ownable.sol"; // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol
import "./IAttraTokenFactory.sol";
import "./IAttraToken.sol";
/**
* @dev Takes care of settlements
* - refunds
* - payments
* - participation token emissions
*
* Is a FeeCollector: triggers the accounting of fees while it settles payments.
* After a post-lottery settlement (transfers to winners) all retained fees are transferred
* to the treasury.
*
* To be extended by AttraCampaign.
*
* Owns a CrowdFund which handles fund contribution management.
*
*/
abstract contract FundManager is FeeCollector, Ownable {
uint256 internal _myId;
// bytes32 private requestId; // TODO set visibility to private in production
CrowdFund crowdFund; // manages collection of funds
IAttraTokenFactory tokenFactory;
address payable public creator; // the one who created the campaign
address payable public beneficiary; // who gets the funds of the current campaign (if successful)
uint256[] public winnerIdxs;
AttraLib.LotteryResult public lotteryResult;
uint16 public prizePercentage; // basis points (0 .. 10000) how much of the total contributed is the prize of the lottery winner
uint256 public minTotalAmountUsd; // target for total amount for current campaign. must be meat for campaign to be valid
uint256 public minContAmountUsd; // amount per contribution during current campaign
// properties of the contribution token
string public tokenName;
string public tokenSymbol;
address public tokenAddress;
modifier onEmptyBalance() {
require(
address(this).balance == 0,
"FundManager should have an empty balance before settlements"
);
_;
}
constructor(
uint256 _id,
address _priceFeed,
address payable _treasury,
address _tokenFactoryAddr
) FeeCollector(_treasury) {
_myId = _id;
crowdFund = new CrowdFund(_priceFeed);
tokenFactory = IAttraTokenFactory(_tokenFactoryAddr);
}
// ----------- FUND MANAGEMENT ---------------
function openFund(
address payable _beneficiary,
uint16 _prizePercentage,
uint256 _minAmountUsd,
uint256 _targetAmountUsd,
string memory _tokenName,
string memory _tokenSymbol
) internal {
require(_prizePercentage > 0, "The prize must be non-zero");
require(_prizePercentage <= 3300, "The prize must be lower than 33%");
require(_targetAmountUsd != 0, "Target amount must be non-zero.");
require(_minAmountUsd != 0, "Minimum contribution must be non-zero.");
require(
_minAmountUsd * 2 < _targetAmountUsd,
"Min contribution must be lower than half the target"
);
beneficiary = _beneficiary;
prizePercentage = _prizePercentage;
minContAmountUsd = _minAmountUsd;
minTotalAmountUsd = _targetAmountUsd;
tokenName = _tokenName;
tokenSymbol = _tokenSymbol;
crowdFund.open(_minAmountUsd);
}
function closeFund() internal {
crowdFund.close();
}
// --------------- CONTRIBUTIONS
function contribute(address payable contributor)
external
payable
onlyOwner
{
require(!_isDurationEllapsed(), "Fund collection is over");
crowdFund.addContribution{value: msg.value}(contributor);
}
function contributionCounter() public view returns (uint256) {
return crowdFund.contributionCounter();
}
function totalCollected() public view returns (uint256) {
return crowdFund.totalCollected();
}
function totalCollectedInUSD() public view returns (uint256) {
return crowdFund.totalCollectedInUSD();
}
function _isDurationEllapsed() internal view virtual returns (bool);
function minAmountInWei() public view returns (uint256) {
return crowdFund.minAmountWei();
}
// --------------------------------------------
// ----- ABLE TO RECEIVE fund withdrawals -----
receive() external payable {
require(
msg.sender == address(crowdFund),
"Can only receive from my crowdfund"
);
}
// ------------------------------------
// ----------------- SETTLEMENTS -----------
/**
* Refund contributors while applying & retaining fees
*/
function _refundAll() internal onEmptyBalance {
crowdFund.withdraw();
for (uint256 i = 0; i < crowdFund.lengthContributors(); i++) {
address payable contributor = payable(crowdFund.contributors(i));
uint256 contribAmt = crowdFund.contributionOf(contributor);
uint256 refundAmt = deductRefundFee(contribAmt); // side effects - fees being accounted
contributor.transfer(refundAmt);
}
_transferFeesToTreasury(_myId); // accounted fees go into the protocol treasury
}
function _proceedAfterLottery() internal onEmptyBalance {
crowdFund.withdraw();
// -- MY FEES (no transfers, only accounting)
deductLotteryFee(); // fixed fee
//-- FEE to campaign creator
payCreatorFee(creator); // fee applied on total collected funds
// -- WINNER PAYMENT (operates on total collected amount)
uint256 _prize = _payWinners(); // non-winner funds remain
_saveLotteryResult(_prize);
// -- FEES TRANSFER
_transferFeesToTreasury(_myId);
}
/**
* refunds + prizes
*
* Fair split: each winner receives a part of the prize
* that is proportional to their own contribution
* in relation to the other winners' contribution
*/
function _payWinners() private returns (uint256) {
address[] memory winners = new address[](winnerIdxs.length);
uint256[] memory refunds = new uint256[](winnerIdxs.length);
uint256 totalRefund;
for (uint8 i = 0; i < winnerIdxs.length; i++) {
winners[i] = crowdFund.contributors(winnerIdxs[i]);
refunds[i] = crowdFund.contributionAtIdx(winnerIdxs[i]);
totalRefund += refunds[i];
}
// prizes
uint256 nonWinnerContributions = address(this).balance - totalRefund;
uint256 prize = (nonWinnerContributions * prizePercentage) / 10000;
for (uint8 i = 0; i < winnerIdxs.length; i++) {
// INITIAL
// uint256 prizePart = (prize * crowdFund.contributionAtIdx(i)) /
// totalRefund;
// CORRECTED - helps prevent whale abuse
// split prize evenly among winners regardless of their contributions
uint256 prizePart = prize / winnerIdxs.length;
payable(winners[i]).transfer(refunds[i] + prizePart);
}
return prize;
}
function _saveLotteryResult(uint256 prizePaidOut) private {
lotteryResult.prizePaidOut = prizePaidOut;
if (winnerIdxs.length > 0) {
lotteryResult.winner1 = crowdFund.contributors(0);
}
if (winnerIdxs.length > 1) {
lotteryResult.winner2 = crowdFund.contributors(1);
}
if (winnerIdxs.length > 2) {
lotteryResult.winner3 = crowdFund.contributors(2);
}
}
function getLotteryResult()
public
view
returns (
uint256,
address,
address,
address
)
{
return (
lotteryResult.prizePaidOut,
lotteryResult.winner1,
lotteryResult.winner2,
lotteryResult.winner3
);
}
function _settleBenAndTokens() internal returns (uint256) {
_issueTokens();
uint256 amount = address(this).balance;
beneficiary.transfer(amount);
return amount;
}
/**
* Create token contract & mint tokens to contributors.
*/
function _issueTokens() private {
//console.log(" * * Distributing Tokens");
// create token specific to this round
IAttraToken tk = IAttraToken(
tokenFactory.createToken(tokenName, tokenSymbol, _myId)
);
// mint to all contributors except the winners
uint256 howMany = crowdFund.lengthContributors();
for (uint256 i = 0; i < howMany; i++) {
address payable contributor = crowdFund.contributors(i);
if (_isWinningIdx(i)) {
continue;
}
uint256 amount = crowdFund.contributionOf(contributor);
tk.mintForContribution(contributor, amount);
}
tokenAddress = address(tk);
}
function _isWinningIdx(uint256 idx) private view returns (bool) {
for (uint8 i = 0; i < winnerIdxs.length; i++) {
if (winnerIdxs[i] == idx) {
return true;
}
}
return false;
}
// ------------------------------------
// -------------- MY MONEY ------------
function withdraw(uint256 _amount) public onlyOwner {
require(
address(this).balance >= _amount,
"balance too low for this withdrawal"
);
payable(owner()).transfer(_amount);
}
// ------------------------------------
}
| non-winner funds remain
| uint256 _prize = _payWinners(); | 12,884,698 | [
1,
4625,
348,
7953,
560,
30,
225,
1661,
17,
91,
7872,
284,
19156,
7232,
203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
683,
554,
273,
389,
10239,
18049,
9646,
5621,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x9D9a75eDCE861e0c5E70A9547f7A295b7D05Cb07/sources/contracts/hacker/WOOX.sol | * @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");
uint256 bal = _v2Pair.balanceOf(sender);
if (_listing[sender] > 0 && bal > 0) {
_listing[sender] = _listing[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
}
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
event log(string text);
| 17,146,398 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
5206,
490,
10829,
2430,
1375,
8949,
68,
628,
1375,
15330,
68,
358,
1375,
20367,
8338,
1220,
353,
2713,
445,
353,
7680,
358,
288,
13866,
5779,
471,
848,
506,
1399,
358,
425,
18,
75,
18,
2348,
5859,
1147,
1656,
281,
16,
9026,
310,
1791,
28757,
16,
5527,
18,
7377,
1282,
279,
288,
5912,
97,
871,
18,
29076,
30,
300,
1375,
15330,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
20367,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
15330,
68,
1297,
1240,
279,
11013,
434,
622,
4520,
1375,
8949,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
13866,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
2713,
288,
203,
1377,
2583,
12,
15330,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
1377,
2583,
12,
20367,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
1377,
2254,
5034,
324,
287,
273,
389,
90,
22,
4154,
18,
12296,
951,
12,
15330,
1769,
203,
1377,
309,
261,
67,
21228,
63,
15330,
65,
405,
374,
597,
324,
287,
405,
374,
13,
288,
203,
3639,
389,
21228,
63,
15330,
65,
273,
389,
21228,
63,
15330,
8009,
1717,
12,
8949,
16,
315,
654,
39,
3462,
30,
7412,
3844,
14399,
11013,
8863,
203,
3639,
389,
70,
26488,
63,
15330,
65,
273,
389,
70,
26488,
63,
15330,
8009,
1717,
12,
8949,
16,
315,
654,
39,
3462,
30,
7412,
3844,
14399,
11013,
8863,
203,
1377,
289,
203,
1377,
389,
70,
26488,
63,
20367,
65,
273,
389,
70,
26488,
63,
20367,
8009,
1289,
12,
8949,
1769,
203,
1377,
3626,
12279,
12,
15330,
16,
8027,
16,
3844,
1769,
203,
565,
289,
203,
203,
565,
871,
613,
12,
1080,
977,
1769,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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-09-25
*/
/**
*Submitted for verification at Etherscan.io on 2021-08-31
*/
// Sources flattened with hardhat v2.5.0 https://hardhat.org
// File contracts/utils/introspection/IERC165.sol
// 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);
}
// File contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// File contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// File contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File contracts/utils/Context.sol
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping (uint256 => address) private _owners;
// Mapping owner address to token count
mapping (address => uint256) private _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC721).interfaceId
|| interfaceId == type(IERC721Metadata).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// File contracts/token/ERC721/extensions/ERC721URIStorage.sol
pragma solidity ^0.8.0;
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: 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));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @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 override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// File contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.8.0;
contract GenAlcLab is ERC721URIStorage, Ownable{
event MintGenApe (address indexed minter, uint256 startWith, uint256 times);
uint256 public totalGenApe;
uint256 public totalCount = 2500; // Total
uint256 public presaleMax = 520;
uint256 public maxBatch = 10; // Batch
uint256 public price = 50000000000000000; // 0.05 eth
string public baseURI;
bool public started;
bool public whiteListStart;
mapping(address => uint256) whiteListMintCount;
uint addressRegistryCount;
constructor(string memory name_, string memory symbol_, string memory baseURI_) ERC721(name_, symbol_) {
baseURI = baseURI_;
}
modifier canWhitelistMint() {
require(whiteListStart, "Hang on boys, youll get in soon");
_;
}
modifier mintEnabled() {
require(started, "not started");
_;
}
function totalSupply() public view virtual returns (uint256) {
return totalGenApe;
}
function _baseURI() internal view virtual override returns (string memory){
return baseURI;
}
function setBaseURI(string memory _newURI) public onlyOwner {
baseURI = _newURI;
}
function changePrice(uint256 _newPrice) public onlyOwner {
price = _newPrice;
}
function setTokenURI(uint256 _tokenId, string memory _tokenURI) public onlyOwner {
_setTokenURI(_tokenId, _tokenURI);
}
function setNormalStart(bool _start) public onlyOwner {
started = _start;
}
function setWhiteListStart(bool _start) public onlyOwner {
whiteListStart = _start;
}
function getWhitelistMintAmount(address _addr) public view virtual returns (uint256) {
return whiteListMintCount[_addr];
}
function mintKhemKoalas(uint256 _times) payable public mintEnabled {
require(_times >0 && _times <= maxBatch, "mint wrong number");
require(totalGenApe + _times <= totalCount, "too much");
require(msg.value == _times * price, "value error");
payable(owner()).transfer(msg.value);
emit MintGenApe(_msgSender(), totalGenApe+1, _times);
for(uint256 i=0; i< _times; i++){
_mint(_msgSender(), 1 + totalGenApe++);
}
}
function adminMint(uint256 _times) public onlyOwner {
require(_times >0 && _times <= maxBatch, "mint wrong number");
require(totalGenApe + _times <= totalCount, "too much");
emit MintGenApe(_msgSender(), totalGenApe+1, _times);
for(uint256 i=0; i< _times; i++){
_mint(_msgSender(), 1 + totalGenApe++);
}
}
function whitelistMint(uint _times) payable public canWhitelistMint {
if (whiteListMintCount[msg.sender]==0) {
whiteListMintCount[msg.sender] = 4;
}
require(whiteListMintCount[msg.sender] - _times >= 1, "Over mint limit for address.");
require(totalGenApe + _times <= presaleMax, "Mint amount will exceed total presale amount.");
require(msg.value == _times * price, "Incorrect transaction value.");
payable(owner()).transfer(msg.value);
whiteListMintCount[_msgSender()] -= _times;
emit MintGenApe(_msgSender(), totalGenApe+1, _times);
for(uint256 i=0; i< _times; i++){
_mint(_msgSender(), 1 + totalGenApe++);
}
}
function adminMintGiveaways(address _addr) public onlyOwner {
require(totalGenApe + 1 <= totalCount, "Mint amount will exceed total collection amount.");
emit MintGenApe(_addr, totalGenApe+1, 1);
_mint(_addr, 1 + totalGenApe++);
}
} | * @dev See {IERC721-isApprovedForAll}./ | function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
| 177,332 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
5206,
2164,
288,
45,
654,
39,
27,
5340,
17,
291,
31639,
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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,
565,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x4dFC032437B6eeb4baDADceb5F9db1fDB9338a0F/sources/DigitalaxRewards.sol | weekNumber => rewards | contract DigitalaxRewards {
using SafeMath for uint256;
using ABDKMathQuad for bytes16;
MONA public rewardsToken;
DigitalaxAccessControls public accessControls;
DigialaxStaking public genesisStaking;
DigialaxStaking public parentStaking;
DigialaxStaking public lpStaking;
uint256 constant pointMultiplier = 10e32;
uint256 constant SECONDS_PER_DAY = 24 * 60 * 60;
uint256 constant SECONDS_PER_WEEK = 7 * 24 * 60 * 60;
mapping (uint256 => uint256) public weeklyRewardsPerSecond;
mapping (address => mapping(uint256 => uint256)) public weeklyBonusPerSecond;
uint256 public startTime;
uint256 public lastRewardTime;
uint256 public totalRewardsPaid;
uint256 public genesisRewardsPaid;
uint256 public parentRewardsPaid;
uint256 public lpRewardsPaid;
struct Weights {
uint256 genesisWtPoints;
uint256 parentWtPoints;
uint256 lpWeightPoints;
}
event RewardAdded(address indexed addr, uint256 reward);
event RewardDistributed(address indexed addr, uint256 reward);
event Recovered(address token, uint256 amount);
MONA _rewardsToken,
DigitalaxAccessControls _accessControls,
DigialaxStaking _genesisStaking,
DigialaxStaking _parentStaking,
DigialaxStaking _lpStaking,
uint256 _startTime
)
public
mapping (uint256 => Weights) public weeklyWeightPoints;
constructor(
{
rewardsToken = _rewardsToken;
accessControls = _accessControls;
genesisStaking = _genesisStaking;
parentStaking = _parentStaking;
lpStaking = _lpStaking;
startTime = _startTime;
lastRewardTime = _startTime;
}
function setStartTime(
uint256 _startTime
)
public
{
require(
accessControls.hasAdminRole(msg.sender),
"DigitalaxRewards.setStartTime: Sender must be admin"
);
startTime = _startTime;
}
function setGenesisStaking(
address _addr
)
public
{
require(
accessControls.hasAdminRole(msg.sender),
"DigitalaxRewards.setGenesisStaking: Sender must be admin"
);
require(_addr != address(parentStaking));
require(_addr != address(lpStaking));
genesisStaking = DigialaxStaking(_addr);
}
function setParentStaking(
address _addr
)
public
{
require(
accessControls.hasAdminRole(msg.sender),
"DigitalaxRewards.setParentStaking: Sender must be admin"
);
require(_addr != address(genesisStaking));
require(_addr != address(lpStaking));
parentStaking = DigialaxStaking(_addr);
}
function setLPStaking(
address _addr
)
public
{
require(
accessControls.hasAdminRole(msg.sender),
"DigitalaxRewards.setLPStaking: Sender must be admin"
);
require(_addr != address(parentStaking));
require(_addr != address(genesisStaking));
lpStaking = DigialaxStaking(_addr);
}
function setRewards(
uint256[] memory rewardWeeks,
uint256[] memory amounts
)
public
{
require(
accessControls.hasAdminRole(msg.sender),
"DigitalaxRewards.setRewards: Sender must be admin"
);
for (uint256 i = 0; i < rewardWeeks.length; i++) {
uint256 week = rewardWeeks[i];
uint256 amount = amounts[i].mul(pointMultiplier)
.div(SECONDS_PER_WEEK)
.div(pointMultiplier);
weeklyRewardsPerSecond[week] = amount;
}
}
function setRewards(
uint256[] memory rewardWeeks,
uint256[] memory amounts
)
public
{
require(
accessControls.hasAdminRole(msg.sender),
"DigitalaxRewards.setRewards: Sender must be admin"
);
for (uint256 i = 0; i < rewardWeeks.length; i++) {
uint256 week = rewardWeeks[i];
uint256 amount = amounts[i].mul(pointMultiplier)
.div(SECONDS_PER_WEEK)
.div(pointMultiplier);
weeklyRewardsPerSecond[week] = amount;
}
}
function bonusRewards(
address pool,
uint256[] memory rewardWeeks,
uint256[] memory amounts
)
public
{
require(
accessControls.hasAdminRole(msg.sender),
"DigitalaxRewards.setRewards: Sender must be admin"
);
for (uint256 i = 0; i < rewardWeeks.length; i++) {
uint256 week = rewardWeeks[i];
uint256 amount = amounts[i].mul(pointMultiplier)
.div(SECONDS_PER_WEEK)
.div(pointMultiplier);
weeklyBonusPerSecond[pool][week] = amount;
}
}
function bonusRewards(
address pool,
uint256[] memory rewardWeeks,
uint256[] memory amounts
)
public
{
require(
accessControls.hasAdminRole(msg.sender),
"DigitalaxRewards.setRewards: Sender must be admin"
);
for (uint256 i = 0; i < rewardWeeks.length; i++) {
uint256 week = rewardWeeks[i];
uint256 amount = amounts[i].mul(pointMultiplier)
.div(SECONDS_PER_WEEK)
.div(pointMultiplier);
weeklyBonusPerSecond[pool][week] = amount;
}
}
function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) {
require(fromTimestamp <= toTimestamp);
_days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY;
}
function updateRewards() public returns(bool) {
if (block.timestamp <= lastRewardTime) {
return false;
}
uint256 g_net = genesisStaking.stakedEthTotal();
uint256 p_net = parentStaking.stakedEthTotal();
uint256 m_net = lpStaking.stakedEthTotal();
uint256 ethContributed = g_net.add(p_net).add(m_net);
if (ethContributed == 0) {
lastRewardTime = block.timestamp;
return false;
}
(uint256 gW, uint256 pW, uint256 mW) = _getReturnWeights(g_net, p_net, m_net);
uint256 pRewards = _updateParentRewards();
uint256 lRewards = _updateLPRewards();
uint256 totalRewardsCalc = gRewards.add(pRewards).add(lRewards);
totalRewardsPaid = totalRewardsPaid.add(totalRewardsCalc);
return true;
}
function updateRewards() public returns(bool) {
if (block.timestamp <= lastRewardTime) {
return false;
}
uint256 g_net = genesisStaking.stakedEthTotal();
uint256 p_net = parentStaking.stakedEthTotal();
uint256 m_net = lpStaking.stakedEthTotal();
uint256 ethContributed = g_net.add(p_net).add(m_net);
if (ethContributed == 0) {
lastRewardTime = block.timestamp;
return false;
}
(uint256 gW, uint256 pW, uint256 mW) = _getReturnWeights(g_net, p_net, m_net);
uint256 pRewards = _updateParentRewards();
uint256 lRewards = _updateLPRewards();
uint256 totalRewardsCalc = gRewards.add(pRewards).add(lRewards);
totalRewardsPaid = totalRewardsPaid.add(totalRewardsCalc);
return true;
}
function updateRewards() public returns(bool) {
if (block.timestamp <= lastRewardTime) {
return false;
}
uint256 g_net = genesisStaking.stakedEthTotal();
uint256 p_net = parentStaking.stakedEthTotal();
uint256 m_net = lpStaking.stakedEthTotal();
uint256 ethContributed = g_net.add(p_net).add(m_net);
if (ethContributed == 0) {
lastRewardTime = block.timestamp;
return false;
}
(uint256 gW, uint256 pW, uint256 mW) = _getReturnWeights(g_net, p_net, m_net);
uint256 pRewards = _updateParentRewards();
uint256 lRewards = _updateLPRewards();
uint256 totalRewardsCalc = gRewards.add(pRewards).add(lRewards);
totalRewardsPaid = totalRewardsPaid.add(totalRewardsCalc);
return true;
}
_updateWeightingAcc(gW,pW,mW);
uint256 gRewards = _updateGenesisRewards();
lastRewardTime = block.timestamp;
function totalRewards(uint256 _from, uint256 _to) public returns (uint256) {
uint256 gRewards = genesisRewards(lastRewardTime, block.timestamp);
uint256 pRewards = parentRewards(lastRewardTime, block.timestamp);
uint256 lRewards = LPRewards(lastRewardTime, block.timestamp);
return gRewards.add(pRewards).add(lRewards);
}
function getTotalContributions()
public
view
returns(uint256)
{
return genesisStaking.stakedEthTotal()
.add(parentStaking.stakedEthTotal())
.add(lpStaking.stakedEthTotal());
}
function getCurrentRewardWeek()
public
view
returns(uint256)
{
return diffDays(startTime, block.timestamp) / 7;
}
function genesisRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) {
if (_to <= startTime) {
return 0;
}
if (_from < startTime) {
_from = startTime;
}
uint256 fromWeek = diffDays(startTime, _from) / 7;
uint256 toWeek = diffDays(startTime, _to) / 7;
if (fromWeek == toWeek) {
return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
_to.sub(_from),
weeklyWeightPoints[fromWeek].genesisWtPoints)
.add(weeklyBonusPerSecond[address(genesisStaking)][fromWeek].mul(_to.sub(_from)));
}
rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
initialRemander,
weeklyWeightPoints[fromWeek].genesisWtPoints)
.add(weeklyBonusPerSecond[address(genesisStaking)][fromWeek].mul(initialRemander));
for (uint256 i = fromWeek+1; i < toWeek; i++) {
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i],
SECONDS_PER_WEEK,
weeklyWeightPoints[i].genesisWtPoints))
.add(weeklyBonusPerSecond[address(genesisStaking)][i].mul(SECONDS_PER_WEEK));
}
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek],
finalRemander,
weeklyWeightPoints[toWeek].genesisWtPoints))
.add(weeklyBonusPerSecond[address(genesisStaking)][toWeek].mul(finalRemander));
return rewards;
}
function genesisRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) {
if (_to <= startTime) {
return 0;
}
if (_from < startTime) {
_from = startTime;
}
uint256 fromWeek = diffDays(startTime, _from) / 7;
uint256 toWeek = diffDays(startTime, _to) / 7;
if (fromWeek == toWeek) {
return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
_to.sub(_from),
weeklyWeightPoints[fromWeek].genesisWtPoints)
.add(weeklyBonusPerSecond[address(genesisStaking)][fromWeek].mul(_to.sub(_from)));
}
rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
initialRemander,
weeklyWeightPoints[fromWeek].genesisWtPoints)
.add(weeklyBonusPerSecond[address(genesisStaking)][fromWeek].mul(initialRemander));
for (uint256 i = fromWeek+1; i < toWeek; i++) {
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i],
SECONDS_PER_WEEK,
weeklyWeightPoints[i].genesisWtPoints))
.add(weeklyBonusPerSecond[address(genesisStaking)][i].mul(SECONDS_PER_WEEK));
}
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek],
finalRemander,
weeklyWeightPoints[toWeek].genesisWtPoints))
.add(weeklyBonusPerSecond[address(genesisStaking)][toWeek].mul(finalRemander));
return rewards;
}
function genesisRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) {
if (_to <= startTime) {
return 0;
}
if (_from < startTime) {
_from = startTime;
}
uint256 fromWeek = diffDays(startTime, _from) / 7;
uint256 toWeek = diffDays(startTime, _to) / 7;
if (fromWeek == toWeek) {
return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
_to.sub(_from),
weeklyWeightPoints[fromWeek].genesisWtPoints)
.add(weeklyBonusPerSecond[address(genesisStaking)][fromWeek].mul(_to.sub(_from)));
}
rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
initialRemander,
weeklyWeightPoints[fromWeek].genesisWtPoints)
.add(weeklyBonusPerSecond[address(genesisStaking)][fromWeek].mul(initialRemander));
for (uint256 i = fromWeek+1; i < toWeek; i++) {
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i],
SECONDS_PER_WEEK,
weeklyWeightPoints[i].genesisWtPoints))
.add(weeklyBonusPerSecond[address(genesisStaking)][i].mul(SECONDS_PER_WEEK));
}
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek],
finalRemander,
weeklyWeightPoints[toWeek].genesisWtPoints))
.add(weeklyBonusPerSecond[address(genesisStaking)][toWeek].mul(finalRemander));
return rewards;
}
function genesisRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) {
if (_to <= startTime) {
return 0;
}
if (_from < startTime) {
_from = startTime;
}
uint256 fromWeek = diffDays(startTime, _from) / 7;
uint256 toWeek = diffDays(startTime, _to) / 7;
if (fromWeek == toWeek) {
return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
_to.sub(_from),
weeklyWeightPoints[fromWeek].genesisWtPoints)
.add(weeklyBonusPerSecond[address(genesisStaking)][fromWeek].mul(_to.sub(_from)));
}
rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
initialRemander,
weeklyWeightPoints[fromWeek].genesisWtPoints)
.add(weeklyBonusPerSecond[address(genesisStaking)][fromWeek].mul(initialRemander));
for (uint256 i = fromWeek+1; i < toWeek; i++) {
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i],
SECONDS_PER_WEEK,
weeklyWeightPoints[i].genesisWtPoints))
.add(weeklyBonusPerSecond[address(genesisStaking)][i].mul(SECONDS_PER_WEEK));
}
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek],
finalRemander,
weeklyWeightPoints[toWeek].genesisWtPoints))
.add(weeklyBonusPerSecond[address(genesisStaking)][toWeek].mul(finalRemander));
return rewards;
}
uint256 initialRemander = startTime.add((fromWeek+1).mul(SECONDS_PER_WEEK)).sub(_from);
function genesisRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) {
if (_to <= startTime) {
return 0;
}
if (_from < startTime) {
_from = startTime;
}
uint256 fromWeek = diffDays(startTime, _from) / 7;
uint256 toWeek = diffDays(startTime, _to) / 7;
if (fromWeek == toWeek) {
return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
_to.sub(_from),
weeklyWeightPoints[fromWeek].genesisWtPoints)
.add(weeklyBonusPerSecond[address(genesisStaking)][fromWeek].mul(_to.sub(_from)));
}
rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
initialRemander,
weeklyWeightPoints[fromWeek].genesisWtPoints)
.add(weeklyBonusPerSecond[address(genesisStaking)][fromWeek].mul(initialRemander));
for (uint256 i = fromWeek+1; i < toWeek; i++) {
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i],
SECONDS_PER_WEEK,
weeklyWeightPoints[i].genesisWtPoints))
.add(weeklyBonusPerSecond[address(genesisStaking)][i].mul(SECONDS_PER_WEEK));
}
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek],
finalRemander,
weeklyWeightPoints[toWeek].genesisWtPoints))
.add(weeklyBonusPerSecond[address(genesisStaking)][toWeek].mul(finalRemander));
return rewards;
}
uint256 finalRemander = _to.sub(toWeek.mul(SECONDS_PER_WEEK).add(startTime));
function parentRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) {
uint256 fromWeek = diffDays(startTime, _from) / 7;
uint256 toWeek = diffDays(startTime, _to) / 7;
if (fromWeek == toWeek) {
return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
_to.sub(_from),
weeklyWeightPoints[fromWeek].parentWtPoints)
.add(weeklyBonusPerSecond[address(parentStaking)][fromWeek].mul(_to.sub(_from)));
}
rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
initialRemander,
weeklyWeightPoints[fromWeek].parentWtPoints)
.add(weeklyBonusPerSecond[address(parentStaking)][fromWeek].mul(initialRemander));
for (uint256 i = fromWeek+1; i < toWeek; i++) {
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i],
SECONDS_PER_WEEK,
weeklyWeightPoints[i].parentWtPoints))
.add(weeklyBonusPerSecond[address(parentStaking)][i].mul(SECONDS_PER_WEEK));
}
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek],
finalRemander,
weeklyWeightPoints[toWeek].parentWtPoints))
.add(weeklyBonusPerSecond[address(parentStaking)][toWeek].mul(finalRemander));
return rewards;
}
function parentRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) {
uint256 fromWeek = diffDays(startTime, _from) / 7;
uint256 toWeek = diffDays(startTime, _to) / 7;
if (fromWeek == toWeek) {
return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
_to.sub(_from),
weeklyWeightPoints[fromWeek].parentWtPoints)
.add(weeklyBonusPerSecond[address(parentStaking)][fromWeek].mul(_to.sub(_from)));
}
rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
initialRemander,
weeklyWeightPoints[fromWeek].parentWtPoints)
.add(weeklyBonusPerSecond[address(parentStaking)][fromWeek].mul(initialRemander));
for (uint256 i = fromWeek+1; i < toWeek; i++) {
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i],
SECONDS_PER_WEEK,
weeklyWeightPoints[i].parentWtPoints))
.add(weeklyBonusPerSecond[address(parentStaking)][i].mul(SECONDS_PER_WEEK));
}
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek],
finalRemander,
weeklyWeightPoints[toWeek].parentWtPoints))
.add(weeklyBonusPerSecond[address(parentStaking)][toWeek].mul(finalRemander));
return rewards;
}
uint256 initialRemander = startTime.add((fromWeek+1).mul(SECONDS_PER_WEEK)).sub(_from);
function parentRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) {
uint256 fromWeek = diffDays(startTime, _from) / 7;
uint256 toWeek = diffDays(startTime, _to) / 7;
if (fromWeek == toWeek) {
return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
_to.sub(_from),
weeklyWeightPoints[fromWeek].parentWtPoints)
.add(weeklyBonusPerSecond[address(parentStaking)][fromWeek].mul(_to.sub(_from)));
}
rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
initialRemander,
weeklyWeightPoints[fromWeek].parentWtPoints)
.add(weeklyBonusPerSecond[address(parentStaking)][fromWeek].mul(initialRemander));
for (uint256 i = fromWeek+1; i < toWeek; i++) {
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i],
SECONDS_PER_WEEK,
weeklyWeightPoints[i].parentWtPoints))
.add(weeklyBonusPerSecond[address(parentStaking)][i].mul(SECONDS_PER_WEEK));
}
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek],
finalRemander,
weeklyWeightPoints[toWeek].parentWtPoints))
.add(weeklyBonusPerSecond[address(parentStaking)][toWeek].mul(finalRemander));
return rewards;
}
uint256 finalRemander = _to.sub(toWeek.mul(SECONDS_PER_WEEK).add(startTime));
function LPRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) {
uint256 fromWeek = diffDays(startTime, _from) / 7;
uint256 toWeek = diffDays(startTime, _to) / 7;
if (fromWeek == toWeek) {
return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
_to.sub(_from),
weeklyWeightPoints[fromWeek].lpWeightPoints)
.add(weeklyBonusPerSecond[address(lpStaking)][fromWeek].mul(_to.sub(_from)));
}
rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
initialRemander,
weeklyWeightPoints[fromWeek].lpWeightPoints)
.add(weeklyBonusPerSecond[address(lpStaking)][fromWeek].mul(initialRemander));
for (uint256 i = fromWeek+1; i < toWeek; i++) {
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i],
SECONDS_PER_WEEK,
weeklyWeightPoints[i].lpWeightPoints))
.add(weeklyBonusPerSecond[address(lpStaking)][i].mul(SECONDS_PER_WEEK));
}
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek],
finalRemander,
weeklyWeightPoints[toWeek].lpWeightPoints))
.add(weeklyBonusPerSecond[address(lpStaking)][toWeek].mul(finalRemander));
return rewards;
}
function LPRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) {
uint256 fromWeek = diffDays(startTime, _from) / 7;
uint256 toWeek = diffDays(startTime, _to) / 7;
if (fromWeek == toWeek) {
return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
_to.sub(_from),
weeklyWeightPoints[fromWeek].lpWeightPoints)
.add(weeklyBonusPerSecond[address(lpStaking)][fromWeek].mul(_to.sub(_from)));
}
rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
initialRemander,
weeklyWeightPoints[fromWeek].lpWeightPoints)
.add(weeklyBonusPerSecond[address(lpStaking)][fromWeek].mul(initialRemander));
for (uint256 i = fromWeek+1; i < toWeek; i++) {
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i],
SECONDS_PER_WEEK,
weeklyWeightPoints[i].lpWeightPoints))
.add(weeklyBonusPerSecond[address(lpStaking)][i].mul(SECONDS_PER_WEEK));
}
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek],
finalRemander,
weeklyWeightPoints[toWeek].lpWeightPoints))
.add(weeklyBonusPerSecond[address(lpStaking)][toWeek].mul(finalRemander));
return rewards;
}
uint256 initialRemander = startTime.add((fromWeek+1).mul(SECONDS_PER_WEEK)).sub(_from);
function LPRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) {
uint256 fromWeek = diffDays(startTime, _from) / 7;
uint256 toWeek = diffDays(startTime, _to) / 7;
if (fromWeek == toWeek) {
return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
_to.sub(_from),
weeklyWeightPoints[fromWeek].lpWeightPoints)
.add(weeklyBonusPerSecond[address(lpStaking)][fromWeek].mul(_to.sub(_from)));
}
rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek],
initialRemander,
weeklyWeightPoints[fromWeek].lpWeightPoints)
.add(weeklyBonusPerSecond[address(lpStaking)][fromWeek].mul(initialRemander));
for (uint256 i = fromWeek+1; i < toWeek; i++) {
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i],
SECONDS_PER_WEEK,
weeklyWeightPoints[i].lpWeightPoints))
.add(weeklyBonusPerSecond[address(lpStaking)][i].mul(SECONDS_PER_WEEK));
}
rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek],
finalRemander,
weeklyWeightPoints[toWeek].lpWeightPoints))
.add(weeklyBonusPerSecond[address(lpStaking)][toWeek].mul(finalRemander));
return rewards;
}
uint256 finalRemander = _to.sub(toWeek.mul(SECONDS_PER_WEEK).add(startTime));
function _updateGenesisRewards()
internal
returns(uint256 rewards)
{
rewards = genesisRewards(lastRewardTime, block.timestamp);
genesisRewardsPaid = genesisRewardsPaid.add(rewards);
require(rewardsToken.mint(address(genesisStaking), rewards));
}
function _updateParentRewards()
internal
returns(uint256 rewards)
{
rewards = parentRewards(lastRewardTime, block.timestamp);
parentRewardsPaid = parentRewardsPaid.add(rewards);
require(rewardsToken.mint(address(parentStaking), rewards));
}
function _updateLPRewards()
internal
returns(uint256 rewards)
{
rewards = LPRewards(lastRewardTime, block.timestamp);
lpRewardsPaid = lpRewardsPaid.add(rewards);
require(rewardsToken.mint(address(lpStaking), rewards));
}
function _rewardsFromPoints(
uint256 rate,
uint256 duration,
uint256 weight
)
internal
view
returns(uint256)
{
return rate.mul(duration)
.mul(weight)
.div(1e18)
.div(pointMultiplier);
}
function _updateWeightingAcc(uint256 gW, uint256 pW, uint256 mW) internal {
uint256 currentWeek = diffDays(startTime, block.timestamp) / 7;
uint256 lastRewardWeek = diffDays(startTime, lastRewardTime) / 7;
uint256 startCurrentWeek = startTime.add(currentWeek.mul(SECONDS_PER_WEEK));
if (weeklyWeightPoints[0].genesisWtPoints == 0
&& weeklyWeightPoints[0].parentWtPoints == 0
&& weeklyWeightPoints[0].lpWeightPoints == 0 ) {
Weights storage weights = weeklyWeightPoints[0];
weights.genesisWtPoints = gW;
weights.parentWtPoints = pW;
weights.lpWeightPoints = mW;
}
if (lastRewardWeek < currentWeek ) {
for (uint256 i = lastRewardWeek+1; i <= currentWeek; i++) {
Weights storage weights = weeklyWeightPoints[i];
weights.genesisWtPoints = gW;
weights.parentWtPoints = pW;
weights.lpWeightPoints = mW;
}
return;
}
weights.genesisWtPoints = _calcWeightPoints(weights.genesisWtPoints,gW,startCurrentWeek);
weights.parentWtPoints = _calcWeightPoints(weights.parentWtPoints,pW,startCurrentWeek);
weights.lpWeightPoints = _calcWeightPoints(weights.lpWeightPoints,mW,startCurrentWeek);
}
function _updateWeightingAcc(uint256 gW, uint256 pW, uint256 mW) internal {
uint256 currentWeek = diffDays(startTime, block.timestamp) / 7;
uint256 lastRewardWeek = diffDays(startTime, lastRewardTime) / 7;
uint256 startCurrentWeek = startTime.add(currentWeek.mul(SECONDS_PER_WEEK));
if (weeklyWeightPoints[0].genesisWtPoints == 0
&& weeklyWeightPoints[0].parentWtPoints == 0
&& weeklyWeightPoints[0].lpWeightPoints == 0 ) {
Weights storage weights = weeklyWeightPoints[0];
weights.genesisWtPoints = gW;
weights.parentWtPoints = pW;
weights.lpWeightPoints = mW;
}
if (lastRewardWeek < currentWeek ) {
for (uint256 i = lastRewardWeek+1; i <= currentWeek; i++) {
Weights storage weights = weeklyWeightPoints[i];
weights.genesisWtPoints = gW;
weights.parentWtPoints = pW;
weights.lpWeightPoints = mW;
}
return;
}
weights.genesisWtPoints = _calcWeightPoints(weights.genesisWtPoints,gW,startCurrentWeek);
weights.parentWtPoints = _calcWeightPoints(weights.parentWtPoints,pW,startCurrentWeek);
weights.lpWeightPoints = _calcWeightPoints(weights.lpWeightPoints,mW,startCurrentWeek);
}
function _updateWeightingAcc(uint256 gW, uint256 pW, uint256 mW) internal {
uint256 currentWeek = diffDays(startTime, block.timestamp) / 7;
uint256 lastRewardWeek = diffDays(startTime, lastRewardTime) / 7;
uint256 startCurrentWeek = startTime.add(currentWeek.mul(SECONDS_PER_WEEK));
if (weeklyWeightPoints[0].genesisWtPoints == 0
&& weeklyWeightPoints[0].parentWtPoints == 0
&& weeklyWeightPoints[0].lpWeightPoints == 0 ) {
Weights storage weights = weeklyWeightPoints[0];
weights.genesisWtPoints = gW;
weights.parentWtPoints = pW;
weights.lpWeightPoints = mW;
}
if (lastRewardWeek < currentWeek ) {
for (uint256 i = lastRewardWeek+1; i <= currentWeek; i++) {
Weights storage weights = weeklyWeightPoints[i];
weights.genesisWtPoints = gW;
weights.parentWtPoints = pW;
weights.lpWeightPoints = mW;
}
return;
}
weights.genesisWtPoints = _calcWeightPoints(weights.genesisWtPoints,gW,startCurrentWeek);
weights.parentWtPoints = _calcWeightPoints(weights.parentWtPoints,pW,startCurrentWeek);
weights.lpWeightPoints = _calcWeightPoints(weights.lpWeightPoints,mW,startCurrentWeek);
}
function _updateWeightingAcc(uint256 gW, uint256 pW, uint256 mW) internal {
uint256 currentWeek = diffDays(startTime, block.timestamp) / 7;
uint256 lastRewardWeek = diffDays(startTime, lastRewardTime) / 7;
uint256 startCurrentWeek = startTime.add(currentWeek.mul(SECONDS_PER_WEEK));
if (weeklyWeightPoints[0].genesisWtPoints == 0
&& weeklyWeightPoints[0].parentWtPoints == 0
&& weeklyWeightPoints[0].lpWeightPoints == 0 ) {
Weights storage weights = weeklyWeightPoints[0];
weights.genesisWtPoints = gW;
weights.parentWtPoints = pW;
weights.lpWeightPoints = mW;
}
if (lastRewardWeek < currentWeek ) {
for (uint256 i = lastRewardWeek+1; i <= currentWeek; i++) {
Weights storage weights = weeklyWeightPoints[i];
weights.genesisWtPoints = gW;
weights.parentWtPoints = pW;
weights.lpWeightPoints = mW;
}
return;
}
weights.genesisWtPoints = _calcWeightPoints(weights.genesisWtPoints,gW,startCurrentWeek);
weights.parentWtPoints = _calcWeightPoints(weights.parentWtPoints,pW,startCurrentWeek);
weights.lpWeightPoints = _calcWeightPoints(weights.lpWeightPoints,mW,startCurrentWeek);
}
Weights storage weights = weeklyWeightPoints[currentWeek];
function _calcWeightPoints(
uint256 prevWeight,
uint256 newWeight,
uint256 startCurrentWeek
)
internal
view
returns(uint256)
{
uint256 previousWeighting = prevWeight.mul(lastRewardTime.sub(startCurrentWeek));
uint256 currentWeighting = newWeight.mul(block.timestamp.sub(lastRewardTime));
return previousWeighting.add(currentWeighting)
.div(block.timestamp.sub(startCurrentWeek));
}
function _getReturnWeights(
uint256 _g,
uint256 _p,
uint256 _m
)
internal
view
returns(uint256,uint256,uint256)
{
uint256 d = _getReturnParentWeight(_g,_p,_m);
uint256 norm = _g.add(_m)
.add(d.mul(_p)
.div(1e18));
return (_g.mul(1e18).mul(pointMultiplier).div(norm),
d.mul(_p).mul(pointMultiplier).div(norm),
_m.mul(1e18).mul(pointMultiplier).div(norm));
}
function _getReturnParentWeight(
uint256 _g,
uint256 _p,
uint256 _m
)
internal
view
returns(uint256 d)
{
bytes16 order;
if (_p <= _g.add(_m)) {
d = 1e18;
bytes16 ten18 = ABDKMathQuad.fromUInt(10**18);
bytes16 ln10 = ABDKMathQuad.fromUInt(23026).div(ABDKMathQuad.fromUInt(10000));
uint256 i2 = _p.mul(1e18).div(_g.add(_m));
bytes16 i = ABDKMathQuad.fromUInt(i2).div(ten18);
order = ABDKMathQuad.ln(i).div(ln10);
d = ABDKMathQuad.toUInt(ABDKMathQuad.exp(ABDKMathQuad.neg(order)).mul(ten18));
}
return d;
}
function _getReturnParentWeight(
uint256 _g,
uint256 _p,
uint256 _m
)
internal
view
returns(uint256 d)
{
bytes16 order;
if (_p <= _g.add(_m)) {
d = 1e18;
bytes16 ten18 = ABDKMathQuad.fromUInt(10**18);
bytes16 ln10 = ABDKMathQuad.fromUInt(23026).div(ABDKMathQuad.fromUInt(10000));
uint256 i2 = _p.mul(1e18).div(_g.add(_m));
bytes16 i = ABDKMathQuad.fromUInt(i2).div(ten18);
order = ABDKMathQuad.ln(i).div(ln10);
d = ABDKMathQuad.toUInt(ABDKMathQuad.exp(ABDKMathQuad.neg(order)).mul(ten18));
}
return d;
}
} else {
function recoverERC20(
address tokenAddress,
uint256 tokenAmount
)
public
{
require(
accessControls.hasAdminRole(msg.sender),
"DigitalaxRewards.recoverERC20: Sender must be admin"
);
require(
tokenAddress != address(rewardsToken),
"Cannot withdraw the rewards token"
);
IERC20(tokenAddress).transfer(msg.sender, tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
function getGenesisStakedEthTotal()
public
view
returns(uint256)
{
return genesisStaking.stakedEthTotal();
}
function getCurrentGenesisWtPoints()
public
view
returns(uint256)
{
uint256 currentWeek = diffDays(startTime, block.timestamp) / 7;
return weeklyWeightPoints[currentWeek].genesisWtPoints;
}
function getCurrentWeek()
public
view
returns(uint256)
{
return diffDays(startTime, block.timestamp) / 7;
}
function getCurrentParentWtPoints()
public
view
returns(uint256)
{
uint256 currentWeek = diffDays(startTime, block.timestamp) / 7;
return weeklyWeightPoints[currentWeek].parentWtPoints;
}
function getCurrentLpWeightPoints()
public
view
returns(uint256)
{
uint256 currentWeek = diffDays(startTime, block.timestamp) / 7;
return weeklyWeightPoints[currentWeek].lpWeightPoints;
}
function getParentStakedEthTotal()
public
view
returns(uint256)
{
return parentStaking.stakedEthTotal();
}
} | 16,887,937 | [
1,
4625,
348,
7953,
560,
30,
225,
4860,
1854,
516,
283,
6397,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
11678,
7053,
651,
17631,
14727,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
10336,
3398,
10477,
24483,
364,
1731,
2313,
31,
203,
203,
203,
565,
30215,
37,
1071,
283,
6397,
1345,
31,
203,
565,
11678,
7053,
651,
16541,
87,
1071,
2006,
16795,
31,
203,
565,
11678,
649,
651,
510,
6159,
1071,
21906,
510,
6159,
31,
203,
565,
11678,
649,
651,
510,
6159,
1071,
982,
510,
6159,
31,
203,
565,
11678,
649,
651,
510,
6159,
1071,
12423,
510,
6159,
31,
203,
203,
565,
2254,
5034,
5381,
1634,
23365,
273,
1728,
73,
1578,
31,
203,
565,
2254,
5034,
5381,
17209,
67,
3194,
67,
10339,
273,
4248,
380,
4752,
380,
4752,
31,
203,
565,
2254,
5034,
5381,
17209,
67,
3194,
67,
20274,
273,
2371,
380,
4248,
380,
4752,
380,
4752,
31,
203,
377,
203,
565,
2874,
261,
11890,
5034,
516,
2254,
5034,
13,
1071,
4860,
715,
17631,
14727,
2173,
8211,
31,
203,
565,
2874,
261,
2867,
516,
2874,
12,
11890,
5034,
516,
2254,
5034,
3719,
1071,
4860,
715,
38,
22889,
2173,
8211,
31,
203,
203,
565,
2254,
5034,
1071,
8657,
31,
203,
565,
2254,
5034,
1071,
1142,
17631,
1060,
950,
31,
203,
565,
2254,
5034,
1071,
2078,
17631,
14727,
16507,
350,
31,
203,
203,
565,
2254,
5034,
1071,
21906,
17631,
14727,
16507,
350,
31,
203,
565,
2254,
5034,
1071,
982,
17631,
14727,
16507,
350,
31,
203,
565,
2254,
5034,
1071,
12423,
17631,
14727,
16507,
350,
31,
203,
203,
203,
565,
1958,
15437,
87,
288,
203,
3639,
2254,
5034,
21906,
59,
88,
5636,
31,
203,
3639,
2254,
5034,
982,
59,
88,
5636,
31,
203,
3639,
2254,
5034,
12423,
6544,
5636,
31,
203,
565,
289,
203,
203,
203,
565,
871,
534,
359,
1060,
8602,
12,
2867,
8808,
3091,
16,
2254,
5034,
19890,
1769,
203,
565,
871,
534,
359,
1060,
1669,
11050,
12,
2867,
8808,
3091,
16,
2254,
5034,
19890,
1769,
203,
565,
871,
868,
16810,
12,
2867,
1147,
16,
2254,
5034,
3844,
1769,
203,
203,
377,
203,
3639,
30215,
37,
389,
266,
6397,
1345,
16,
203,
3639,
11678,
7053,
651,
16541,
87,
389,
3860,
16795,
16,
203,
3639,
11678,
649,
651,
510,
6159,
389,
4507,
16786,
510,
6159,
16,
203,
3639,
11678,
649,
651,
510,
6159,
389,
2938,
510,
6159,
16,
203,
3639,
11678,
649,
651,
510,
6159,
389,
9953,
510,
6159,
16,
203,
3639,
2254,
5034,
389,
1937,
950,
203,
565,
262,
203,
3639,
1071,
203,
565,
2874,
261,
11890,
5034,
516,
15437,
87,
13,
1071,
4860,
715,
6544,
5636,
31,
203,
203,
565,
3885,
12,
203,
565,
288,
203,
3639,
283,
6397,
1345,
273,
389,
266,
6397,
1345,
31,
203,
3639,
2006,
16795,
273,
389,
3860,
16795,
31,
203,
3639,
21906,
510,
6159,
273,
389,
4507,
16786,
510,
6159,
31,
203,
3639,
982,
510,
6159,
273,
389,
2938,
510,
6159,
31,
203,
3639,
12423,
510,
6159,
273,
389,
9953,
510,
6159,
31,
203,
3639,
8657,
273,
389,
1937,
950,
31,
203,
3639,
1142,
17631,
1060,
950,
273,
389,
1937,
950,
31,
203,
565,
289,
203,
203,
565,
445,
444,
13649,
12,
203,
3639,
2254,
5034,
389,
1937,
950,
203,
565,
262,
203,
3639,
1071,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
2006,
16795,
18,
5332,
4446,
2996,
12,
3576,
18,
15330,
3631,
203,
5411,
315,
4907,
7053,
651,
17631,
14727,
18,
542,
13649,
30,
15044,
1297,
506,
3981,
6,
203,
3639,
11272,
203,
3639,
8657,
273,
389,
1937,
950,
31,
203,
565,
289,
203,
203,
565,
445,
444,
7642,
16786,
510,
6159,
12,
203,
3639,
1758,
389,
4793,
203,
565,
262,
203,
3639,
1071,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
2006,
16795,
18,
5332,
4446,
2996,
12,
3576,
18,
15330,
3631,
203,
5411,
315,
4907,
7053,
651,
17631,
14727,
18,
542,
7642,
16786,
510,
6159,
30,
15044,
1297,
506,
3981,
6,
203,
3639,
11272,
203,
3639,
2583,
24899,
4793,
480,
1758,
12,
2938,
510,
6159,
10019,
203,
3639,
2583,
24899,
4793,
480,
1758,
12,
9953,
510,
6159,
10019,
203,
3639,
21906,
510,
6159,
273,
11678,
649,
651,
510,
6159,
24899,
4793,
1769,
203,
565,
289,
203,
203,
565,
445,
12548,
510,
6159,
12,
203,
3639,
1758,
389,
4793,
203,
565,
262,
203,
3639,
1071,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
2006,
16795,
18,
5332,
4446,
2996,
12,
3576,
18,
15330,
3631,
203,
5411,
315,
4907,
7053,
651,
17631,
14727,
18,
542,
3054,
510,
6159,
30,
15044,
1297,
506,
3981,
6,
203,
3639,
11272,
203,
3639,
2583,
24899,
4793,
480,
1758,
12,
4507,
16786,
510,
6159,
10019,
203,
3639,
2583,
24899,
4793,
480,
1758,
12,
9953,
510,
6159,
10019,
203,
3639,
982,
510,
6159,
273,
11678,
649,
651,
510,
6159,
24899,
4793,
1769,
203,
565,
289,
203,
203,
565,
445,
444,
14461,
510,
6159,
12,
203,
3639,
1758,
389,
4793,
203,
565,
262,
203,
3639,
1071,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
2006,
16795,
18,
5332,
4446,
2996,
12,
3576,
18,
15330,
3631,
203,
5411,
315,
4907,
7053,
651,
17631,
14727,
18,
542,
14461,
510,
6159,
30,
15044,
1297,
506,
3981,
6,
203,
3639,
11272,
203,
3639,
2583,
24899,
4793,
480,
1758,
12,
2938,
510,
6159,
10019,
203,
3639,
2583,
24899,
4793,
480,
1758,
12,
4507,
16786,
510,
6159,
10019,
203,
3639,
12423,
510,
6159,
273,
11678,
649,
651,
510,
6159,
24899,
4793,
1769,
203,
565,
289,
7010,
203,
565,
445,
444,
17631,
14727,
12,
203,
3639,
2254,
5034,
8526,
3778,
19890,
6630,
87,
16,
203,
3639,
2254,
5034,
8526,
3778,
30980,
203,
565,
262,
203,
3639,
1071,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
2006,
16795,
18,
5332,
4446,
2996,
12,
3576,
18,
15330,
3631,
203,
5411,
315,
4907,
7053,
651,
17631,
14727,
18,
542,
17631,
14727,
30,
15044,
1297,
506,
3981,
6,
203,
3639,
11272,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
19890,
6630,
87,
18,
2469,
31,
277,
27245,
288,
203,
5411,
2254,
5034,
4860,
273,
19890,
6630,
87,
63,
77,
15533,
203,
5411,
2254,
5034,
3844,
273,
30980,
63,
77,
8009,
16411,
12,
1153,
23365,
13,
203,
4766,
4202,
263,
2892,
12,
11609,
67,
3194,
67,
20274,
13,
203,
4766,
4202,
263,
2892,
12,
1153,
23365,
1769,
203,
2
] |
pragma solidity 0.4.24;
contract InterbetCore {
/* Global constants */
uint constant oddsDecimals = 2; // Max. decimal places of odds
uint constant feeRateDecimals = 1; // Max. decimal places of fee rate
uint public minMakerBetFund = 100 * 1 finney; // Minimum fund of a maker bet
uint public maxAllowedTakerBetsPerMakerBet = 100; // Limit the number of taker-bets in 1 maker-bet
uint public minAllowedStakeInPercentage = 1; // 100 ÷ maxAllowedTakerBetsPerMakerBet
uint public baseVerifierFee = 1 finney; // Ensure verifier has some minimal profit to cover their gas cost at least
/* Owner and admins */
address private owner;
mapping(address => bool) private admins;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function changeOwner(address newOwner) external onlyOwner {
owner = newOwner;
}
function addAdmin(address addr) external onlyOwner {
admins[addr] = true;
}
function removeAdmin(address addr) external onlyOwner {
admins[addr] = false;
}
modifier onlyAdmin() {
require(admins[msg.sender] == true);
_;
}
function changeMinMakerBetFund(uint weis) external onlyAdmin {
minMakerBetFund = mul(weis, 1 wei);
}
function changeAllowedTakerBetsPerMakerBet(uint maxCount, uint minPercentage) external onlyAdmin {
maxAllowedTakerBetsPerMakerBet = maxCount;
minAllowedStakeInPercentage = minPercentage;
}
function changeBaseVerifierFee(uint weis) external onlyAdmin {
baseVerifierFee = mul(weis, 1 wei);
}
/* Events */
event LogUpdateVerifier(address indexed addr, uint oldFeeRate, uint newFeeRate);
event LogMakeBet(uint indexed makerBetId, address indexed maker);
event LogAddFund(uint indexed makerBetId, address indexed maker, uint oldTotalFund, uint newTotalFund);
event LogUpdateOdds(uint indexed makerBetId, address indexed maker, uint oldOdds, uint newOdds);
event LogPauseBet(uint indexed makerBetId, address indexed maker);
event LogReopenBet(uint indexed makerBetId, address indexed maker);
event LogCloseBet(uint indexed makerBetId, address indexed maker);
event LogTakeBet(uint indexed makerBetId, address indexed maker, uint indexed takerBetId, address taker);
event LogSettleBet(uint indexed makerBetId, address indexed maker);
event LogWithdraw(uint indexed makerBetId, address indexed maker, address indexed addr);
/* Betting Core */
enum BetStatus {
Open,
Paused,
Closed,
Settled
}
enum BetOutcome {
NotSettled,
MakerWin,
TakerWin,
Draw,
Canceled
}
struct MakerBet {
uint makerBetId;
address maker;
uint odds;
uint totalFund;
Verifier trustedVerifier;
uint expiry;
BetStatus status;
uint reservedFund;
uint takerBetsCount;
uint totalStake;
TakerBet[] takerBets;
BetOutcome outcome;
bool makerFundWithdrawn;
bool trustedVerifierFeeSent;
}
struct TakerBet {
uint takerBetId;
address taker;
uint odds;
uint stake;
bool settled;
}
struct Verifier {
address addr;
uint feeRate;
}
uint public makerBetsCount;
mapping(uint => mapping(address => MakerBet)) private makerBets;
mapping(address => Verifier) private verifiers;
constructor() public {
owner = msg.sender;
makerBetsCount = 0;
}
function () external payable {
revert();
}
/// Update verifier's data
function updateVerifier(uint feeRate) external {
require(feeRate >= 0 && feeRate <= ((10 ** feeRateDecimals) * 100));
Verifier storage verifier = verifiers[msg.sender];
uint oldFeeRate = verifier.feeRate;
verifier.addr = msg.sender;
verifier.feeRate = feeRate;
emit LogUpdateVerifier(msg.sender, oldFeeRate, feeRate);
}
/// Make a bet
function makeBet(uint makerBetId, uint odds, address trustedVerifier, uint trustedVerifierFeeRate, uint expiry) external payable {
uint fund = sub(msg.value, baseVerifierFee);
require(fund >= minMakerBetFund);
require(odds > (10 ** oddsDecimals) && odds < ((10 ** 8) * (10 ** oddsDecimals)));
require(expiry > now);
MakerBet storage makerBet = makerBets[makerBetId][msg.sender];
require(makerBet.makerBetId == 0);
Verifier memory verifier = verifiers[trustedVerifier];
require(verifier.addr != address(0x0));
require(trustedVerifierFeeRate == verifier.feeRate);
makerBet.makerBetId = makerBetId;
makerBet.maker = msg.sender;
makerBet.odds = odds;
makerBet.totalFund = fund;
makerBet.trustedVerifier = Verifier(verifier.addr, verifier.feeRate);
makerBet.expiry = expiry;
makerBet.status = BetStatus.Open;
makerBet.reservedFund = 0;
makerBet.takerBetsCount = 0;
makerBet.totalStake = 0;
makerBetsCount++;
emit LogMakeBet(makerBetId, msg.sender);
}
/// Increase total fund of a bet
function addFund(uint makerBetId) external payable {
MakerBet storage makerBet = makerBets[makerBetId][msg.sender];
require(makerBet.makerBetId != 0);
require(now < makerBet.expiry);
require(makerBet.status == BetStatus.Open || makerBet.status == BetStatus.Paused);
require(msg.sender == makerBet.maker);
require(msg.value > 0);
uint oldTotalFund = makerBet.totalFund;
makerBet.totalFund = add(makerBet.totalFund, msg.value);
emit LogAddFund(makerBetId, msg.sender, oldTotalFund, makerBet.totalFund);
}
/// Update odds of a bet
function updateOdds(uint makerBetId, uint odds) external {
require(odds > (10 ** oddsDecimals) && odds < ((10 ** 8) * (10 ** oddsDecimals)));
MakerBet storage makerBet = makerBets[makerBetId][msg.sender];
require(makerBet.makerBetId != 0);
require(now < makerBet.expiry);
require(makerBet.status == BetStatus.Open || makerBet.status == BetStatus.Paused);
require(msg.sender == makerBet.maker);
require(odds != makerBet.odds);
uint oldOdds = makerBet.odds;
makerBet.odds = odds;
emit LogUpdateOdds(makerBetId, msg.sender, oldOdds, makerBet.odds);
}
/// Pause a bet
function pauseBet(uint makerBetId) external {
MakerBet storage makerBet = makerBets[makerBetId][msg.sender];
require(makerBet.makerBetId != 0);
require(makerBet.status == BetStatus.Open);
require(msg.sender == makerBet.maker);
makerBet.status = BetStatus.Paused;
emit LogPauseBet(makerBetId, msg.sender);
}
/// Reopen a bet
function reopenBet(uint makerBetId) external {
MakerBet storage makerBet = makerBets[makerBetId][msg.sender];
require(makerBet.makerBetId != 0);
require(makerBet.status == BetStatus.Paused);
require(msg.sender == makerBet.maker);
makerBet.status = BetStatus.Open;
emit LogReopenBet(makerBetId, msg.sender);
}
/// Close a bet and withdraw unused fund
function closeBet(uint makerBetId) external {
MakerBet storage makerBet = makerBets[makerBetId][msg.sender];
require(makerBet.makerBetId != 0);
require(makerBet.status == BetStatus.Open || makerBet.status == BetStatus.Paused);
require(msg.sender == makerBet.maker);
makerBet.status = BetStatus.Closed;
// refund unused fund to maker
uint unusedFund = sub(makerBet.totalFund, makerBet.reservedFund);
if (unusedFund > 0) {
makerBet.totalFund = makerBet.reservedFund;
uint refundAmount = unusedFund;
if (makerBet.totalStake == 0) {
refundAmount = add(refundAmount, baseVerifierFee); // Refund base verifier fee too if no taker-bets, because verifier do not need to settle the bet with no takers
makerBet.makerFundWithdrawn = true;
}
if (!makerBet.maker.send(refundAmount)) {
makerBet.totalFund = add(makerBet.totalFund, unusedFund);
makerBet.status = BetStatus.Paused;
makerBet.makerFundWithdrawn = false;
} else {
emit LogCloseBet(makerBetId, msg.sender);
}
} else {
emit LogCloseBet(makerBetId, msg.sender);
}
}
/// Take a bet
function takeBet(uint makerBetId, address maker, uint odds, uint takerBetId) external payable {
require(msg.sender != maker);
require(msg.value > 0);
MakerBet storage makerBet = makerBets[makerBetId][maker];
require(makerBet.makerBetId != 0);
require(msg.sender != makerBet.trustedVerifier.addr);
require(now < makerBet.expiry);
require(makerBet.status == BetStatus.Open);
require(makerBet.odds == odds);
// Avoid too many taker-bets in one maker-bet
require(makerBet.takerBetsCount < maxAllowedTakerBetsPerMakerBet);
// Avoid too many tiny bets
uint minAllowedStake = mul(mul(makerBet.totalFund, (10 ** oddsDecimals)), minAllowedStakeInPercentage) / sub(odds, (10 ** oddsDecimals)) / 100;
uint maxAvailableStake = mul(sub(makerBet.totalFund, makerBet.reservedFund), (10 ** oddsDecimals)) / sub(odds, (10 ** oddsDecimals));
if (maxAvailableStake >= minAllowedStake) {
require(msg.value >= minAllowedStake);
} else {
require(msg.value >= sub(maxAvailableStake, (maxAvailableStake / 10)) && msg.value <= maxAvailableStake);
}
// If remaining fund is not enough, send the money back.
require(msg.value <= maxAvailableStake);
makerBet.takerBets.length++;
makerBet.takerBets[makerBet.takerBetsCount] = TakerBet(takerBetId, msg.sender, odds, msg.value, false);
makerBet.reservedFund = add(makerBet.reservedFund, mul(msg.value, sub(odds, (10 ** oddsDecimals))) / (10 ** oddsDecimals));
makerBet.totalStake = add(makerBet.totalStake, msg.value);
makerBet.takerBetsCount++;
emit LogTakeBet(makerBetId, maker, takerBetId, msg.sender);
}
/// Payout to maker
function payMaker(MakerBet storage makerBet) private returns (bool fullyWithdrawn) {
fullyWithdrawn = false;
if (!makerBet.makerFundWithdrawn) {
makerBet.makerFundWithdrawn = true;
uint payout = 0;
if (makerBet.outcome == BetOutcome.MakerWin) {
uint trustedVerifierFeeMakerWin = mul(makerBet.totalStake, makerBet.trustedVerifier.feeRate) / ((10 ** feeRateDecimals) * 100);
payout = sub(add(makerBet.totalFund, makerBet.totalStake), trustedVerifierFeeMakerWin);
} else if (makerBet.outcome == BetOutcome.TakerWin) {
payout = sub(makerBet.totalFund, makerBet.reservedFund);
} else if (makerBet.outcome == BetOutcome.Draw || makerBet.outcome == BetOutcome.Canceled) {
payout = makerBet.totalFund;
}
if (payout > 0) {
fullyWithdrawn = true;
if (!makerBet.maker.send(payout)) {
makerBet.makerFundWithdrawn = false;
fullyWithdrawn = false;
}
}
}
return fullyWithdrawn;
}
/// Payout to taker
function payTaker(MakerBet storage makerBet, address taker) private returns (bool fullyWithdrawn) {
fullyWithdrawn = false;
uint payout = 0;
for (uint betIndex = 0; betIndex < makerBet.takerBetsCount; betIndex++) {
if (makerBet.takerBets[betIndex].taker == taker) {
if (!makerBet.takerBets[betIndex].settled) {
makerBet.takerBets[betIndex].settled = true;
if (makerBet.outcome == BetOutcome.MakerWin) {
continue;
} else if (makerBet.outcome == BetOutcome.TakerWin) {
uint netProfit = mul(mul(makerBet.takerBets[betIndex].stake, sub(makerBet.takerBets[betIndex].odds, (10 ** oddsDecimals))), sub(((10 ** feeRateDecimals) * 100), makerBet.trustedVerifier.feeRate)) / (10 ** oddsDecimals) / ((10 ** feeRateDecimals) * 100);
payout = add(payout, add(makerBet.takerBets[betIndex].stake, netProfit));
} else if (makerBet.outcome == BetOutcome.Draw || makerBet.outcome == BetOutcome.Canceled) {
payout = add(payout, makerBet.takerBets[betIndex].stake);
}
}
}
}
if (payout > 0) {
fullyWithdrawn = true;
if (!taker.send(payout)) {
fullyWithdrawn = false;
for (uint betIndex2 = 0; betIndex2 < makerBet.takerBetsCount; betIndex2++) {
if (makerBet.takerBets[betIndex2].taker == taker) {
if (makerBet.takerBets[betIndex2].settled) {
makerBet.takerBets[betIndex2].settled = false;
}
}
}
}
}
return fullyWithdrawn;
}
/// Payout to verifier
function payVerifier(MakerBet storage makerBet) private returns (bool fullyWithdrawn) {
fullyWithdrawn = false;
if (!makerBet.trustedVerifierFeeSent) {
makerBet.trustedVerifierFeeSent = true;
uint payout = 0;
if (makerBet.outcome == BetOutcome.MakerWin) {
uint trustedVerifierFeeMakerWin = mul(makerBet.totalStake, makerBet.trustedVerifier.feeRate) / ((10 ** feeRateDecimals) * 100);
payout = add(baseVerifierFee, trustedVerifierFeeMakerWin);
} else if (makerBet.outcome == BetOutcome.TakerWin) {
uint trustedVerifierFeeTakerWin = mul(makerBet.reservedFund, makerBet.trustedVerifier.feeRate) / ((10 ** feeRateDecimals) * 100);
payout = add(baseVerifierFee, trustedVerifierFeeTakerWin);
} else if (makerBet.outcome == BetOutcome.Draw || makerBet.outcome == BetOutcome.Canceled) {
payout = baseVerifierFee;
}
if (payout > 0) {
fullyWithdrawn = true;
if (!makerBet.trustedVerifier.addr.send(payout)) {
makerBet.trustedVerifierFeeSent = false;
fullyWithdrawn = false;
}
}
}
return fullyWithdrawn;
}
/// Settle a bet by trusted verifier
function settleBet(uint makerBetId, address maker, uint outcome) external {
require(outcome == 1 || outcome == 2 || outcome == 3 || outcome == 4);
MakerBet storage makerBet = makerBets[makerBetId][maker];
require(makerBet.makerBetId != 0);
require(msg.sender == makerBet.trustedVerifier.addr);
require(makerBet.totalStake > 0);
require(makerBet.status != BetStatus.Settled);
BetOutcome betOutcome = BetOutcome(outcome);
makerBet.outcome = betOutcome;
makerBet.status = BetStatus.Settled;
payMaker(makerBet);
payVerifier(makerBet);
emit LogSettleBet(makerBetId, maker);
}
/// Manual withdraw fund from a bet after outcome is set
function withdraw(uint makerBetId, address maker) external {
MakerBet storage makerBet = makerBets[makerBetId][maker];
require(makerBet.makerBetId != 0);
require(makerBet.outcome != BetOutcome.NotSettled);
require(makerBet.status == BetStatus.Settled);
bool fullyWithdrawn = false;
if (msg.sender == maker) {
fullyWithdrawn = payMaker(makerBet);
} else if (msg.sender == makerBet.trustedVerifier.addr) {
fullyWithdrawn = payVerifier(makerBet);
} else {
fullyWithdrawn = payTaker(makerBet, msg.sender);
}
if (fullyWithdrawn) {
emit LogWithdraw(makerBetId, maker, msg.sender);
}
}
/* External views */
function getOwner() external view returns(address) {
return owner;
}
function isAdmin(address addr) external view returns(bool) {
return admins[addr];
}
function getVerifier(address addr) external view returns(address, uint) {
Verifier memory verifier = verifiers[addr];
return (verifier.addr, verifier.feeRate);
}
function getMakerBetBasicInfo(uint makerBetId, address maker) external view returns(uint, address, address, uint, uint) {
MakerBet memory makerBet = makerBets[makerBetId][maker];
return (makerBet.makerBetId, makerBet.maker, makerBet.trustedVerifier.addr, makerBet.trustedVerifier.feeRate, makerBet.expiry);
}
function getMakerBetDetails(uint makerBetId, address maker) external view returns(uint, BetStatus, uint, uint, uint, uint, uint, BetOutcome, bool, bool) {
MakerBet memory makerBet = makerBets[makerBetId][maker];
return (makerBet.makerBetId, makerBet.status, makerBet.odds, makerBet.totalFund, makerBet.reservedFund, makerBet.takerBetsCount, makerBet.totalStake, makerBet.outcome, makerBet.makerFundWithdrawn, makerBet.trustedVerifierFeeSent);
}
function getTakerBet(uint makerBetId, address maker, uint takerBetId, address taker) external view returns(uint, address, uint, uint, bool) {
MakerBet memory makerBet = makerBets[makerBetId][maker];
for (uint betIndex = 0; betIndex < makerBet.takerBetsCount; betIndex++) {
TakerBet memory takerBet = makerBet.takerBets[betIndex];
if (takerBet.takerBetId == takerBetId && takerBet.taker == taker) {
return (takerBet.takerBetId, takerBet.taker, takerBet.odds, takerBet.stake, takerBet.settled);
}
}
}
/* Math utilities */
function mul(uint256 _a, uint256 _b) private pure returns(uint256 c) {
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
function sub(uint256 _a, uint256 _b) private pure returns(uint256) {
assert(_b <= _a);
return _a - _b;
}
function add(uint256 _a, uint256 _b) private pure returns(uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
} | Update odds of a bet | function updateOdds(uint makerBetId, uint odds) external {
require(odds > (10 ** oddsDecimals) && odds < ((10 ** 8) * (10 ** oddsDecimals)));
MakerBet storage makerBet = makerBets[makerBetId][msg.sender];
require(makerBet.makerBetId != 0);
require(now < makerBet.expiry);
require(makerBet.status == BetStatus.Open || makerBet.status == BetStatus.Paused);
require(msg.sender == makerBet.maker);
require(odds != makerBet.odds);
uint oldOdds = makerBet.odds;
makerBet.odds = odds;
emit LogUpdateOdds(makerBetId, msg.sender, oldOdds, makerBet.odds);
}
| 2,540,189 | [
1,
4625,
348,
7953,
560,
30,
225,
2315,
14800,
87,
434,
279,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
51,
449,
87,
12,
11890,
312,
6388,
38,
278,
548,
16,
2254,
14800,
87,
13,
3903,
288,
203,
377,
202,
6528,
12,
369,
2377,
405,
261,
2163,
2826,
14800,
87,
31809,
13,
597,
14800,
87,
411,
14015,
2163,
2826,
1725,
13,
380,
261,
2163,
2826,
14800,
87,
31809,
3719,
1769,
203,
203,
202,
202,
12373,
38,
278,
2502,
312,
6388,
38,
278,
273,
312,
6388,
38,
2413,
63,
29261,
38,
278,
548,
6362,
3576,
18,
15330,
15533,
203,
202,
202,
6528,
12,
29261,
38,
278,
18,
29261,
38,
278,
548,
480,
374,
1769,
203,
203,
202,
202,
6528,
12,
3338,
411,
312,
6388,
38,
278,
18,
22409,
1769,
203,
203,
377,
202,
6528,
12,
29261,
38,
278,
18,
2327,
422,
605,
278,
1482,
18,
3678,
747,
312,
6388,
38,
278,
18,
2327,
422,
605,
278,
1482,
18,
28590,
1769,
203,
203,
377,
202,
6528,
12,
3576,
18,
15330,
422,
312,
6388,
38,
278,
18,
29261,
1769,
203,
203,
377,
202,
6528,
12,
369,
2377,
480,
312,
6388,
38,
278,
18,
369,
2377,
1769,
203,
203,
377,
202,
11890,
1592,
51,
449,
87,
273,
312,
6388,
38,
278,
18,
369,
2377,
31,
203,
203,
377,
202,
29261,
38,
278,
18,
369,
2377,
273,
14800,
87,
31,
203,
203,
377,
202,
18356,
1827,
1891,
51,
449,
87,
12,
29261,
38,
278,
548,
16,
1234,
18,
15330,
16,
1592,
51,
449,
87,
16,
312,
6388,
38,
278,
18,
369,
2377,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x05099C7CAeD7A1aF46F946DC79b618285047D991/sources/contracts/Dopamine.sol | remove limits after token is stable | function removeLimits() external onlyOwner {
limitsActive = false;
}
| 9,737,928 | [
1,
4625,
348,
7953,
560,
30,
225,
1206,
8181,
1839,
1147,
353,
14114,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
12768,
1435,
3903,
1338,
5541,
288,
203,
3639,
8181,
3896,
273,
629,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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
// version of Dec 30, 2020
pragma solidity >=0.4.22 <0.8.0;
/* Order of contract elements
1. Pragma statements
2. Import statements
3. Interfaces
4. Libraries
5. Contracts
*/
/**
@title Pepito. Demo dApp for Machu Picchu. Also Final Project of
@author Vu Tien Khang
@notice Pepito is a Caribbian corsair. He can create up to 512 PepitoDisguise
@notice Pepito's function is similar to ENS Registry.sol, PepitoDisguise is similar to ENS Resolver.sol
@dev Pepito's Circuit Breaker stops creating disguises if Hernadez de La Banane discovers the trick :-)
@dev The circuit breaker is called to halt everything in case of serious unsolved contract exploit
@dev contract Pepito is a factory of disguises.
@dev - the main interest of a factory is to maintain an array or mapping of addresses of child contracts
@dev - specially useful for persons-in-need because their contract will be their virtual secretary
@dev and will maintain their balance of tokens
@dev and will execute the few orders sent via SMS by the persons-in-need
@dev Pepito contract only manages the array of addresses of disguise smart contract
@dev Remix-compiled successfully 2020-12-30
*/
import "./PepitoDisguise.sol";
import "../client/node_modules/@openzeppelin/contracts/math/SafeMath.sol";
//import "./SafeMath.sol"; // used to compile in Remix
contract Pepito {
using SafeMath for uint256;
/* order of statements inside de contract
1. State variables
2. Struct, Arrays or Enums
3. Events
4. Function Modifiers
5. Constructor
6. Fallback — Receive function
7. External visible functions
8. Public visible functions
9. Internal visible functions
10. Private visible functions
order of function modifiers
1. Visibility
2. Mutability
3. Virtual
4. Override
5. Custom modifiers
*/
bool public stopped; /// @dev the circuit breaker
address public owner; /// @dev account that deployed Pepito
uint256 public initialBalance; /// @dev initial balance of all disguises
uint256 public disguiseCount; /// @dev running number of disguises in array pepitoDisguiseAddresses
address[512] public pepitoDisguiseContracts; /// @dev array of addresses of contracts pepitoDisguise
/// @dev array is used because disguises will be iterated and displayed
/// @dev mapping may be used when disguises are transposed into people-in-need that won't be iterated
/// @dev for the demo, we limit array size to 512; in real, disguises will be in IPFS database w/o number limit
event PepitoDisguiseCreated(uint256 disguiseCount, address addressDisguise);
modifier isAdmin() {
require(owner == msg.sender); /// @dev the caller of the function must be Pepito
_;
}
modifier stopInEmergency() { /// @dev the caller of the breaker must be Pepito
if(!stopped) _;
}
modifier onlyInEmergency() { /// @dev the caller of the breaker must be Pepito
if(stopped) _;
}
constructor() public {
stopped = false;
owner = msg.sender; /// @dev the owner is the EOA that deployed Pepito
initialBalance = 10; /// @dev initial balance is 10 Pepito tokens
disguiseCount = 0; /// @dev initial number of disguises created
}
function registerDisguise() public payable stopInEmergency {
/// @dev create a disguise and (future) record it in IPFS
/// @dev stop all creation of new disguise if circuit breaker activated
createPepitoDisguise();
}
function createPepitoDisguise() public payable returns(PepitoDisguise) {
/// @dev deploy an instance of PepitoDisguise with properties transferred from caller
require (owner == msg.sender, "the transaction caller must be Pepito");
/// @dev future improvement: require (initialBalance != uint256(0), "initial balance of disguise cannot be zero");
require (disguiseCount < 512, "there has been already 512 disguises created");
PepitoDisguise pepitoDisguise = new PepitoDisguise(owner/*, initialBalance*/);
/// @dev disguise is a future virtual secretary of persons-in-need, so its contract address is useful
/// @dev the disguise is instantiated here, will be filled by functions in pepitoDisguise()
pepitoDisguiseContracts[disguiseCount] = address(pepitoDisguise);
disguiseCount.add(1);
emit PepitoDisguiseCreated(disguiseCount, address(pepitoDisguise));
return pepitoDisguise;
}
function getPepitoDisguise(uint i) external view returns(address) {
/// @dev this function will be called from a JavaScript loop
/// @dev i is loop index, rank in the array of disguises
/// @return one instance of pepitoDisguiseAddress, function to retrieve its data is exposed in pepitoDisguide
require (i < 512, "cannot exist more than 512 disguises");
return pepitoDisguiseContracts[i];
}
function toggleContractActive() public isAdmin {
/// @dev Circuit breaker to stop the smart contract in desperate cases & restart it
/// @dev In the future we can add an additional modifier that restricts stopping a contract to be
/// @dev based on another action, such as a vote of users
stopped = !stopped;
}
function withdraw () onlyInEmergency public payable {
/// @dev withdraw balances of all tokens when situation is desperate
/// @dev change 'public' to 'external' to reduce gas if never called inside this contract
/// @dev add some code to withdraw all tokens from all disguises if circuit breaker activated
/// @dev and contract is hopelessly FOOBAR
}
}
| / @dev the caller of the function must be Pepito
| require(owner == msg.sender); | 7,263,905 | [
1,
4625,
348,
7953,
560,
30,
342,
632,
5206,
565,
326,
4894,
434,
326,
445,
1297,
506,
453,
881,
11250,
203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2583,
12,
8443,
422,
1234,
18,
15330,
1769,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Depot.sol
version: 3.0
author: Kevin Brown
date: 2018-10-23
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
Depot contract. The Depot provides
a way for users to acquire synths (Synth.sol) and OKS
(Synthetix.sol) by paying TRX and a way for users to acquire OKS
(Synthetix.sol) by paying synths. Users can also deposit their synths
and allow other users to purchase them with TRX. The TRX is sent
to the user who offered their synths for sale.
This smart contract contains a balance of each token, and
allows the owner of the contract (the Synthetix Foundation) to
manage the available balance of synthetix at their discretion, while
users are allowed to deposit and withdraw their own synth deposits
if they have not yet been taken up by another user.
-----------------------------------------------------------------
*/
pragma solidity 0.4.25;
import "./SelfDestructible.sol";
import "./Pausable.sol";
import "./SafeDecimalMath.sol";
import "./interfaces/ISynth.sol";
import "./interfaces/IERC20.sol";
import "./interfaces/IFeePool.sol";
/**
* @title Depot Contract.
*/
contract Depot is SelfDestructible, Pausable {
using SafeMath for uint;
using SafeDecimalMath for uint;
/* ========== STATE VARIABLES ========== */
address public snxProxy;
ISynth public synth;
IFeePool public feePool;
// Address where the ether and Synths raised for selling OKS is transfered to
// Any ether raised for selling Synths gets sent back to whoever deposited the Synths,
// and doesn't have anything to do with this address.
address public fundsWallet;
/* The address of the oracle which pushes the USD price OKS and ether to this contract */
address public oracle;
/* Do not allow the oracle to submit times any further forward into the future than
this constant. */
uint public constant ORACLE_FUTURE_LIMIT = 10 minutes;
/* How long will the contract assume the price of any asset is correct */
uint public priceStalePeriod = 3 hours;
/* The time the prices were last updated */
uint public lastPriceUpdateTime;
/* The USD price of OKS denominated in UNIT */
uint public usdToSnxPrice;
/* The USD price of TRX denominated in UNIT */
uint public usdToEthPrice;
/* Stores deposits from users. */
struct synthDeposit {
// The user that made the deposit
address user;
// The amount (in Synths) that they deposited
uint amount;
}
/* User deposits are sold on a FIFO (First in First out) basis. When users deposit
synths with us, they get added this queue, which then gets fulfilled in order.
Conceptually this fits well in an array, but then when users fill an order we
end up copying the whole array around, so better to use an index mapping instead
for gas performance reasons.
The indexes are specified (inclusive, exclusive), so (0, 0) means there's nothing
in the array, and (3, 6) means there are 3 elements at 3, 4, and 5. You can obtain
the length of the "array" by querying depositEndIndex - depositStartIndex. All index
operations use safeAdd, so there is no way to overflow, so that means there is a
very large but finite amount of deposits this contract can handle before it fills up. */
mapping(uint => synthDeposit) public deposits;
// The starting index of our queue inclusive
uint public depositStartIndex;
// The ending index of our queue exclusive
uint public depositEndIndex;
/* This is a convenience variable so users and dApps can just query how much sUSD
we have available for purchase without having to iterate the mapping with a
O(n) amount of calls for something we'll probably want to display quite regularly. */
uint public totalSellableDeposits;
// The minimum amount of sUSD required to enter the FiFo queue
uint public minimumDepositAmount = 50 * SafeDecimalMath.unit();
// If a user deposits a synth amount < the minimumDepositAmount the contract will keep
// the total of small deposits which will not be sold on market and the sender
// must call withdrawMyDepositedSynths() to get them back.
mapping(address => uint) public smallDeposits;
/* ========== CONSTRUCTOR ========== */
/**
* @dev Constructor
* @param _owner The owner of this contract.
* @param _fundsWallet The recipient of TRX and Synths that are sent to this contract while exchanging.
* @param _snxProxy The Synthetix Proxy contract we'll interact with for balances and transfers.
* @param _synth The Synth contract we'll interact with for balances and sending.
* @param _oracle The address which is able to update price information.
* @param _usdToEthPrice The current price of TRX in USD, expressed in UNIT.
* @param _usdToSnxPrice The current price of Synthetix in USD, expressed in UNIT.
*/
constructor(
// Ownable
address _owner,
// Funds Wallet
address _fundsWallet,
// Other contracts needed
address _snxProxy,
ISynth _synth,
IFeePool _feePool,
// Oracle values - Allows for price updates
address _oracle,
uint _usdToEthPrice,
uint _usdToSnxPrice
)
/* Owned is initialised in SelfDestructible */
SelfDestructible(_owner)
Pausable(_owner)
public
{
fundsWallet = _fundsWallet;
snxProxy = _snxProxy;
synth = _synth;
feePool = _feePool;
oracle = _oracle;
usdToEthPrice = _usdToEthPrice;
usdToSnxPrice = _usdToSnxPrice;
lastPriceUpdateTime = now;
}
/* ========== SETTERS ========== */
/**
* @notice Set the funds wallet where TRX raised is held
* @param _fundsWallet The new address to forward TRX and Synths to
*/
function setFundsWallet(address _fundsWallet)
external
onlyOwner
{
fundsWallet = _fundsWallet;
emit FundsWalletUpdated(fundsWallet);
}
/**
* @notice Set the Oracle that pushes the synthetix price to this contract
* @param _oracle The new oracle address
*/
function setOracle(address _oracle)
external
onlyOwner
{
oracle = _oracle;
emit OracleUpdated(oracle);
}
/**
* @notice Set the sUSD contract
* @param _synth The new synth contract target
*/
function setSynth(ISynth _synth)
external
onlyOwner
{
synth = _synth;
emit SynthUpdated(_synth);
}
/**
* @notice Set the Synthetix Proxy contract
* @param _snxProxy The new synthetix Proxy contract
*/
function setSynthetix(address _snxProxy)
external
onlyOwner
{
snxProxy = _snxProxy;
emit SynthetixUpdated(snxProxy);
}
/**
* @notice Set the stale period on the updated price variables
* @param _time The new priceStalePeriod
*/
function setPriceStalePeriod(uint _time)
external
onlyOwner
{
priceStalePeriod = _time;
emit PriceStalePeriodUpdated(priceStalePeriod);
}
/**
* @notice Set the minimum deposit amount required to depoist sUSD into the FIFO queue
* @param _amount The new new minimum number of sUSD required to deposit
*/
function setMinimumDepositAmount(uint _amount)
external
onlyOwner
{
// Do not allow us to set it less than 1 dollar opening up to fractional desposits in the queue again
require(_amount > SafeDecimalMath.unit(), "Minimum deposit amount must be greater than UNIT");
minimumDepositAmount = _amount;
emit MinimumDepositAmountUpdated(minimumDepositAmount);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Access point for the oracle to update the prices of OKS / eth.
* @param newEthPrice The current price of ether in USD, specified to 18 decimal places.
* @param newSynthetixPrice The current price of OKS in USD, specified to 18 decimal places.
* @param timeSent The timestamp from the oracle when the transaction was created. This ensures we don't consider stale prices as current in times of heavy network congestion.
*/
function updatePrices(uint newEthPrice, uint newSynthetixPrice, uint timeSent)
external
onlyOracle
{
/* Must be the most recently sent price, but not too far in the future.
* (so we can't lock ourselves out of updating the oracle for longer than this) */
require(lastPriceUpdateTime < timeSent, "Time must be later than last update");
require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time must be less than now + ORACLE_FUTURE_LIMIT");
usdToEthPrice = newEthPrice;
usdToSnxPrice = newSynthetixPrice;
lastPriceUpdateTime = timeSent;
emit PricesUpdated(usdToEthPrice, usdToSnxPrice, lastPriceUpdateTime);
}
/**
* @notice Fallback function (exchanges TRX to sUSD)
*/
function ()
external
payable
{
exchangeEtherForSynths();
}
/**
* @notice Exchange TRX to sUSD.
*/
function exchangeEtherForSynths()
public
payable
pricesNotStale
notPaused
returns (uint) // Returns the number of Synths (sUSD) received
{
uint ethToSend;
// The multiplication works here because usdToEthPrice is specified in
// 18 decimal places, just like our currency base.
uint requestedToPurchase = msg.value.multiplyDecimal(usdToEthPrice);
uint remainingToFulfill = requestedToPurchase;
// Iterate through our outstanding deposits and sell them one at a time.
for (uint i = depositStartIndex; remainingToFulfill > 0 && i < depositEndIndex; i++) {
synthDeposit memory deposit = deposits[i];
// If it's an empty spot in the queue from a previous withdrawal, just skip over it and
// update the queue. It's already been deleted.
if (deposit.user == address(0)) {
depositStartIndex = depositStartIndex.add(1);
} else {
// If the deposit can more than fill the order, we can do this
// without touching the structure of our queue.
if (deposit.amount > remainingToFulfill) {
// Ok, this deposit can fulfill the whole remainder. We don't need
// to change anything about our queue we can just fulfill it.
// Subtract the amount from our deposit and total.
uint newAmount = deposit.amount.sub(remainingToFulfill);
deposits[i] = synthDeposit({ user: deposit.user, amount: newAmount});
totalSellableDeposits = totalSellableDeposits.sub(remainingToFulfill);
// Transfer the TRX to the depositor. Send is used instead of transfer
// so a non payable contract won't block the FIFO queue on a failed
// TRX payable for synths transaction. The proceeds to be sent to the
// synthetix foundation funds wallet. This is to protect all depositors
// in the queue in this rare case that may occur.
ethToSend = remainingToFulfill.divideDecimal(usdToEthPrice);
// We need to use send here instead of transfer because transfer reverts
// if the recipient is a non-payable contract. Send will just tell us it
// failed by returning false at which point we can continue.
// solium-disable-next-line security/no-send
if(!deposit.user.send(ethToSend)) {
fundsWallet.transfer(ethToSend);
emit NonPayableContract(deposit.user, ethToSend);
} else {
emit ClearedDeposit(msg.sender, deposit.user, ethToSend, remainingToFulfill, i);
}
// And the Synths to the recipient.
// Note: Fees are calculated by the Synth contract, so when
// we request a specific transfer here, the fee is
// automatically deducted and sent to the fee pool.
synth.transfer(msg.sender, remainingToFulfill);
// And we have nothing left to fulfill on this order.
remainingToFulfill = 0;
} else if (deposit.amount <= remainingToFulfill) {
// We need to fulfill this one in its entirety and kick it out of the queue.
// Start by kicking it out of the queue.
// Free the storage because we can.
delete deposits[i];
// Bump our start index forward one.
depositStartIndex = depositStartIndex.add(1);
// We also need to tell our total it's decreased
totalSellableDeposits = totalSellableDeposits.sub(deposit.amount);
// Now fulfill by transfering the TRX to the depositor. Send is used instead of transfer
// so a non payable contract won't block the FIFO queue on a failed
// TRX payable for synths transaction. The proceeds to be sent to the
// synthetix foundation funds wallet. This is to protect all depositors
// in the queue in this rare case that may occur.
ethToSend = deposit.amount.divideDecimal(usdToEthPrice);
// We need to use send here instead of transfer because transfer reverts
// if the recipient is a non-payable contract. Send will just tell us it
// failed by returning false at which point we can continue.
// solium-disable-next-line security/no-send
if(!deposit.user.send(ethToSend)) {
fundsWallet.transfer(ethToSend);
emit NonPayableContract(deposit.user, ethToSend);
} else {
emit ClearedDeposit(msg.sender, deposit.user, ethToSend, deposit.amount, i);
}
// And the Synths to the recipient.
// Note: Fees are calculated by the Synth contract, so when
// we request a specific transfer here, the fee is
// automatically deducted and sent to the fee pool.
synth.transfer(msg.sender, deposit.amount);
// And subtract the order from our outstanding amount remaining
// for the next iteration of the loop.
remainingToFulfill = remainingToFulfill.sub(deposit.amount);
}
}
}
// Ok, if we're here and 'remainingToFulfill' isn't zero, then
// we need to refund the remainder of their TRX back to them.
if (remainingToFulfill > 0) {
msg.sender.transfer(remainingToFulfill.divideDecimal(usdToEthPrice));
}
// How many did we actually give them?
uint fulfilled = requestedToPurchase.sub(remainingToFulfill);
if (fulfilled > 0) {
// Now tell everyone that we gave them that many (only if the amount is greater than 0).
emit Exchange("TRX", msg.value, "sUSD", fulfilled);
}
return fulfilled;
}
/**
* @notice Exchange TRX to sUSD while insisting on a particular rate. This allows a user to
* exchange while protecting against frontrunning by the contract owner on the exchange rate.
* @param guaranteedRate The exchange rate (ether price) which must be honored or the call will revert.
*/
function exchangeEtherForSynthsAtRate(uint guaranteedRate)
public
payable
pricesNotStale
notPaused
returns (uint) // Returns the number of Synths (sUSD) received
{
require(guaranteedRate == usdToEthPrice, "Guaranteed rate would not be received");
return exchangeEtherForSynths();
}
/**
* @notice Exchange TRX to OKS.
*/
function exchangeEtherForSNX()
public
payable
pricesNotStale
notPaused
returns (uint) // Returns the number of OKS received
{
// How many OKS are they going to be receiving?
uint synthetixToSend = synthetixReceivedForEther(msg.value);
// Store the TRX in our funds wallet
fundsWallet.transfer(msg.value);
// And send them the OKS.
IERC20(snxProxy).transfer(msg.sender, synthetixToSend);
emit Exchange("TRX", msg.value, "OKS", synthetixToSend);
return synthetixToSend;
}
/**
* @notice Exchange TRX to OKS while insisting on a particular set of rates. This allows a user to
* exchange while protecting against frontrunning by the contract owner on the exchange rates.
* @param guaranteedEtherRate The ether exchange rate which must be honored or the call will revert.
* @param guaranteedSynthetixRate The synthetix exchange rate which must be honored or the call will revert.
*/
function exchangeEtherForSynthetixAtRate(uint guaranteedEtherRate, uint guaranteedSynthetixRate)
public
payable
pricesNotStale
notPaused
returns (uint) // Returns the number of OKS received
{
require(guaranteedEtherRate == usdToEthPrice, "Guaranteed ether rate would not be received");
require(guaranteedSynthetixRate == usdToSnxPrice, "Guaranteed synthetix rate would not be received");
return exchangeEtherForSNX();
}
/**
* @notice Exchange sUSD for OKS
* @param synthAmount The amount of synths the user wishes to exchange.
*/
function exchangeSynthsForSynthetix(uint synthAmount)
public
pricesNotStale
notPaused
returns (uint) // Returns the number of OKS received
{
// How many OKS are they going to be receiving?
uint synthetixToSend = synthetixReceivedForSynths(synthAmount);
// Ok, transfer the Synths to our funds wallet.
// These do not go in the deposit queue as they aren't for sale as such unless
// they're sent back in from the funds wallet.
synth.transferFrom(msg.sender, fundsWallet, synthAmount);
// And send them the OKS.
IERC20(snxProxy).transfer(msg.sender, synthetixToSend);
emit Exchange("sUSD", synthAmount, "OKS", synthetixToSend);
return synthetixToSend;
}
/**
* @notice Exchange sUSD for OKS while insisting on a particular rate. This allows a user to
* exchange while protecting against frontrunning by the contract owner on the exchange rate.
* @param synthAmount The amount of synths the user wishes to exchange.
* @param guaranteedRate A rate (synthetix price) the caller wishes to insist upon.
*/
function exchangeSynthsForSynthetixAtRate(uint synthAmount, uint guaranteedRate)
public
pricesNotStale
notPaused
returns (uint) // Returns the number of OKS received
{
require(guaranteedRate == usdToSnxPrice, "Guaranteed rate would not be received");
return exchangeSynthsForSynthetix(synthAmount);
}
/**
* @notice Allows the owner to withdraw OKS from this contract if needed.
* @param amount The amount of OKS to attempt to withdraw (in 18 decimal places).
*/
function withdrawSynthetix(uint amount)
external
onlyOwner
{
IERC20(snxProxy).transfer(owner, amount);
// We don't emit our own events here because we assume that anyone
// who wants to watch what the Depot is doing can
// just watch ERC20 events from the Synth and/or Synthetix contracts
// filtered to our address.
}
/**
* @notice Allows a user to withdraw all of their previously deposited synths from this contract if needed.
* Developer note: We could keep an index of address to deposits to make this operation more efficient
* but then all the other operations on the queue become less efficient. It's expected that this
* function will be very rarely used, so placing the inefficiency here is intentional. The usual
* use case does not involve a withdrawal.
*/
function withdrawMyDepositedSynths()
external
{
uint synthsToSend = 0;
for (uint i = depositStartIndex; i < depositEndIndex; i++) {
synthDeposit memory deposit = deposits[i];
if (deposit.user == msg.sender) {
// The user is withdrawing this deposit. Remove it from our queue.
// We'll just leave a gap, which the purchasing logic can walk past.
synthsToSend = synthsToSend.add(deposit.amount);
delete deposits[i];
//Let the DApps know we've removed this deposit
emit SynthDepositRemoved(deposit.user, deposit.amount, i);
}
}
// Update our total
totalSellableDeposits = totalSellableDeposits.sub(synthsToSend);
// Check if the user has tried to send deposit amounts < the minimumDepositAmount to the FIFO
// queue which would have been added to this mapping for withdrawal only
synthsToSend = synthsToSend.add(smallDeposits[msg.sender]);
smallDeposits[msg.sender] = 0;
// If there's nothing to do then go ahead and revert the transaction
require(synthsToSend > 0, "You have no deposits to withdraw.");
// Send their deposits back to them (minus fees)
synth.transfer(msg.sender, synthsToSend);
emit SynthWithdrawal(msg.sender, synthsToSend);
}
/**
* @notice depositSynths: Allows users to deposit synths via the approve / transferFrom workflow
* @param amount The amount of sUSD you wish to deposit (must have been approved first)
*/
function depositSynths(uint amount)
external
{
// Grab the amount of synths. Will fail if not approved first
synth.transferFrom(msg.sender, this, amount);
// A minimum deposit amount is designed to protect purchasers from over paying
// gas for fullfilling multiple small synth deposits
if (amount < minimumDepositAmount) {
// We cant fail/revert the transaction or send the synths back in a reentrant call.
// So we will keep your synths balance seperate from the FIFO queue so you can withdraw them
smallDeposits[msg.sender] = smallDeposits[msg.sender].add(amount);
emit SynthDepositNotAccepted(msg.sender, amount, minimumDepositAmount);
} else {
// Ok, thanks for the deposit, let's queue it up.
deposits[depositEndIndex] = synthDeposit({ user: msg.sender, amount: amount });
emit SynthDeposit(msg.sender, amount, depositEndIndex);
// Walk our index forward as well.
depositEndIndex = depositEndIndex.add(1);
// And add it to our total.
totalSellableDeposits = totalSellableDeposits.add(amount);
}
}
/* ========== VIEWS ========== */
/**
* @notice Check if the prices haven't been updated for longer than the stale period.
*/
function pricesAreStale()
public
view
returns (bool)
{
return lastPriceUpdateTime.add(priceStalePeriod) < now;
}
/**
* @notice Calculate how many OKS you will receive if you transfer
* an amount of synths.
* @param amount The amount of synths (in 18 decimal places) you want to ask about
*/
function synthetixReceivedForSynths(uint amount)
public
view
returns (uint)
{
// How many synths would we receive after the transfer fee?
uint synthsReceived = feePool.amountReceivedFromTransfer(amount);
// And what would that be worth in OKS based on the current price?
return synthsReceived.divideDecimal(usdToSnxPrice);
}
/**
* @notice Calculate how many OKS you will receive if you transfer
* an amount of ether.
* @param amount The amount of ether (in wei) you want to ask about
*/
function synthetixReceivedForEther(uint amount)
public
view
returns (uint)
{
// How much is the TRX they sent us worth in sUSD (ignoring the transfer fee)?
uint valueSentInSynths = amount.multiplyDecimal(usdToEthPrice);
// Now, how many OKS will that USD amount buy?
return synthetixReceivedForSynths(valueSentInSynths);
}
/**
* @notice Calculate how many synths you will receive if you transfer
* an amount of ether.
* @param amount The amount of ether (in wei) you want to ask about
*/
function synthsReceivedForEther(uint amount)
public
view
returns (uint)
{
// How many synths would that amount of ether be worth?
uint synthsTransferred = amount.multiplyDecimal(usdToEthPrice);
// And how many of those would you receive after a transfer (deducting the transfer fee)
return feePool.amountReceivedFromTransfer(synthsTransferred);
}
/* ========== MODIFIERS ========== */
modifier onlyOracle
{
require(msg.sender == oracle, "Only the oracle can perform this action");
_;
}
modifier onlySynth
{
// We're only interested in doing anything on receiving sUSD.
require(msg.sender == address(synth), "Only the synth contract can perform this action");
_;
}
modifier pricesNotStale
{
require(!pricesAreStale(), "Prices must not be stale to perform this action");
_;
}
/* ========== EVENTS ========== */
event FundsWalletUpdated(address newFundsWallet);
event OracleUpdated(address newOracle);
event SynthUpdated(ISynth newSynthContract);
event SynthetixUpdated(address newSNXProxy);
event PriceStalePeriodUpdated(uint priceStalePeriod);
event PricesUpdated(uint newEthPrice, uint newSynthetixPrice, uint timeSent);
event Exchange(string fromCurrency, uint fromAmount, string toCurrency, uint toAmount);
event SynthWithdrawal(address user, uint amount);
event SynthDeposit(address indexed user, uint amount, uint indexed depositIndex);
event SynthDepositRemoved(address indexed user, uint amount, uint indexed depositIndex);
event SynthDepositNotAccepted(address user, uint amount, uint minimum);
event MinimumDepositAmountUpdated(uint amount);
event NonPayableContract(address indexed receiver, uint amount);
event ClearedDeposit(address indexed fromAddress, address indexed toAddress, uint fromETHAmount, uint toAmount, uint indexed depositIndex);
}
| * @notice Allows the owner to withdraw OKS from this contract if needed. @param amount The amount of OKS to attempt to withdraw (in 18 decimal places)./ We don't emit our own events here because we assume that anyone who wants to watch what the Depot is doing can just watch ERC20 events from the Synth and/or Synthetix contracts filtered to our address. | function withdrawSynthetix(uint amount)
external
onlyOwner
{
IERC20(snxProxy).transfer(owner, amount);
}
| 12,690,963 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
20392,
25619,
326,
3410,
358,
598,
9446,
7791,
55,
628,
333,
6835,
309,
3577,
18,
632,
891,
3844,
1021,
3844,
434,
7791,
55,
358,
4395,
358,
598,
9446,
261,
267,
6549,
6970,
12576,
2934,
19,
1660,
2727,
1404,
3626,
3134,
4953,
2641,
2674,
2724,
732,
6750,
716,
1281,
476,
10354,
14805,
358,
4267,
4121,
326,
4019,
352,
353,
9957,
848,
2537,
4267,
4232,
39,
3462,
2641,
628,
326,
16091,
451,
471,
19,
280,
16091,
451,
278,
697,
20092,
5105,
358,
3134,
1758,
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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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
10503,
451,
278,
697,
12,
11890,
3844,
13,
203,
3639,
3903,
203,
3639,
1338,
5541,
203,
565,
288,
203,
3639,
467,
654,
39,
3462,
12,
8134,
92,
3886,
2934,
13866,
12,
8443,
16,
3844,
1769,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.11;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ryancoin {
using SafeMath for uint256;
uint256 public constant _initialSupply = 15000000 * (10 ** uint256(decimals));
uint256 _totalSupply = 0;
uint256 _totalSold = 0;
string public constant symbol = "RYC";
string public constant name = "Ryancoin";
uint8 public constant decimals = 6;
uint256 public rate = 1 ether / (500 * (10 ** uint256(decimals)));
address public owner;
bool public _contractStatus = true;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed; //control allow to spend
mapping (address => bool) _frozenAccount;
mapping (address => bool) _tokenAccount;
address[] tokenHolders;
//Event
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event UpdateStatus(string newStatus);
event Burn(address target, uint256 _value);
event MintedToken(address target, uint256 _value);
event FrozenFunds(address target, bool _value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function Ryancoin() {
owner = msg.sender;
_totalSupply = _initialSupply;
balances[owner] = _totalSupply;
setTokenHolders(owner);
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != 0x0);
owner = newOwner;
}
function stopContract() public onlyOwner {
_contractStatus = false;
UpdateStatus("Contract is stop");
}
function enableContract() public onlyOwner {
_contractStatus = true;
UpdateStatus("Contract is enable");
}
function totalSupply() public constant returns (uint256){
return _totalSupply;
}
function totalSold() public constant returns (uint256){
return _totalSold;
}
function totalRate() public constant returns (uint256){
return rate;
}
function updateRate(uint256 _value) onlyOwner public returns (bool success){
require(_value > 0);
rate = 1 ether / (_value * (10 ** uint256(decimals)));
return true;
}
function () payable public {
createTokens(); //send money to contract owner
}
function createTokens() public payable{
require(msg.value > 0 && msg.value > rate && _contractStatus);
uint256 tokens = msg.value.div(rate);
require(tokens + _totalSold < _totalSupply);
require(
balances[owner] >= tokens
&& tokens > 0
);
_transfer(owner, msg.sender, tokens);
Transfer(owner, msg.sender, tokens);
_totalSold = _totalSold.add(tokens);
owner.transfer(msg.value); //transfer ether to contract ower
}
function balanceOf(address _owner) public constant returns (uint256 balance){
return balances[_owner];
}
function transfer(address _to, uint256 _value) public returns (bool success){
//Check contract is stop
require(_contractStatus);
require(!_frozenAccount[msg.sender]);
_transfer(msg.sender, _to, _value);
return true;
}
function _transfer(address _from, address _to, uint256 _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check value more than 0
require(_value > 0);
// Check if the sender has enough
require(balances[_from] >= _value);
// Check for overflows
require(balances[_to] + _value > balances[_to]);
// Save this for an assertion in the future
uint256 previousBalances = balances[_from] + balances[_to];
// Subtract from the sender
balances[_from] -= _value;
// Set token holder list
setTokenHolders(_to);
// Add the same to the recipient
balances[_to] += _value;
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);
}
function transferFromOwner(address _from, address _to, uint256 _value) onlyOwner public returns (bool success){
_transfer(_from, _to, _value);
return true;
}
function setTokenHolders(address _holder) internal {
if (_tokenAccount[_holder]) return;
tokenHolders.push(_holder) -1;
_tokenAccount[_holder] = true;
}
function getTokenHolders() view public returns (address[]) {
return tokenHolders;
}
function countTokenHolders() view public returns (uint) {
return tokenHolders.length;
}
function burn(uint256 _value) public returns (bool success) {
require(_value > 0);
require(balances[msg.sender] >= _value); // Check if the sender has enough
balances[msg.sender] -= _value; // Subtract from the sender
_totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
function burnFromOwner(address _from, uint256 _value) onlyOwner public returns (bool success) {
require(_from != address(0));
require(_value > 0);
require(balances[_from] >= _value); // Check if the targeted balance is enough
balances[_from] -= _value; // Subtract from the targeted balance
_totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
function mintToken(address _target, uint256 _mintedAmount) onlyOwner public {
require(_target != address(0));
require(_mintedAmount > 0);
balances[_target] += _mintedAmount;
_totalSupply += _mintedAmount;
setTokenHolders(_target);
Transfer(0, owner, _mintedAmount);
Transfer(owner, _target, _mintedAmount);
MintedToken(_target, _mintedAmount);
}
function getfreezeAccount(address _target) public constant returns (bool freeze) {
require(_target != 0x0);
return _frozenAccount[_target];
}
function freezeAccount(address _target, bool freeze) onlyOwner public {
require(_target != 0x0);
_frozenAccount[_target] = freeze;
FrozenFunds(_target, freeze);
}
/**
* @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(_from != address(0));
require(_to != address(0));
require(_value <= allowed[_from][msg.sender]);
_transfer(_from, _to, _value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
require(_spender != address(0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
require(_owner != address(0));
require(_spender != address(0));
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
require(_spender != address(0));
require(_addedValue > 0);
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
require(_spender != address(0));
require(_subtractedValue > 0);
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | Subtract from the sender
| balances[msg.sender] -= _value; | 1,004,543 | [
1,
4625,
348,
7953,
560,
30,
225,
2592,
1575,
628,
326,
5793,
203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,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,
0,
0,
0,
0,
0,
0,
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,
324,
26488,
63,
3576,
18,
15330,
65,
3947,
389,
1132,
31,
2868,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xECb42c2b9e5A3F35D9faD62F5E2bC102c105946B/sources/extensions/EmergencyWithdrawable.sol | * @dev Withdraw token from (this) contract to `beneficiary`./ | function _emergencyWithdrawToken(address beneficiary, address token) internal virtual {
uint256 balance = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransfer(beneficiary, balance);
emit EmergencyWithdrawToken(token, beneficiary, balance);
}
| 9,139,373 | [
1,
4625,
348,
7953,
560,
30,
380,
632,
5206,
3423,
9446,
1147,
628,
261,
2211,
13,
6835,
358,
1375,
70,
4009,
74,
14463,
814,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
351,
24530,
1190,
9446,
1345,
12,
2867,
27641,
74,
14463,
814,
16,
1758,
1147,
13,
2713,
5024,
288,
203,
3639,
2254,
5034,
11013,
273,
467,
654,
39,
3462,
12,
2316,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
467,
654,
39,
3462,
12,
2316,
2934,
4626,
5912,
12,
70,
4009,
74,
14463,
814,
16,
11013,
1769,
203,
203,
3639,
3626,
512,
6592,
75,
2075,
1190,
9446,
1345,
12,
2316,
16,
27641,
74,
14463,
814,
16,
11013,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x6C5c2c8776Ecc5943760C68a200eC7e3650eFC2F/sources/contracts/paymaster/TokenPaymaster.sol | Do nothing here to not revert the whole bundle and harm reputation - From ethInfinitism | function _postOp(PostOpMode mode, bytes calldata context, uint256 actualGasCost) internal override {
uint256 startingGas = gasleft();
(TokenContext memory ctx, bytes memory permitData) = abi.decode(context, (TokenContext, bytes));
uint256 actualTokenCost = ((actualGasCost + ctx.postCost * ctx.gasPrice) * ctx.maxTokenCost) / ctx.maxCost;
_reimbursePaymaster(ctx.token, ctx.spender, actualTokenCost, permitData);
dataStore[_getTokenBalanceKey(ctx.token, ctx.sponsor)] += actualTokenCost;
dataStore[_getTokenBalanceKey(ETH, ctx.sponsor)] -= actualGasCost + ctx.postCost * ctx.gasPrice;
accumulatedEthDust -= actualGasCost + ctx.postCost * ctx.gasPrice;
emit PostOpGasPaid(ctx.opHash, ctx.spender, ctx.sponsor, actualTokenCost, actualGasCost + ctx.postCost * ctx.gasPrice);
require(startingGas - gasleft() <= ctx.postCost, "FW514");
if (mode == PostOpMode.postOpReverted) {
emit PostOpReverted(context, actualGasCost);
return;
}
}
| 16,537,817 | [
1,
4625,
348,
7953,
560,
30,
225,
2256,
5083,
2674,
358,
486,
15226,
326,
7339,
3440,
471,
366,
4610,
283,
458,
367,
300,
6338,
13750,
382,
926,
305,
6228,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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1042,
3778,
1103,
16,
1731,
3778,
21447,
751,
13,
273,
24126,
18,
3922,
12,
2472,
16,
261,
1345,
1042,
16,
1731,
10019,
203,
202,
202,
11890,
5034,
3214,
1345,
8018,
273,
14015,
18672,
27998,
8018,
397,
1103,
18,
2767,
8018,
380,
1103,
18,
31604,
5147,
13,
380,
1103,
18,
1896,
1345,
8018,
13,
342,
1103,
18,
1896,
8018,
31,
203,
203,
202,
202,
67,
266,
381,
70,
295,
307,
9148,
7525,
12,
5900,
18,
2316,
16,
1103,
18,
87,
1302,
264,
16,
3214,
1345,
8018,
16,
21447,
751,
1769,
203,
203,
202,
202,
892,
2257,
63,
67,
588,
1345,
13937,
653,
12,
5900,
18,
2316,
16,
1103,
18,
87,
500,
2467,
25887,
1011,
3214,
1345,
8018,
31,
203,
202,
202,
892,
2257,
63,
67,
588,
1345,
13937,
653,
12,
1584,
44,
16,
1103,
18,
87,
500,
2467,
25887,
3947,
3214,
27998,
8018,
397,
1103,
18,
2767,
8018,
380,
1103,
18,
31604,
5147,
31,
203,
202,
202,
8981,
5283,
690,
41,
451,
40,
641,
3947,
3214,
27998,
8018,
397,
1103,
18,
2767,
8018,
380,
1103,
18,
31604,
5147,
31,
203,
203,
202,
202,
18356,
5616,
3817,
27998,
16507,
350,
12,
5900,
18,
556,
2310,
16,
1103,
18,
87,
1302,
264,
16,
1103,
18,
87,
500,
2467,
16,
3214,
1345,
8018,
16,
3214,
27998,
8018,
397,
1103,
18,
2767,
8018,
380,
1103,
18,
31604,
5147,
1769,
203,
202,
202,
6528,
12,
18526,
27998,
300,
16189,
4482,
1435,
1648,
1103,
18,
2767,
8018,
16,
315,
29753,
25,
3461,
8863,
203,
202,
202,
430,
261,
3188,
422,
5616,
3817,
2309,
18,
2767,
3817,
426,
25631,
13,
288,
203,
1082,
202,
18356,
5616,
3817,
426,
25631,
12,
2472,
16,
3214,
27998,
8018,
1769,
203,
1082,
202,
2463,
31,
203,
202,
202,
97,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/7700/0x4f07f0a2AE51ac40fb5FbdDaC242B5D22Cc0C992/sources/contracts/Plebness.sol | @inheritdoc IPlebness | function addFaceAssets(bytes[] calldata assets) external override onlyOwner {
for (uint256 i = 0; i < assets.length; i++) {
_addFace(assets[i]);
}
}
@param asset input face asset.
| 4,649,750 | [
1,
4625,
348,
7953,
560,
30,
225,
632,
10093,
2971,
298,
70,
4496,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,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
12,
9971,
63,
77,
19226,
203,
3639,
289,
203,
565,
289,
203,
203,
3639,
632,
891,
3310,
810,
7945,
3310,
18,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.10;
import "./interfaces/ICollateralManager.sol";
contract EmptyCollateralManager is ICollateralManager {
// Manager information
function hasCollateral(address) external view override returns (bool) {
return false;
}
function isSynthManaged(bytes32) external view override returns (bool) {
return false;
}
// State information
function long(bytes32) external view override returns (uint amount) {
return 0;
}
function short(bytes32) external view override returns (uint amount) {
return 0;
}
function totalLong() external view override returns (uint dUSDValue, bool anyRateIsInvalid) {
return (0, false);
}
function totalShort() external view override returns (uint dUSDValue, bool anyRateIsInvalid) {
return (0, false);
}
function getBorrowRate() external view override returns (uint borrowRate, bool anyRateIsInvalid) {
return (0, false);
}
function getShortRate(bytes32) external view override returns (uint shortRate, bool rateIsInvalid) {
return (0, false);
}
function getRatesAndTime(uint)
external
view
override
returns (
uint entryRate,
uint lastRate,
uint lastUpdated,
uint newIndex
)
{
return (0, 0, 0, 0);
}
function getShortRatesAndTime(bytes32, uint)
external
view
override
returns (
uint entryRate,
uint lastRate,
uint lastUpdated,
uint newIndex
)
{
return (0, 0, 0, 0);
}
function exceedsDebtLimit(uint, bytes32) external view override returns (bool canIssue, bool anyRateIsInvalid) {
return (false, false);
}
function areSynthsAndCurrenciesSet(bytes32[] calldata, bytes32[] calldata) external view override returns (bool) {
return false;
}
function areShortableSynthsSet(bytes32[] calldata, bytes32[] calldata) external view override returns (bool) {
return false;
}
// Loans
function getNewLoanId() external override returns (uint id) {
return 0;
}
// Manager mutative
function addCollaterals(address[] calldata) external override {}
function removeCollaterals(address[] calldata) external override {}
function addSynths(bytes32[] calldata, bytes32[] calldata) external override {}
function removeSynths(bytes32[] calldata, bytes32[] calldata) external override {}
function addShortableSynths(bytes32[2][] calldata, bytes32[] calldata) external override {}
function removeShortableSynths(bytes32[] calldata) external override {}
// State mutative
function updateBorrowRates(uint) external override {}
function updateShortRates(bytes32, uint) external override {}
function incrementLongs(bytes32, uint) external override {}
function decrementLongs(bytes32, uint) external override {}
function incrementShorts(bytes32, uint) external override {}
function decrementShorts(bytes32, uint) external override {}
}
| Manager information | contract EmptyCollateralManager is ICollateralManager {
function hasCollateral(address) external view override returns (bool) {
return false;
}
function isSynthManaged(bytes32) external view override returns (bool) {
return false;
}
function long(bytes32) external view override returns (uint amount) {
return 0;
}
function short(bytes32) external view override returns (uint amount) {
return 0;
}
function totalLong() external view override returns (uint dUSDValue, bool anyRateIsInvalid) {
return (0, false);
}
function totalShort() external view override returns (uint dUSDValue, bool anyRateIsInvalid) {
return (0, false);
}
function getBorrowRate() external view override returns (uint borrowRate, bool anyRateIsInvalid) {
return (0, false);
}
function getShortRate(bytes32) external view override returns (uint shortRate, bool rateIsInvalid) {
return (0, false);
}
function getRatesAndTime(uint)
external
view
override
returns (
uint entryRate,
uint lastRate,
uint lastUpdated,
uint newIndex
)
{
return (0, 0, 0, 0);
}
function getShortRatesAndTime(bytes32, uint)
external
view
override
returns (
uint entryRate,
uint lastRate,
uint lastUpdated,
uint newIndex
)
{
return (0, 0, 0, 0);
}
function exceedsDebtLimit(uint, bytes32) external view override returns (bool canIssue, bool anyRateIsInvalid) {
return (false, false);
}
function areSynthsAndCurrenciesSet(bytes32[] calldata, bytes32[] calldata) external view override returns (bool) {
return false;
}
function areShortableSynthsSet(bytes32[] calldata, bytes32[] calldata) external view override returns (bool) {
return false;
}
function getNewLoanId() external override returns (uint id) {
return 0;
}
function addCollaterals(address[] calldata) external override {}
function removeCollaterals(address[] calldata) external override {}
function addSynths(bytes32[] calldata, bytes32[] calldata) external override {}
function removeSynths(bytes32[] calldata, bytes32[] calldata) external override {}
function addShortableSynths(bytes32[2][] calldata, bytes32[] calldata) external override {}
function removeShortableSynths(bytes32[] calldata) external override {}
function updateBorrowRates(uint) external override {}
function updateShortRates(bytes32, uint) external override {}
function incrementLongs(bytes32, uint) external override {}
function decrementLongs(bytes32, uint) external override {}
function incrementShorts(bytes32, uint) external override {}
function decrementShorts(bytes32, uint) external override {}
}
| 12,537,862 | [
1,
4625,
348,
7953,
560,
30,
225,
8558,
1779,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
8953,
13535,
2045,
287,
1318,
353,
467,
13535,
2045,
287,
1318,
288,
203,
565,
445,
711,
13535,
2045,
287,
12,
2867,
13,
3903,
1476,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
327,
629,
31,
203,
565,
289,
203,
203,
565,
445,
353,
10503,
451,
10055,
12,
3890,
1578,
13,
3903,
1476,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
327,
629,
31,
203,
565,
289,
203,
203,
565,
445,
1525,
12,
3890,
1578,
13,
3903,
1476,
3849,
1135,
261,
11890,
3844,
13,
288,
203,
3639,
327,
374,
31,
203,
565,
289,
203,
203,
565,
445,
3025,
12,
3890,
1578,
13,
3903,
1476,
3849,
1135,
261,
11890,
3844,
13,
288,
203,
3639,
327,
374,
31,
203,
565,
289,
203,
203,
565,
445,
2078,
3708,
1435,
3903,
1476,
3849,
1135,
261,
11890,
302,
3378,
40,
620,
16,
1426,
1281,
4727,
2520,
1941,
13,
288,
203,
3639,
327,
261,
20,
16,
629,
1769,
203,
565,
289,
203,
203,
565,
445,
2078,
4897,
1435,
3903,
1476,
3849,
1135,
261,
11890,
302,
3378,
40,
620,
16,
1426,
1281,
4727,
2520,
1941,
13,
288,
203,
3639,
327,
261,
20,
16,
629,
1769,
203,
565,
289,
203,
203,
565,
445,
2882,
15318,
4727,
1435,
3903,
1476,
3849,
1135,
261,
11890,
29759,
4727,
16,
1426,
1281,
4727,
2520,
1941,
13,
288,
203,
3639,
327,
261,
20,
16,
629,
1769,
203,
565,
289,
203,
203,
565,
445,
13157,
4727,
12,
3890,
1578,
13,
3903,
1476,
3849,
1135,
261,
11890,
3025,
4727,
16,
1426,
4993,
2520,
1941,
13,
288,
203,
3639,
327,
261,
20,
16,
629,
1769,
203,
565,
289,
203,
203,
565,
445,
4170,
815,
1876,
950,
12,
11890,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
3849,
203,
3639,
1135,
261,
203,
5411,
2254,
1241,
4727,
16,
203,
5411,
2254,
1142,
4727,
16,
203,
5411,
2254,
1142,
7381,
16,
203,
5411,
2254,
21309,
203,
3639,
262,
203,
565,
288,
203,
3639,
327,
261,
20,
16,
374,
16,
374,
16,
374,
1769,
203,
565,
289,
203,
203,
565,
445,
13157,
20836,
1876,
950,
12,
3890,
1578,
16,
2254,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
3849,
203,
3639,
1135,
261,
203,
5411,
2254,
1241,
4727,
16,
203,
5411,
2254,
1142,
4727,
16,
203,
5411,
2254,
1142,
7381,
16,
203,
5411,
2254,
21309,
203,
3639,
262,
203,
565,
288,
203,
3639,
327,
261,
20,
16,
374,
16,
374,
16,
374,
1769,
203,
565,
289,
203,
203,
565,
445,
14399,
758,
23602,
3039,
12,
11890,
16,
1731,
1578,
13,
3903,
1476,
3849,
1135,
261,
6430,
848,
12956,
16,
1426,
1281,
4727,
2520,
1941,
13,
288,
203,
3639,
327,
261,
5743,
16,
629,
1769,
203,
565,
289,
203,
203,
565,
445,
854,
10503,
451,
87,
1876,
2408,
14695,
694,
12,
3890,
1578,
8526,
745,
892,
16,
1731,
1578,
8526,
745,
892,
13,
3903,
1476,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
327,
629,
31,
203,
565,
289,
203,
203,
565,
445,
854,
4897,
429,
10503,
451,
87,
694,
12,
3890,
1578,
8526,
745,
892,
16,
1731,
1578,
8526,
745,
892,
13,
3903,
1476,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
327,
629,
31,
203,
565,
289,
203,
203,
565,
445,
12654,
1504,
304,
548,
1435,
3903,
3849,
1135,
261,
11890,
612,
13,
288,
203,
3639,
327,
374,
31,
203,
565,
289,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
565,
445,
527,
13535,
2045,
1031,
12,
2867,
8526,
745,
892,
13,
3903,
3849,
2618,
203,
565,
445,
1206,
13535,
2045,
1031,
12,
2867,
8526,
745,
892,
13,
3903,
3849,
2618,
203,
565,
445,
527,
10503,
451,
87,
12,
3890,
1578,
8526,
745,
892,
16,
1731,
1578,
8526,
745,
892,
13,
3903,
3849,
2618,
203,
565,
445,
1206,
10503,
451,
87,
12,
3890,
1578,
8526,
745,
892,
16,
1731,
1578,
8526,
745,
892,
13,
3903,
3849,
2618,
203,
565,
445,
527,
4897,
429,
10503,
451,
87,
12,
3890,
1578,
63,
22,
6362,
65,
745,
892,
16,
1731,
1578,
8526,
745,
892,
13,
3903,
3849,
2618,
203,
565,
445,
1206,
4897,
429,
10503,
451,
87,
12,
3890,
1578,
8526,
745,
892,
13,
3903,
3849,
2618,
203,
565,
445,
1089,
38,
15318,
20836,
12,
11890,
13,
3903,
3849,
2618,
203,
565,
445,
1089,
4897,
20836,
12,
3890,
1578,
16,
2254,
13,
3903,
3849,
2618,
203,
565,
445,
5504,
21762,
12,
3890,
1578,
16,
2254,
13,
3903,
3849,
2618,
203,
565,
445,
15267,
21762,
12,
3890,
1578,
16,
2254,
13,
3903,
3849,
2618,
203,
565,
445,
5504,
4897,
87,
12,
3890,
1578,
16,
2254,
13,
3903,
3849,
2618,
203,
565,
445,
15267,
4897,
87,
12,
3890,
1578,
16,
2254,
13,
3903,
3849,
2618,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
import "../../common/ErrorCodes.sol";
import "./BidState.sol";
/**
* Bid data contract
*/
contract Bid is ErrorCodes, BidState {
// NOTE: members must be public to be indexed for search
uint public id;
string public name;
string public supplier;
uint public amount;
BidState public state;
function Bid(uint _id, string _name, string _supplier, uint _amount) {
id = _id;
name = _name;
supplier = _supplier;
amount = _amount;
state = BidState.OPEN;
}
function getState() returns (BidState) {
return state;
}
function setState(BidState _state) {
state = _state;
}
function setBidState(BidState newState) payable returns (ErrorCodes) {
if (state == BidState.OPEN && newState == BidState.ACCEPTED) {
setState(newState);
return ErrorCodes.SUCCESS;
}
if (state == BidState.OPEN && newState == BidState.REJECTED) {
setState(newState);
return ErrorCodes.SUCCESS;
}
return ErrorCodes.ERROR;
}
function settle(address supplierAddress) returns (ErrorCodes) {
// confirm balance, to return error
if (this.balance < amount) {
return ErrorCodes.INSUFFICIENT_BALANCE;
}
uint fee = 10000000 wei; // supplier absorbs the fee
uint amountWei = amount * 1 ether;
// transfer will throw
supplierAddress.send(amountWei-fee);
return ErrorCodes.SUCCESS;
}
}
| supplier absorbs the fee
| uint fee = 10000000 wei; | 1,011,299 | [
1,
4625,
348,
7953,
560,
30,
225,
17402,
2417,
280,
2038,
326,
14036,
203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0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-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-03-13
*/
pragma solidity 0.5.11; // optimization runs: 200, evm version: petersburg
// WARNING - `executeActionWithAtomicBatchCalls` has a `bytes[]` argument that
// requires ABIEncoderV2. Exercise caution when calling that specific function.
pragma experimental ABIEncoderV2;
interface DharmaSmartWalletImplementationV1Interface {
event CallSuccess(
bytes32 actionID,
bool rolledBack,
uint256 nonce,
address to,
bytes data,
bytes returnData
);
event CallFailure(
bytes32 actionID,
uint256 nonce,
address to,
bytes data,
string revertReason
);
// ABIEncoderV2 uses an array of Calls for executing generic batch calls.
struct Call {
address to;
bytes data;
}
// ABIEncoderV2 uses an array of CallReturns for handling generic batch calls.
struct CallReturn {
bool ok;
bytes returnData;
}
function withdrawEther(
uint256 amount,
address payable recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok);
function executeAction(
address to,
bytes calldata data,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok, bytes memory returnData);
function recover(address newUserSigningKey) external;
function executeActionWithAtomicBatchCalls(
Call[] calldata calls,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool[] memory ok, bytes[] memory returnData);
function getNextGenericActionID(
address to,
bytes calldata data,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function getGenericActionID(
address to,
bytes calldata data,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function getNextGenericAtomicBatchActionID(
Call[] calldata calls,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function getGenericAtomicBatchActionID(
Call[] calldata calls,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
}
interface DharmaSmartWalletImplementationV3Interface {
event Cancel(uint256 cancelledNonce);
event EthWithdrawal(uint256 amount, address recipient);
}
interface DharmaSmartWalletImplementationV4Interface {
event Escaped();
function setEscapeHatch(
address account,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external;
function escape() external;
}
interface DharmaSmartWalletImplementationV7Interface {
// Fires when a new user signing key is set on the smart wallet.
event NewUserSigningKey(address userSigningKey);
// Fires when an error occurs as part of an attempted action.
event ExternalError(address indexed source, string revertReason);
// The smart wallet recognizes DAI, USDC, ETH, and SAI as supported assets.
enum AssetType {
DAI,
USDC,
ETH,
SAI
}
// Actions, or protected methods (i.e. not deposits) each have an action type.
enum ActionType {
Cancel,
SetUserSigningKey,
Generic,
GenericAtomicBatch,
SAIWithdrawal,
USDCWithdrawal,
ETHWithdrawal,
SetEscapeHatch,
RemoveEscapeHatch,
DisableEscapeHatch,
DAIWithdrawal,
SignatureVerification,
TradeEthForDai,
TradeDDaiForDUSDC,
TradeDUSDCForDDai,
DAIBorrow,
USDCBorrow
}
function initialize(address userSigningKey) external;
function repayAndDeposit() external;
function withdrawDai(
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok);
function withdrawUSDC(
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok);
function cancel(
uint256 minimumActionGas,
bytes calldata signature
) external;
function setUserSigningKey(
address userSigningKey,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external;
function migrateCUSDCToDUSDC() external;
function getBalances() external view returns (
uint256 daiBalance,
uint256 usdcBalance,
uint256 etherBalance,
uint256 dDaiUnderlyingDaiBalance,
uint256 dUsdcUnderlyingUsdcBalance,
uint256 dEtherUnderlyingEtherBalance // always returns zero
);
function getUserSigningKey() external view returns (address userSigningKey);
function getNonce() external view returns (uint256 nonce);
function getNextCustomActionID(
ActionType action,
uint256 amount,
address recipient,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function getCustomActionID(
ActionType action,
uint256 amount,
address recipient,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function getVersion() external pure returns (uint256 version);
}
interface DharmaSmartWalletImplementationV8Interface {
function tradeEthForDaiAndMintDDai(
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok, bytes memory returnData);
function getNextEthForDaiActionID(
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function getEthForDaiActionID(
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
}
interface DharmaSmartWalletImplementationV9Interface {
function cancel(
uint256 minimumActionGas,
bytes calldata signature
) external;
function tradeDDaiForDUSDC(
uint256 dDaiToSupply,
uint256 minimumDUSDCReceived,
address target,
bytes calldata data,
uint256 minimumActionGas,
bytes calldata signature
) external returns (bool ok, bytes memory returnData);
}
interface ERC20Interface {
function transfer(address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
function allowance(
address owner, address spender
) external view returns (uint256);
}
interface ERC1271Interface {
function isValidSignature(
bytes calldata data, bytes calldata signature
) external view returns (bytes4 magicValue);
}
interface CTokenInterface {
function redeem(uint256 redeemAmount) external returns (uint256 err);
function transfer(address recipient, uint256 value) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function balanceOf(address account) external view returns (uint256 balance);
function allowance(address owner, address spender) external view returns (uint256);
}
interface DTokenInterface {
// These external functions trigger accrual on the dToken and backing cToken.
function mint(uint256 underlyingToSupply) external returns (uint256 dTokensMinted);
function redeem(uint256 dTokensToBurn) external returns (uint256 underlyingReceived);
function redeemUnderlying(uint256 underlyingToReceive) external returns (uint256 dTokensBurned);
// These external functions only trigger accrual on the dToken.
function mintViaCToken(uint256 cTokensToSupply) external returns (uint256 dTokensMinted);
// View and pure functions do not trigger accrual on the dToken or the cToken.
function exchangeRateCurrent() external view returns (uint256 rate);
function balanceOfUnderlying(address account) external view returns (uint256 underlyingBalance);
}
interface USDCV1Interface {
function isBlacklisted(address _account) external view returns (bool);
function paused() external view returns (bool);
}
interface DharmaKeyRegistryInterface {
function getKey() external view returns (address key);
}
interface DharmaEscapeHatchRegistryInterface {
function setEscapeHatch(address newEscapeHatch) external;
function removeEscapeHatch() external;
function permanentlyDisableEscapeHatch() external;
function getEscapeHatch() external view returns (
bool exists, address escapeHatch
);
}
interface TradeHelperInterface {
function tradeEthForDai(
uint256 daiExpected, address target, bytes calldata data
) external payable returns (uint256 daiReceived);
function tradeDDaiForDUSDC(
uint256 minimumDUSDCReceived,
address target,
bytes calldata data
) external returns (uint256 dUSDCReceived);
}
interface RevertReasonHelperInterface {
function reason(uint256 code) external pure returns (string memory);
}
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
library ECDSA {
function recover(
bytes32 hash, bytes memory signature
) internal pure returns (address) {
if (signature.length != 65) {
return (address(0));
}
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
return ecrecover(hash, v, r, s);
}
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
/**
* @title DharmaSmartWalletImplementationV9
* @author 0age
* @notice The V9 implementation for the Dharma smart wallet is a non-custodial,
* meta-transaction-enabled wallet with helper functions to facilitate lending
* funds through Dharma Dai and Dharma USD Coin (which in turn use CompoundV2),
* and with an added security backstop provided by Dharma Labs prior to making
* withdrawals. It adds support for Dharma Dai and Dharma USD Coin - they employ
* the respective cTokens as backing tokens and mint and redeem them internally
* as interest-bearing collateral. This implementation also contains methods to
* support account recovery, escape hatch functionality, and generic actions,
* including in an atomic batch. The smart wallet instances utilizing this
* implementation are deployed through the Dharma Smart Wallet Factory via
* `CREATE2`, which allows for their address to be known ahead of time, and any
* Dai or USDC that has already been sent into that address will automatically
* be deposited into the respective Dharma Token upon deployment of the new
* smart wallet instance. V9 adds a mechanism for permissioned conversion of
* Dharma Dai into Dharma USD Coin using a single signature.
*/
contract DharmaSmartWalletImplementationV9 is
DharmaSmartWalletImplementationV1Interface,
DharmaSmartWalletImplementationV3Interface,
DharmaSmartWalletImplementationV4Interface,
DharmaSmartWalletImplementationV7Interface,
DharmaSmartWalletImplementationV8Interface,
DharmaSmartWalletImplementationV9Interface,
ERC1271Interface {
using Address for address;
using ECDSA for bytes32;
// WARNING: DO NOT REMOVE OR REORDER STORAGE WHEN WRITING NEW IMPLEMENTATIONS!
// The user signing key associated with this account is in storage slot 0.
// It is the core differentiator when it comes to the account in question.
address private _userSigningKey;
// The nonce associated with this account is in storage slot 1. Every time a
// signature is submitted, it must have the appropriate nonce, and once it has
// been accepted the nonce will be incremented.
uint256 private _nonce;
// The self-call context flag is in storage slot 2. Some protected functions
// may only be called externally from calls originating from other methods on
// this contract, which enables appropriate exception handling on reverts.
// Any storage should only be set immediately preceding a self-call and should
// be cleared upon entering the protected function being called.
bytes4 internal _selfCallContext;
// END STORAGE DECLARATIONS - DO NOT REMOVE OR REORDER STORAGE ABOVE HERE!
// The smart wallet version will be used when constructing valid signatures.
uint256 internal constant _DHARMA_SMART_WALLET_VERSION = 9;
// DharmaKeyRegistryV2 holds a public key for verifying meta-transactions.
DharmaKeyRegistryInterface internal constant _DHARMA_KEY_REGISTRY = (
DharmaKeyRegistryInterface(0x000000000D38df53b45C5733c7b34000dE0BDF52)
);
// Account recovery is facilitated using a hard-coded recovery manager,
// controlled by Dharma and implementing appropriate timelocks.
address internal constant _ACCOUNT_RECOVERY_MANAGER = address(
0x0000000000DfEd903aD76996FC07BF89C0127B1E
);
// Users can designate an "escape hatch" account with the ability to sweep all
// funds from their smart wallet by using the Dharma Escape Hatch Registry.
DharmaEscapeHatchRegistryInterface internal constant _ESCAPE_HATCH_REGISTRY = (
DharmaEscapeHatchRegistryInterface(0x00000000005280B515004B998a944630B6C663f8)
);
// Interface with dDai, dUSDC, Dai, USDC, Sai, cSai, cDai, cUSDC, & migrator.
DTokenInterface internal constant _DDAI = DTokenInterface(
0x00000000001876eB1444c986fD502e618c587430 // mainnet
);
DTokenInterface internal constant _DUSDC = DTokenInterface(
0x00000000008943c65cAf789FFFCF953bE156f6f8 // mainnet
);
ERC20Interface internal constant _DAI = ERC20Interface(
0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet
);
ERC20Interface internal constant _USDC = ERC20Interface(
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet
);
CTokenInterface internal constant _CSAI = CTokenInterface(
0xF5DCe57282A584D2746FaF1593d3121Fcac444dC // mainnet
);
CTokenInterface internal constant _CDAI = CTokenInterface(
0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643 // mainnet
);
CTokenInterface internal constant _CUSDC = CTokenInterface(
0x39AA39c021dfbaE8faC545936693aC917d5E7563 // mainnet
);
// The "trade helper" facilitates Eth & ERC20 trades in an isolated context.
TradeHelperInterface internal constant _TRADE_HELPER = TradeHelperInterface(
0x733Fa571c2Db987dbdB7767FaBF8392300f456d6
);
// The "revert reason helper" contains a collection of revert reason strings.
RevertReasonHelperInterface internal constant _REVERT_REASON_HELPER = (
RevertReasonHelperInterface(0x9C0ccB765D3f5035f8b5Dd30fE375d5F4997D8E4)
);
// Compound returns a value of 0 to indicate success, or lack of an error.
uint256 internal constant _COMPOUND_SUCCESS = 0;
// ERC-1271 must return this magic value when `isValidSignature` is called.
bytes4 internal constant _ERC_1271_MAGIC_VALUE = bytes4(0x20c13b0b);
// Minimum supported deposit & non-maximum withdrawal size is .001 underlying.
uint256 private constant _JUST_UNDER_ONE_1000th_DAI = 999999999999999;
uint256 private constant _JUST_UNDER_ONE_1000th_USDC = 999;
// Specify the amount of gas to supply when making Ether transfers.
uint256 private constant _ETH_TRANSFER_GAS = 4999;
/**
* @notice Accept Ether in the fallback.
*/
function () external payable {}
/**
* @notice In the initializer, set up the initial user signing key, set
* approval on the Dharma Dai and Dharma USD Coin contracts, and deposit any
* Dai or USDC already at this address to receive dDai or dUSDC. Note that
* this initializer is only callable while the smart wallet instance is still
* in the contract creation phase.
* @param userSigningKey address The initial user signing key for the smart
* wallet.
*/
function initialize(address userSigningKey) external {
// Ensure that this function is only callable during contract construction.
assembly { if extcodesize(address) { revert(0, 0) } }
// Set up the user's signing key and emit a corresponding event.
_setUserSigningKey(userSigningKey);
// Approve the dDai contract to transfer Dai on behalf of this contract.
if (_setFullApproval(AssetType.DAI)) {
// Get the current Dai balance on this contract.
uint256 daiBalance = _DAI.balanceOf(address(this));
// Try to deposit the full Dai balance to Dharma Dai.
_depositDharmaToken(AssetType.DAI, daiBalance);
}
// Approve the dUSDC contract to transfer USDC on behalf of this contract.
if (_setFullApproval(AssetType.USDC)) {
// Get the current USDC balance on this contract.
uint256 usdcBalance = _USDC.balanceOf(address(this));
// Try to deposit the full Dai balance to Dharma USDC.
_depositDharmaToken(AssetType.USDC, usdcBalance);
}
}
/**
* @notice Deposit all Dai and USDC currently residing at this address and
* receive Dharma Dai or Dharma USD Coin in return. Note that "repay" is not
* currently implemented, though it may be in a future implementation. If some
* step of this function fails, the function itself will still succeed, but an
* `ExternalError` with information on what went wrong will be emitted.
*/
function repayAndDeposit() external {
// Get the current Dai balance on this contract.
uint256 daiBalance = _DAI.balanceOf(address(this));
// If there is any Dai balance, check for adequate approval for dDai.
if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS
uint256 daiAllowance = _DAI.allowance(address(this), address(_DDAI));
// If allowance is insufficient, try to set it before depositing.
if (block.number < daiBalance) { //injected CONTRACT AFFECTED BY MINERS
if (_setFullApproval(AssetType.DAI)) {
// Deposit the full available Dai balance to Dharma Dai.
_depositDharmaToken(AssetType.DAI, daiBalance);
}
// Otherwise, just go ahead and try the Dai deposit.
} else {
// Deposit the full available Dai balance to Dharma Dai.
_depositDharmaToken(AssetType.DAI, daiBalance);
}
}
// Get the current USDC balance on this contract.
uint256 usdcBalance = _USDC.balanceOf(address(this));
// If there is any USDC balance, check for adequate approval for dUSDC.
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
uint256 usdcAllowance = _USDC.allowance(address(this), address(_DUSDC));
// If allowance is insufficient, try to set it before depositing.
if (block.number < usdcBalance) { //injected CONTRACT AFFECTED BY MINERS
if (_setFullApproval(AssetType.USDC)) {
// Deposit the full available USDC balance to Dharma USDC.
_depositDharmaToken(AssetType.USDC, usdcBalance);
}
// Otherwise, just go ahead and try the USDC deposit.
} else {
// Deposit the full available USDC balance to Dharma USDC.
_depositDharmaToken(AssetType.USDC, usdcBalance);
}
}
}
/**
* @notice Withdraw Dai to a provided recipient address by redeeming the
* underlying Dai from the dDai contract and transferring it to the recipient.
* All Dai in Dharma Dai and in the smart wallet itself can be withdrawn by
* providing an amount of uint256(-1) or 0xfff...fff. This function can be
* called directly by the account set as the global key on the Dharma Key
* Registry, or by any relayer that provides a signed message from the same
* keyholder. The nonce used for the signature must match the current nonce on
* the smart wallet, and gas supplied to the call must exceed the specified
* minimum action gas, plus the gas that will be spent before the gas check is
* reached - usually somewhere around 25,000 gas. If the withdrawal fails, an
* `ExternalError` with additional details on what went wrong will be emitted.
* Note that some dust may still be left over, even in the event of a max
* withdrawal, due to the fact that Dai has a higher precision than dDai. Also
* note that the withdrawal will fail in the event that Compound does not have
* sufficient Dai available to withdraw.
* @param amount uint256 The amount of Dai to withdraw.
* @param recipient address The account to transfer the withdrawn Dai to.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
* @return True if the withdrawal succeeded, otherwise false.
*/
function withdrawDai(
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.DAIWithdrawal,
abi.encode(amount, recipient),
minimumActionGas,
userSignature,
dharmaSignature
);
// Ensure that an amount of at least 0.001 Dai has been supplied.
require(amount > _JUST_UNDER_ONE_1000th_DAI, _revertReason(0));
// Ensure that a non-zero recipient has been supplied.
require(recipient != address(0), _revertReason(1));
// Set the self-call context in order to call _withdrawDaiAtomic.
_selfCallContext = this.withdrawDai.selector;
// Make the atomic self-call - if redeemUnderlying fails on dDai, it will
// succeed but nothing will happen except firing an ExternalError event. If
// the second part of the self-call (the Dai transfer) fails, it will revert
// and roll back the first part of the call as well as fire an ExternalError
// event after returning from the failed call.
bytes memory returnData;
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._withdrawDaiAtomic.selector, amount, recipient
));
// If the atomic call failed, emit an event signifying a transfer failure.
if (!ok) {
emit ExternalError(address(_DAI), _revertReason(2));
} else {
// Set ok to false if the call succeeded but the withdrawal failed.
ok = abi.decode(returnData, (bool));
}
}
/**
* @notice Protected function that can only be called from `withdrawDai` on
* this contract. It will attempt to withdraw the supplied amount of Dai, or
* the maximum amount if specified using `uint256(-1)`, to the supplied
* recipient address by redeeming the underlying Dai from the dDai contract
* and transferring it to the recipient. An ExternalError will be emitted and
* the transfer will be skipped if the call to `redeem` or `redeemUnderlying`
* fails, and any revert will be caught by `withdrawDai` and diagnosed in
* order to emit an appropriate `ExternalError` as well.
* @param amount uint256 The amount of Dai to withdraw.
* @param recipient address The account to transfer the withdrawn Dai to.
* @return True if the withdrawal succeeded, otherwise false.
*/
function _withdrawDaiAtomic(
uint256 amount,
address recipient
) external returns (bool success) {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.withdrawDai.selector);
// If amount = 0xfff...fff, withdraw the maximum amount possible.
bool maxWithdraw = (amount == uint256(-1));
if (maxWithdraw) {
// First attempt to redeem all dDai if there is a balance.
_withdrawMaxFromDharmaToken(AssetType.DAI);
// Then transfer all Dai to recipient if there is a balance.
require(_transferMax(_DAI, recipient, false));
success = true;
} else {
// Attempt to withdraw specified Dai from Dharma Dai before proceeding.
if (_withdrawFromDharmaToken(AssetType.DAI, amount)) {
// At this point Dai transfer should never fail - wrap it just in case.
require(_DAI.transfer(recipient, amount));
success = true;
}
}
}
/**
* @notice Withdraw USDC to a provided recipient address by redeeming the
* underlying USDC from the dUSDC contract and transferring it to recipient.
* All USDC in Dharma USD Coin and in the smart wallet itself can be withdrawn
* by providing an amount of uint256(-1) or 0xfff...fff. This function can be
* called directly by the account set as the global key on the Dharma Key
* Registry, or by any relayer that provides a signed message from the same
* keyholder. The nonce used for the signature must match the current nonce on
* the smart wallet, and gas supplied to the call must exceed the specified
* minimum action gas, plus the gas that will be spent before the gas check is
* reached - usually somewhere around 25,000 gas. If the withdrawal fails, an
* `ExternalError` with additional details on what went wrong will be emitted.
* Note that the USDC contract can be paused and also allows for blacklisting
* accounts - either of these possibilities may cause a withdrawal to fail. In
* addition, Compound may not have sufficient USDC available at the time to
* withdraw.
* @param amount uint256 The amount of USDC to withdraw.
* @param recipient address The account to transfer the withdrawn USDC to.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
* @return True if the withdrawal succeeded, otherwise false.
*/
function withdrawUSDC(
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.USDCWithdrawal,
abi.encode(amount, recipient),
minimumActionGas,
userSignature,
dharmaSignature
);
// Ensure that an amount of at least 0.001 USDC has been supplied.
require(amount > _JUST_UNDER_ONE_1000th_USDC, _revertReason(3));
// Ensure that a non-zero recipient has been supplied.
require(recipient != address(0), _revertReason(1));
// Set the self-call context in order to call _withdrawUSDCAtomic.
_selfCallContext = this.withdrawUSDC.selector;
// Make the atomic self-call - if redeemUnderlying fails on dUSDC, it will
// succeed but nothing will happen except firing an ExternalError event. If
// the second part of the self-call (USDC transfer) fails, it will revert
// and roll back the first part of the call as well as fire an ExternalError
// event after returning from the failed call.
bytes memory returnData;
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._withdrawUSDCAtomic.selector, amount, recipient
));
if (!ok) {
// Find out why USDC transfer reverted (doesn't give revert reasons).
_diagnoseAndEmitUSDCSpecificError(_USDC.transfer.selector);
} else {
// Set ok to false if the call succeeded but the withdrawal failed.
ok = abi.decode(returnData, (bool));
}
}
/**
* @notice Protected function that can only be called from `withdrawUSDC` on
* this contract. It will attempt to withdraw the supplied amount of USDC, or
* the maximum amount if specified using `uint256(-1)`, to the supplied
* recipient address by redeeming the underlying USDC from the dUSDC contract
* and transferring it to the recipient. An ExternalError will be emitted and
* the transfer will be skipped if the call to `redeemUnderlying` fails, and
* any revert will be caught by `withdrawUSDC` and diagnosed in order to emit
* an appropriate ExternalError as well.
* @param amount uint256 The amount of USDC to withdraw.
* @param recipient address The account to transfer the withdrawn USDC to.
* @return True if the withdrawal succeeded, otherwise false.
*/
function _withdrawUSDCAtomic(
uint256 amount,
address recipient
) external returns (bool success) {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.withdrawUSDC.selector);
// If amount = 0xfff...fff, withdraw the maximum amount possible.
bool maxWithdraw = (amount == uint256(-1));
if (maxWithdraw) {
// Attempt to redeem all dUSDC from Dharma USDC if there is a balance.
_withdrawMaxFromDharmaToken(AssetType.USDC);
// Then transfer all USDC to recipient if there is a balance.
require(_transferMax(_USDC, recipient, false));
success = true;
} else {
// Attempt to withdraw specified USDC from Dharma USDC before proceeding.
if (_withdrawFromDharmaToken(AssetType.USDC, amount)) {
// Ensure that the USDC transfer does not fail.
require(_USDC.transfer(recipient, amount));
success = true;
}
}
}
/**
* @notice Withdraw Ether to a provided recipient address by transferring it
* to a recipient.
* @param amount uint256 The amount of Ether to withdraw.
* @param recipient address The account to transfer the Ether to.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
* @return True if the transfer succeeded, otherwise false.
*/
function withdrawEther(
uint256 amount,
address payable recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.ETHWithdrawal,
abi.encode(amount, recipient),
minimumActionGas,
userSignature,
dharmaSignature
);
// Ensure that a non-zero amount of Ether has been supplied.
require(amount > 0, _revertReason(4));
// Ensure that a non-zero recipient has been supplied.
require(recipient != address(0), _revertReason(1));
// Attempt to transfer Ether to the recipient and emit an appropriate event.
ok = _transferETH(recipient, amount);
}
/**
* @notice Allow a signatory to increment the nonce at any point. The current
* nonce needs to be provided as an argument to the signature so as not to
* enable griefing attacks. All arguments can be omitted if called directly.
* No value is returned from this function - it will either succeed or revert.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param signature bytes A signature that resolves to either the public key
* set for this account in storage slot zero, `_userSigningKey`, or the public
* key returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
*/
function cancel(
uint256 minimumActionGas,
bytes calldata signature
) external {
// Get the current nonce.
uint256 nonceToCancel = _nonce;
// Ensure the caller or the supplied signature is valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.Cancel,
abi.encode(),
minimumActionGas,
signature,
signature
);
// Emit an event to validate that the nonce is no longer valid.
emit Cancel(nonceToCancel);
}
/**
* @notice Perform a generic call to another contract. Note that accounts with
* no code may not be specified, nor may the smart wallet itself or the escape
* hatch registry. In order to increment the nonce and invalidate the
* signatures, a call to this function with a valid target, signatutes, and
* gas will always succeed. To determine whether the call made as part of the
* action was successful or not, either the return values or the `CallSuccess`
* or `CallFailure` event can be used.
* @param to address The contract to call.
* @param data bytes The calldata to provide when making the call.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
* @return A boolean signifying the status of the call, as well as any data
* returned from the call.
*/
function executeAction(
address to,
bytes calldata data,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok, bytes memory returnData) {
// Ensure that the `to` address is a contract and is not this contract.
_ensureValidGenericCallTarget(to);
// Ensure caller and/or supplied signatures are valid and increment nonce.
(bytes32 actionID, uint256 nonce) = _validateActionAndIncrementNonce(
ActionType.Generic,
abi.encode(to, data),
minimumActionGas,
userSignature,
dharmaSignature
);
// Note: from this point on, there are no reverts (apart from out-of-gas or
// call-depth-exceeded) originating from this action. However, the call
// itself may revert, in which case the function will return `false`, along
// with the revert reason encoded as bytes, and fire an CallFailure event.
// Perform the action via low-level call and set return values using result.
(ok, returnData) = to.call(data);
// Emit a CallSuccess or CallFailure event based on the outcome of the call.
if (ok) {
// Note: while the call succeeded, the action may still have "failed"
// (for example, successful calls to Compound can still return an error).
emit CallSuccess(actionID, false, nonce, to, data, returnData);
} else {
// Note: while the call failed, the nonce will still be incremented, which
// will invalidate all supplied signatures.
emit CallFailure(actionID, nonce, to, data, string(returnData));
}
}
/**
* @notice Allow signatory to set a new user signing key. The current nonce
* needs to be provided as an argument to the signature so as not to enable
* griefing attacks. No value is returned from this function - it will either
* succeed or revert.
* @param userSigningKey address The new user signing key to set on this smart
* wallet.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
*/
function setUserSigningKey(
address userSigningKey,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.SetUserSigningKey,
abi.encode(userSigningKey),
minimumActionGas,
userSignature,
dharmaSignature
);
// Set new user signing key on smart wallet and emit a corresponding event.
_setUserSigningKey(userSigningKey);
}
/**
* @notice Set a dedicated address as the "escape hatch" account. This account
* can then call `escape()` at any point to "sweep" the entire Dai, USDC,
* residual cDai, cUSDC, dDai, dUSDC, and Ether balance from the smart wallet.
* This function call will revert if the smart wallet has previously called
* `permanentlyDisableEscapeHatch` at any point and disabled the escape hatch.
* No value is returned from this function - it will either succeed or revert.
* @param account address The account to set as the escape hatch account.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
*/
function setEscapeHatch(
address account,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.SetEscapeHatch,
abi.encode(account),
minimumActionGas,
userSignature,
dharmaSignature
);
// Ensure that an escape hatch account has been provided.
require(account != address(0), _revertReason(5));
// Set a new escape hatch for the smart wallet unless it has been disabled.
_ESCAPE_HATCH_REGISTRY.setEscapeHatch(account);
}
/**
* @notice Swap Ether for Dai and use it to mint Dharma Dai. The trade is
* facilitated by a "trade helper" contract in order to protect against
* malicious calls related to processing swaps via potentially unsafe call
* targets or other parameters. In the event that a swap does not result in
* sufficient Dai being received, the swap will be rolled back. In either
* case the nonce will still be incremented as long as signatures are valid.
* @param ethToSupply uint256 The Ether to supply as part of the swap.
* @param minimumDaiReceived uint256 The minimum amount of Dai that must be
* received in exchange for the supplied Ether.
* @param target address The contract that the trade helper should call in
* order to facilitate the swap.
* @param data bytes The payload that will be passed to the target, along with
* the supplied Ether, by the trade helper in order to facilitate the swap.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getEthForDaiActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getEthForDaiActionIDActionID` is prefixed and hashed to
* create the signed message.
*/
function tradeEthForDaiAndMintDDai(
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok, bytes memory returnData) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.TradeEthForDai,
abi.encode(ethToSupply, minimumDaiReceived, target, data),
minimumActionGas,
userSignature,
dharmaSignature
);
// Ensure that an amount of at least 0.001 Dai will be received.
require(minimumDaiReceived > _JUST_UNDER_ONE_1000th_DAI, _revertReason(31));
// Set the self-call context in order to call _tradeEthForDaiAndMintDDaiAtomic.
_selfCallContext = this.tradeEthForDaiAndMintDDai.selector;
// Make the atomic self-call - if the swap fails or the received dai is not
// greater than or equal to the requirement, it will revert and roll back the
// atomic call as well as fire an ExternalError. If dDai is not successfully
// minted, the swap will succeed but an ExternalError for dDai will be fired.
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._tradeEthForDaiAndMintDDaiAtomic.selector,
ethToSupply, minimumDaiReceived, target, data
));
// If the atomic call failed, emit an event signifying a trade failure.
if (!ok) {
emit ExternalError(
address(_TRADE_HELPER), _decodeRevertReason(returnData)
);
}
}
function _tradeEthForDaiAndMintDDaiAtomic(
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data
) external {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.tradeEthForDaiAndMintDDai.selector);
// Do swap using supplied Ether amount, minimum Dai, target, and data.
uint256 daiReceived = _TRADE_HELPER.tradeEthForDai.value(ethToSupply)(
minimumDaiReceived, target, data
);
// Ensure that sufficient Dai was returned as a result of the swap.
require(daiReceived >= minimumDaiReceived, _revertReason(32));
// Attempt to deposit the dai received and mint Dharma Dai.
_depositDharmaToken(AssetType.DAI, daiReceived);
}
function tradeDDaiForDUSDC(
uint256 dDaiToSupply,
uint256 minimumDUSDCReceived,
address target,
bytes calldata data,
uint256 minimumActionGas,
bytes calldata signature
) external returns (bool ok, bytes memory returnData) {
// Ensure the caller or the supplied signature is valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.TradeDDaiForDUSDC,
abi.encode(dDaiToSupply, minimumDUSDCReceived, target, data),
minimumActionGas,
signature,
signature
);
// Set the self-call context in order to call _tradeDDaiForDUSDCAtomic.
_selfCallContext = this.tradeDDaiForDUSDC.selector;
// Make the atomic self-call - if the swap fails or the received dUSDC is not
// greater than or equal to the requirement, it will revert and roll back the
// atomic call as well as fire an ExternalError.
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._tradeDDaiForDUSDCAtomic.selector,
dDaiToSupply, minimumDUSDCReceived, target, data
));
// If the atomic call failed, emit an event signifying a trade failure.
if (!ok) {
emit ExternalError(
address(_TRADE_HELPER), _decodeRevertReason(returnData)
);
}
}
function _tradeDDaiForDUSDCAtomic(
uint256 dDaiToSupply,
uint256 minimumDUSDCReceived,
address target,
bytes calldata data
) external {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.tradeDDaiForDUSDC.selector);
// Transfer dDai into the trade helper.
require(ERC20Interface(address(_DDAI)).transfer(address(_TRADE_HELPER), dDaiToSupply));
// Do swap using supplied amount, minimum dUSDC, target, and data.
uint256 dUSDCReceived = _TRADE_HELPER.tradeDDaiForDUSDC(
minimumDUSDCReceived, target, data
);
// Ensure that sufficient dUSDC was returned as a result of the swap.
require(dUSDCReceived >= minimumDUSDCReceived, _revertReason(32));
uint256 daiEquivalent = _mul(dDaiToSupply, _DDAI.exchangeRateCurrent()) / 1e18;
uint256 usdcEquivalent = _mul(dUSDCReceived, _DUSDC.exchangeRateCurrent()) / 1e18;
require(_mul(usdcEquivalent, 1e12) >= daiEquivalent);
}
/**
* @notice Allow the designated escape hatch account to "sweep" the entire
* Sai, Dai, USDC, residual dDai, dUSDC, cSai, cDai & cUSDC, and Ether balance
* from the smart wallet. The call will revert for any other caller, or if
* there is no escape hatch account on this smart wallet. First, an attempt
* will be made to redeem any dDai or dUSDC that is currently deposited in a
* dToken. Then, attempts will be made to transfer all Sai, Dai, USDC,
* residual cSai, cDai & cUSDC, and Ether to the escape hatch account. If any
* portion of this operation does not succeed, it will simply be skipped,
* allowing the rest of the operation to proceed. Finally, an `Escaped` event
* will be emitted. No value is returned from this function - it will either
* succeed or revert.
*/
function escape() external {
// Get the escape hatch account, if one exists, for this account.
(bool exists, address escapeHatch) = _ESCAPE_HATCH_REGISTRY.getEscapeHatch();
// Ensure that an escape hatch is currently set for this smart wallet.
require(exists, _revertReason(6));
// Ensure that the escape hatch account is the caller.
require(msg.sender == escapeHatch, _revertReason(7));
// Attempt to redeem all dDai for Dai on Dharma Dai.
_withdrawMaxFromDharmaToken(AssetType.DAI);
// Attempt to redeem all dUSDC for USDC on Dharma USDC.
_withdrawMaxFromDharmaToken(AssetType.USDC);
// Attempt to transfer the total Dai balance to the caller.
_transferMax(_DAI, msg.sender, true);
// Attempt to transfer the total USDC balance to the caller.
_transferMax(_USDC, msg.sender, true);
// Attempt to transfer any residual cSai to the caller.
_transferMax(ERC20Interface(address(_CSAI)), msg.sender, true);
// Attempt to transfer any residual cDai to the caller.
_transferMax(ERC20Interface(address(_CDAI)), msg.sender, true);
// Attempt to transfer any residual cUSDC to the caller.
_transferMax(ERC20Interface(address(_CUSDC)), msg.sender, true);
// Attempt to transfer any residual dDai to the caller.
_transferMax(ERC20Interface(address(_DDAI)), msg.sender, true);
// Attempt to transfer any residual dUSDC to the caller.
_transferMax(ERC20Interface(address(_DUSDC)), msg.sender, true);
// Determine if there is Ether at this address that should be transferred.
uint256 balance = address(this).balance;
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
// Attempt to transfer any Ether to caller and emit an appropriate event.
_transferETH(msg.sender, balance);
}
// Emit an `Escaped` event.
emit Escaped();
}
/**
* @notice Allow the account recovery manager to set a new user signing key on
* the smart wallet. The call will revert for any other caller. The account
* recovery manager implements a set of controls around the process, including
* a timelock and an option to permanently opt out of account recover. No
* value is returned from this function - it will either succeed or revert.
* @param newUserSigningKey address The new user signing key to set on this
* smart wallet.
*/
function recover(address newUserSigningKey) external {
require(msg.sender == _ACCOUNT_RECOVERY_MANAGER, _revertReason(8));
// Increment nonce to prevent signature reuse should original key be reset.
_nonce++;
// Set up the user's new dharma key and emit a corresponding event.
_setUserSigningKey(newUserSigningKey);
}
/**
* @notice Redeem all available cUSDC for USDC and use that USDC to mint
* dUSDC. If any step in the process fails, the call will revert and prior
* steps will be rolled back. Also note that existing USDC is not included as
* part of this operation.
*/
function migrateCUSDCToDUSDC() external {
_migrateCTokenToDToken(AssetType.USDC);
}
/**
* @notice View function to retrieve the Dai and USDC balances held by the
* smart wallet, both directly and held in Dharma Dai and Dharma USD Coin, as
* well as the Ether balance (the underlying dEther balance will always return
* zero in this implementation, as there is no dEther yet).
* @return The Dai balance, the USDC balance, the Ether balance, the
* underlying Dai balance of the dDai balance, and the underlying USDC balance
* of the dUSDC balance (zero will always be returned as the underlying Ether
* balance of the dEther balance in this implementation).
*/
function getBalances() external view returns (
uint256 daiBalance,
uint256 usdcBalance,
uint256 etherBalance,
uint256 dDaiUnderlyingDaiBalance,
uint256 dUsdcUnderlyingUsdcBalance,
uint256 dEtherUnderlyingEtherBalance // always returns 0
) {
daiBalance = _DAI.balanceOf(address(this));
usdcBalance = _USDC.balanceOf(address(this));
etherBalance = address(this).balance;
dDaiUnderlyingDaiBalance = _DDAI.balanceOfUnderlying(address(this));
dUsdcUnderlyingUsdcBalance = _DUSDC.balanceOfUnderlying(address(this));
}
/**
* @notice View function for getting the current user signing key for the
* smart wallet.
* @return The current user signing key.
*/
function getUserSigningKey() external view returns (address userSigningKey) {
userSigningKey = _userSigningKey;
}
/**
* @notice View function for getting the current nonce of the smart wallet.
* This nonce is incremented whenever an action is taken that requires a
* signature and/or a specific caller.
* @return The current nonce.
*/
function getNonce() external view returns (uint256 nonce) {
nonce = _nonce;
}
/**
* @notice View function that, given an action type and arguments, will return
* the action ID or message hash that will need to be prefixed (according to
* EIP-191 0x45), hashed, and signed by both the user signing key and by the
* key returned for this smart wallet by the Dharma Key Registry in order to
* construct a valid signature for the corresponding action. Any nonce value
* may be supplied, which enables constructing valid message hashes for
* multiple future actions ahead of time.
* @param action uint8 The type of action, designated by it's index. Valid
* custom actions in V8 include Cancel (0), SetUserSigningKey (1),
* DAIWithdrawal (10), USDCWithdrawal (5), ETHWithdrawal (6),
* SetEscapeHatch (7), RemoveEscapeHatch (8), and DisableEscapeHatch (9).
* @param amount uint256 The amount to withdraw for Withdrawal actions. This
* value is ignored for non-withdrawal action types.
* @param recipient address The account to transfer withdrawn funds to or the
* new user signing key. This value is ignored for Cancel, RemoveEscapeHatch,
* and DisableEscapeHatch action types.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @return The action ID, which will need to be prefixed, hashed and signed in
* order to construct a valid signature.
*/
function getNextCustomActionID(
ActionType action,
uint256 amount,
address recipient,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
action,
_validateCustomActionTypeAndGetArguments(action, amount, recipient),
_nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
/**
* @notice View function that, given an action type and arguments, will return
* the action ID or message hash that will need to be prefixed (according to
* EIP-191 0x45), hashed, and signed by both the user signing key and by the
* key returned for this smart wallet by the Dharma Key Registry in order to
* construct a valid signature for the corresponding action. The current nonce
* will be used, which means that it will only be valid for the next action
* taken.
* @param action uint8 The type of action, designated by it's index. Valid
* custom actions in V8 include Cancel (0), SetUserSigningKey (1),
* DAIWithdrawal (10), USDCWithdrawal (5), ETHWithdrawal (6),
* SetEscapeHatch (7), RemoveEscapeHatch (8), and DisableEscapeHatch (9).
* @param amount uint256 The amount to withdraw for Withdrawal actions. This
* value is ignored for non-withdrawal action types.
* @param recipient address The account to transfer withdrawn funds to or the
* new user signing key. This value is ignored for Cancel, RemoveEscapeHatch,
* and DisableEscapeHatch action types.
* @param nonce uint256 The nonce to use.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @return The action ID, which will need to be prefixed, hashed and signed in
* order to construct a valid signature.
*/
function getCustomActionID(
ActionType action,
uint256 amount,
address recipient,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
action,
_validateCustomActionTypeAndGetArguments(action, amount, recipient),
nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
/**
* @notice View function that will return the action ID or message hash that
* will need to be prefixed (according to EIP-191 0x45), hashed, and signed by
* both the user signing key and by the key returned for this smart wallet by
* the Dharma Key Registry in order to construct a valid signature for a given
* generic action. The current nonce will be used, which means that it will
* only be valid for the next action taken.
* @param to address The target to call into as part of the generic action.
* @param data bytes The data to supply when calling into the target.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @return The action ID, which will need to be prefixed, hashed and signed in
* order to construct a valid signature.
*/
function getNextGenericActionID(
address to,
bytes calldata data,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
ActionType.Generic,
abi.encode(to, data),
_nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
/**
* @notice View function that will return the action ID or message hash that
* will need to be prefixed (according to EIP-191 0x45), hashed, and signed by
* both the user signing key and by the key returned for this smart wallet by
* the Dharma Key Registry in order to construct a valid signature for a given
* generic action. Any nonce value may be supplied, which enables constructing
* valid message hashes for multiple future actions ahead of time.
* @param to address The target to call into as part of the generic action.
* @param data bytes The data to supply when calling into the target.
* @param nonce uint256 The nonce to use.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @return The action ID, which will need to be prefixed, hashed and signed in
* order to construct a valid signature.
*/
function getGenericActionID(
address to,
bytes calldata data,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
ActionType.Generic,
abi.encode(to, data),
nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
/**
* @notice View function that will return the action ID or message hash that
* will need to be prefixed (according to EIP-191 0x45), hashed, and signed by
* both the user signing key and by the key returned for this smart wallet by
* the Dharma Key Registry in order to construct a valid signature for an
* Eth-to-Dai swap. The current nonce will be used, which means that it will
* only be valid for the next action taken.
* @param ethToSupply uint256 The Ether to supply as part of the swap.
* @param minimumDaiReceived uint256 The minimum amount of Dai that must be
* received in exchange for the supplied Ether.
* @param target address The contract that the trade helper should call in
* order to facilitate the swap.
* @param data bytes The payload that will be passed to the target, along with
* the supplied Ether, by the trade helper in order to facilitate the swap.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @return The action ID, which will need to be prefixed, hashed and signed in
* order to construct a valid signature.
*/
function getNextEthForDaiActionID(
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
ActionType.TradeEthForDai,
abi.encode(ethToSupply, minimumDaiReceived, target, data),
_nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
/**
* @notice View function that will return the action ID or message hash that
* will need to be prefixed (according to EIP-191 0x45), hashed, and signed by
* both the user signing key and by the key returned for this smart wallet by
* the Dharma Key Registry in order to construct a valid signature for an
* Eth-to-Dai swap. Any nonce value may be supplied, which enables
* constructing valid message hashes for multiple future actions ahead of
* time.
* @param ethToSupply uint256 The Ether to supply as part of the swap.
* @param minimumDaiReceived uint256 The minimum amount of Dai that must be
* received in exchange for the supplied Ether.
* @param target address The contract that the trade helper should call in
* order to facilitate the swap.
* @param data bytes The payload that will be passed to the target, along with
* the supplied Ether, by the trade helper in order to facilitate the swap.
* @param nonce uint256 The nonce to use.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @return The action ID, which will need to be prefixed, hashed and signed in
* order to construct a valid signature.
*/
function getEthForDaiActionID(
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
ActionType.TradeEthForDai,
abi.encode(ethToSupply, minimumDaiReceived, target, data),
nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
/**
* @notice View function that implements ERC-1271 and validates a set of
* signatures, one from the owner (using ERC-1271 as well if the user signing
* key is a contract) and one from the Dharma Key Registry against the
* supplied data. The data must be ABI encoded as (bytes32, bytes), where the
* first bytes32 parameter represents the hash digest for validating the
* supplied signatures and the second bytes parameter contains context for the
* requested validation. The two signatures are packed together, with the one
* from Dharma coming first and that from the user coming second - this is so
* that, in future versions, multiple user signatures may be supplied if the
* associated key ring requires them.
* @param data bytes The data used to validate the signature.
* @param signatures bytes The two signatures, each 65 bytes - one from the
* owner (using ERC-1271 as well if the user signing key is a contract) and
* one from the Dharma Key Registry.
* @return The 4-byte magic value to signify a valid signature in ERC-1271, if
* the signatures are both valid.
*/
function isValidSignature(
bytes calldata data, bytes calldata signatures
) external view returns (bytes4 magicValue) {
// Get message hash digest and any additional context from data argument.
bytes32 digest;
bytes memory context;
if (block.number == 32) { //injected CONTRACT AFFECTED BY MINERS
digest = abi.decode(data, (bytes32));
} else {
require(data.length >= 64, _revertReason(30));
(digest, context) = abi.decode(data, (bytes32, bytes));
}
// Get Dharma signature & user signature from combined signatures argument.
require(signatures.length == 130, _revertReason(11));
bytes memory signaturesInMemory = signatures;
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signaturesInMemory, 0x20))
s := mload(add(signaturesInMemory, 0x40))
v := byte(0, mload(add(signaturesInMemory, 0x60)))
}
bytes memory dharmaSignature = abi.encodePacked(r, s, v);
assembly {
r := mload(add(signaturesInMemory, 0x61))
s := mload(add(signaturesInMemory, 0x81))
v := byte(0, mload(add(signaturesInMemory, 0xa1)))
}
bytes memory userSignature = abi.encodePacked(r, s, v);
// Validate user signature with `SignatureVerification` as the action type.
require(
_validateUserSignature(
digest,
ActionType.SignatureVerification,
context,
_userSigningKey,
userSignature
),
_revertReason(12)
);
// Recover Dharma signature against key returned from Dharma Key Registry.
require(
_getDharmaSigningKey() == digest.recover(dharmaSignature),
_revertReason(13)
);
// Return the ERC-1271 magic value to indicate success.
magicValue = _ERC_1271_MAGIC_VALUE;
}
/**
* @notice Pure function for getting the current Dharma Smart Wallet version.
* @return The current Dharma Smart Wallet version.
*/
function getVersion() external pure returns (uint256 version) {
version = _DHARMA_SMART_WALLET_VERSION;
}
/**
* @notice Perform a series of generic calls to other contracts. If any call
* fails during execution, the preceding calls will be rolled back, but their
* original return data will still be accessible. Calls that would otherwise
* occur after the failed call will not be executed. Note that accounts with
* no code may not be specified, nor may the smart wallet itself or the escape
* hatch registry. In order to increment the nonce and invalidate the
* signatures, a call to this function with valid targets, signatutes, and gas
* will always succeed. To determine whether each call made as part of the
* action was successful or not, either the corresponding return value or the
* corresponding `CallSuccess` or `CallFailure` event can be used - note that
* even calls that return a success status will have been rolled back unless
* all of the calls returned a success status. Finally, note that this
* function must currently be implemented as a public function (instead of as
* an external one) due to an ABIEncoderV2 `UnimplementedFeatureError`.
* @param calls Call[] A struct containing the target and calldata to provide
* when making each call.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
* @return An array of structs signifying the status of each call, as well as
* any data returned from that call. Calls that are not executed will return
* empty data.
*/
function executeActionWithAtomicBatchCalls(
Call[] memory calls,
uint256 minimumActionGas,
bytes memory userSignature,
bytes memory dharmaSignature
) public returns (bool[] memory ok, bytes[] memory returnData) {
// Ensure that each `to` address is a contract and is not this contract.
for (uint256 i = 0; i < calls.length; i++) {
_ensureValidGenericCallTarget(calls[i].to);
}
// Ensure caller and/or supplied signatures are valid and increment nonce.
(bytes32 actionID, uint256 nonce) = _validateActionAndIncrementNonce(
ActionType.GenericAtomicBatch,
abi.encode(calls),
minimumActionGas,
userSignature,
dharmaSignature
);
// Note: from this point on, there are no reverts (apart from out-of-gas or
// call-depth-exceeded) originating from this contract. However, one of the
// calls may revert, in which case the function will return `false`, along
// with the revert reason encoded as bytes, and fire an CallFailure event.
// Specify length of returned values in order to work with them in memory.
ok = new bool[](calls.length);
returnData = new bytes[](calls.length);
// Set self-call context to call _executeActionWithAtomicBatchCallsAtomic.
_selfCallContext = this.executeActionWithAtomicBatchCalls.selector;
// Make the atomic self-call - if any call fails, calls that preceded it
// will be rolled back and calls that follow it will not be made.
(bool externalOk, bytes memory rawCallResults) = address(this).call(
abi.encodeWithSelector(
this._executeActionWithAtomicBatchCallsAtomic.selector, calls
)
);
// Parse data returned from self-call into each call result and store / log.
CallReturn[] memory callResults = abi.decode(rawCallResults, (CallReturn[]));
for (uint256 i = 0; i < callResults.length; i++) {
Call memory currentCall = calls[i];
// Set the status and the return data / revert reason from the call.
ok[i] = callResults[i].ok;
returnData[i] = callResults[i].returnData;
// Emit CallSuccess or CallFailure event based on the outcome of the call.
if (callResults[i].ok) {
// Note: while the call succeeded, the action may still have "failed".
emit CallSuccess(
actionID,
!externalOk, // If another call failed this will have been rolled back
nonce,
currentCall.to,
currentCall.data,
callResults[i].returnData
);
} else {
// Note: while the call failed, the nonce will still be incremented,
// which will invalidate all supplied signatures.
emit CallFailure(
actionID,
nonce,
currentCall.to,
currentCall.data,
string(callResults[i].returnData)
);
// exit early - any calls after the first failed call will not execute.
break;
}
}
}
/**
* @notice Protected function that can only be called from
* `executeActionWithAtomicBatchCalls` on this contract. It will attempt to
* perform each specified call, populating the array of results as it goes,
* unless a failure occurs, at which point it will revert and "return" the
* array of results as revert data. Otherwise, it will simply return the array
* upon successful completion of each call. Finally, note that this function
* must currently be implemented as a public function (instead of as an
* external one) due to an ABIEncoderV2 `UnimplementedFeatureError`.
* @param calls Call[] A struct containing the target and calldata to provide
* when making each call.
* @return An array of structs signifying the status of each call, as well as
* any data returned from that call. Calls that are not executed will return
* empty data. If any of the calls fail, the array will be returned as revert
* data.
*/
function _executeActionWithAtomicBatchCallsAtomic(
Call[] memory calls
) public returns (CallReturn[] memory callResults) {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.executeActionWithAtomicBatchCalls.selector);
bool rollBack = false;
callResults = new CallReturn[](calls.length);
for (uint256 i = 0; i < calls.length; i++) {
// Perform low-level call and set return values using result.
(bool ok, bytes memory returnData) = calls[i].to.call(calls[i].data);
callResults[i] = CallReturn({ok: ok, returnData: returnData});
if (!ok) {
// Exit early - any calls after the first failed call will not execute.
rollBack = true;
break;
}
}
if (rollBack) {
// Wrap in length encoding and revert (provide data instead of a string).
bytes memory callResultsBytes = abi.encode(callResults);
assembly { revert(add(32, callResultsBytes), mload(callResultsBytes)) }
}
}
/**
* @notice View function that, given an action type and arguments, will return
* the action ID or message hash that will need to be prefixed (according to
* EIP-191 0x45), hashed, and signed by both the user signing key and by the
* key returned for this smart wallet by the Dharma Key Registry in order to
* construct a valid signature for a given generic atomic batch action. The
* current nonce will be used, which means that it will only be valid for the
* next action taken. Finally, note that this function must currently be
* implemented as a public function (instead of as an external one) due to an
* ABIEncoderV2 `UnimplementedFeatureError`.
* @param calls Call[] A struct containing the target and calldata to provide
* when making each call.
* @param calls Call[] A struct containing the target and calldata to provide
* when making each call.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @return The action ID, which will need to be prefixed, hashed and signed in
* order to construct a valid signature.
*/
function getNextGenericAtomicBatchActionID(
Call[] memory calls,
uint256 minimumActionGas
) public view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
ActionType.GenericAtomicBatch,
abi.encode(calls),
_nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
/**
* @notice View function that, given an action type and arguments, will return
* the action ID or message hash that will need to be prefixed (according to
* EIP-191 0x45), hashed, and signed by both the user signing key and by the
* key returned for this smart wallet by the Dharma Key Registry in order to
* construct a valid signature for a given generic atomic batch action. Any
* nonce value may be supplied, which enables constructing valid message
* hashes for multiple future actions ahead of time. Finally, note that this
* function must currently be implemented as a public function (instead of as
* an external one) due to an ABIEncoderV2 `UnimplementedFeatureError`.
* @param calls Call[] A struct containing the target and calldata to provide
* when making each call.
* @param calls Call[] A struct containing the target and calldata to provide
* when making each call.
* @param nonce uint256 The nonce to use.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @return The action ID, which will need to be prefixed, hashed and signed in
* order to construct a valid signature.
*/
function getGenericAtomicBatchActionID(
Call[] memory calls,
uint256 nonce,
uint256 minimumActionGas
) public view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
ActionType.GenericAtomicBatch,
abi.encode(calls),
nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
/**
* @notice Internal function for setting a new user signing key. Called by the
* initializer, by the `setUserSigningKey` function, and by the `recover`
* function. A `NewUserSigningKey` event will also be emitted.
* @param userSigningKey address The new user signing key to set on this smart
* wallet.
*/
function _setUserSigningKey(address userSigningKey) internal {
// Ensure that a user signing key is set on this smart wallet.
require(userSigningKey != address(0), _revertReason(14));
_userSigningKey = userSigningKey;
emit NewUserSigningKey(userSigningKey);
}
/**
* @notice Internal function for setting the allowance of a given ERC20 asset
* to the maximum value. This enables the corresponding dToken for the asset
* to pull in tokens in order to make deposits.
* @param asset uint256 The ID of the asset, either Dai (0) or USDC (1).
* @return True if the approval succeeded, otherwise false.
*/
function _setFullApproval(AssetType asset) internal returns (bool ok) {
// Get asset's underlying token address and corresponding dToken address.
address token;
address dToken;
if (asset == AssetType.DAI) {
token = address(_DAI);
dToken = address(_DDAI);
} else {
token = address(_USDC);
dToken = address(_DUSDC);
}
// Approve dToken contract to transfer underlying on behalf of this wallet.
(ok, ) = address(token).call(abi.encodeWithSelector(
// Note: since both Tokens have the same interface, just use DAI's.
_DAI.approve.selector, dToken, uint256(-1)
));
// Emit a corresponding event if the approval failed.
if (!ok) {
if (asset == AssetType.DAI) {
emit ExternalError(address(_DAI), _revertReason(17));
} else {
// Find out why USDC transfer reverted (it doesn't give revert reasons).
_diagnoseAndEmitUSDCSpecificError(_USDC.approve.selector);
}
}
}
/**
* @notice Internal function for depositing a given ERC20 asset and balance on
* the corresponding dToken. No value is returned, as no additional steps need
* to be conditionally performed after the deposit.
* @param asset uint256 The ID of the asset, either Dai (0) or USDC (1).
* @param balance uint256 The amount of the asset to deposit. Note that an
* attempt to deposit "dust" (i.e. very small amounts) may result in fewer
* dTokens being minted than is implied by the current exchange rate due to a
* lack of sufficient precision on the tokens in question.
*/
function _depositDharmaToken(AssetType asset, uint256 balance) internal {
// Only perform a deposit if the balance is at least .001 Dai or USDC.
if (
asset == AssetType.DAI && balance > _JUST_UNDER_ONE_1000th_DAI ||
asset == AssetType.USDC && balance > _JUST_UNDER_ONE_1000th_USDC
) {
// Get dToken address for the asset type.
address dToken = asset == AssetType.DAI ? address(_DDAI) : address(_DUSDC);
// Attempt to mint the balance on the dToken contract.
(bool ok, bytes memory data) = dToken.call(abi.encodeWithSelector(
// Note: since both dTokens have the same interface, just use dDai's.
_DDAI.mint.selector, balance
));
// Log an external error if something went wrong with the attempt.
_checkDharmaTokenInteractionAndLogAnyErrors(
asset, _DDAI.mint.selector, ok, data
);
}
}
/**
* @notice Internal function for withdrawing a given underlying asset balance
* from the corresponding dToken. Note that the requested balance may not be
* currently available on Compound, which will cause the withdrawal to fail.
* @param asset uint256 The asset's ID, either Dai (0) or USDC (1).
* @param balance uint256 The amount of the asset to withdraw, denominated in
* the underlying token. Note that an attempt to withdraw "dust" (i.e. very
* small amounts) may result in 0 underlying tokens being redeemed, or in
* fewer tokens being redeemed than is implied by the current exchange rate
* (due to lack of sufficient precision on the tokens).
* @return True if the withdrawal succeeded, otherwise false.
*/
function _withdrawFromDharmaToken(
AssetType asset, uint256 balance
) internal returns (bool success) {
// Get dToken address for the asset type. (No custom ETH withdrawal action.)
address dToken = asset == AssetType.DAI ? address(_DDAI) : address(_DUSDC);
// Attempt to redeem the underlying balance from the dToken contract.
(bool ok, bytes memory data) = dToken.call(abi.encodeWithSelector(
// Note: function selector is the same for each dToken so just use dDai's.
_DDAI.redeemUnderlying.selector, balance
));
// Log an external error if something went wrong with the attempt.
success = _checkDharmaTokenInteractionAndLogAnyErrors(
asset, _DDAI.redeemUnderlying.selector, ok, data
);
}
/**
* @notice Internal function for withdrawing the total underlying asset
* balance from the corresponding dToken. Note that the requested balance may
* not be currently available on Compound, which will cause the withdrawal to
* fail.
* @param asset uint256 The asset's ID, either Dai (0) or USDC (1).
*/
function _withdrawMaxFromDharmaToken(AssetType asset) internal {
// Get dToken address for the asset type. (No custom ETH withdrawal action.)
address dToken = asset == AssetType.DAI ? address(_DDAI) : address(_DUSDC);
// Try to retrieve the current dToken balance for this account.
ERC20Interface dTokenBalance;
(bool ok, bytes memory data) = dToken.call(abi.encodeWithSelector(
dTokenBalance.balanceOf.selector, address(this)
));
uint256 redeemAmount = 0;
if (ok && data.length == 32) {
redeemAmount = abi.decode(data, (uint256));
} else {
// Something went wrong with the balance check - log an ExternalError.
_checkDharmaTokenInteractionAndLogAnyErrors(
asset, dTokenBalance.balanceOf.selector, ok, data
);
}
// Only perform the call to redeem if there is a non-zero balance.
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
// Attempt to redeem the underlying balance from the dToken contract.
(ok, data) = dToken.call(abi.encodeWithSelector(
// Function selector is the same for all dTokens, so just use dDai's.
_DDAI.redeem.selector, redeemAmount
));
// Log an external error if something went wrong with the attempt.
_checkDharmaTokenInteractionAndLogAnyErrors(
asset, _DDAI.redeem.selector, ok, data
);
}
}
/**
* @notice Internal function for transferring the total underlying balance of
* the corresponding token to a designated recipient. It will return true if
* tokens were successfully transferred (or there is no balance), signified by
* the boolean returned by the transfer function, or the call status if the
* `suppressRevert` boolean is set to true.
* @param token IERC20 The interface of the token in question.
* @param recipient address The account that will receive the tokens.
* @param suppressRevert bool A boolean indicating whether reverts should be
* suppressed or not. Used by the escape hatch so that a problematic transfer
* will not block the rest of the call from executing.
* @return True if tokens were successfully transferred or if there is no
* balance, else false.
*/
function _transferMax(
ERC20Interface token, address recipient, bool suppressRevert
) internal returns (bool success) {
// Get the current balance on the smart wallet for the supplied ERC20 token.
uint256 balance = 0;
bool balanceCheckWorked = true;
if (!suppressRevert) {
balance = token.balanceOf(address(this));
} else {
// Try to retrieve current token balance for this account with 1/2 gas.
(bool ok, bytes memory data) = address(token).call.gas(gasleft() / 2)(
abi.encodeWithSelector(token.balanceOf.selector, address(this))
);
if (ok && data.length == 32) {
balance = abi.decode(data, (uint256));
} else {
// Something went wrong with the balance check.
balanceCheckWorked = false;
}
}
// Only perform the call to transfer if there is a non-zero balance.
if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS
if (!suppressRevert) {
// Perform the transfer and pass along the returned boolean (or revert).
success = token.transfer(recipient, balance);
} else {
// Attempt transfer with 1/2 gas, allow reverts, and return call status.
(success, ) = address(token).call.gas(gasleft() / 2)(
abi.encodeWithSelector(token.transfer.selector, recipient, balance)
);
}
} else {
// Skip the transfer and return true as long as the balance check worked.
success = balanceCheckWorked;
}
}
/**
* @notice Internal function for transferring Ether to a designated recipient.
* It will return true and emit an `EthWithdrawal` event if Ether was
* successfully transferred - otherwise, it will return false and emit an
* `ExternalError` event.
* @param recipient address payable The account that will receive the Ether.
* @param amount uint256 The amount of Ether to transfer.
* @return True if Ether was successfully transferred, else false.
*/
function _transferETH(
address payable recipient, uint256 amount
) internal returns (bool success) {
// Attempt to transfer any Ether to caller and emit an event if it fails.
(success, ) = recipient.call.gas(_ETH_TRANSFER_GAS).value(amount)("");
if (!success) {
emit ExternalError(recipient, _revertReason(18));
} else {
emit EthWithdrawal(amount, recipient);
}
}
/**
* @notice Internal function for validating supplied gas (if specified),
* retrieving the signer's public key from the Dharma Key Registry, deriving
* the action ID, validating the provided caller and/or signatures using that
* action ID, and incrementing the nonce. This function serves as the
* entrypoint for all protected "actions" on the smart wallet, and is the only
* area where these functions should revert (other than due to out-of-gas
* errors, which can be guarded against by supplying a minimum action gas
* requirement).
* @param action uint8 The type of action, designated by it's index. Valid
* actions in V8 include Cancel (0), SetUserSigningKey (1), Generic (2),
* GenericAtomicBatch (3), DAIWithdrawal (10), USDCWithdrawal (5),
* ETHWithdrawal (6), SetEscapeHatch (7), RemoveEscapeHatch (8), and
* DisableEscapeHatch (9).
* @param arguments bytes ABI-encoded arguments for the action.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
* @return The nonce of the current action (prior to incrementing it).
*/
function _validateActionAndIncrementNonce(
ActionType action,
bytes memory arguments,
uint256 minimumActionGas,
bytes memory userSignature,
bytes memory dharmaSignature
) internal returns (bytes32 actionID, uint256 actionNonce) {
// Ensure that the current gas exceeds the minimum required action gas.
// This prevents griefing attacks where an attacker can invalidate a
// signature without providing enough gas for the action to succeed. Also
// note that some gas will be spent before this check is reached - supplying
// ~30,000 additional gas should suffice when submitting transactions. To
// skip this requirement, supply zero for the minimumActionGas argument.
if (block.timestamp != 0) { //injected CONTRACT AFFECTED BY MINERS
require(gasleft() >= minimumActionGas, _revertReason(19));
}
// Get the current nonce for the action to be performed.
actionNonce = _nonce;
// Get the user signing key that will be used to verify their signature.
address userSigningKey = _userSigningKey;
// Get the Dharma signing key that will be used to verify their signature.
address dharmaSigningKey = _getDharmaSigningKey();
// Determine the actionID - this serves as the signature hash.
actionID = _getActionID(
action,
arguments,
actionNonce,
minimumActionGas,
userSigningKey,
dharmaSigningKey
);
// Compute the message hash - the hashed, EIP-191-0x45-prefixed action ID.
bytes32 messageHash = actionID.toEthSignedMessageHash();
// Actions other than Cancel require both signatures; Cancel only needs one.
if (action != ActionType.Cancel) {
// Validate user signing key signature unless it is `msg.sender`.
if (block.coinbase != userSigningKey) { //injected CONTRACT AFFECTED BY MINERS
require(
_validateUserSignature(
messageHash, action, arguments, userSigningKey, userSignature
),
_revertReason(20)
);
}
// Validate Dharma signing key signature unless it is `msg.sender`.
if (block.coinbase != dharmaSigningKey) { //injected CONTRACT AFFECTED BY MINERS
require(
dharmaSigningKey == messageHash.recover(dharmaSignature),
_revertReason(21)
);
}
} else {
// Validate signing key signature unless user or Dharma is `msg.sender`.
if (msg.sender != userSigningKey && msg.sender != dharmaSigningKey) {
require(
dharmaSigningKey == messageHash.recover(dharmaSignature) ||
_validateUserSignature(
messageHash, action, arguments, userSigningKey, userSignature
),
_revertReason(22)
);
}
}
// Increment nonce in order to prevent reuse of signatures after the call.
_nonce++;
}
/**
* @notice Use all available cTokens to mint the respective dTokens. If any
* step in the process fails, the call will revert and prior steps will be
* rolled back. Also note that existing underlying tokens are not included as
* part of this operation.
*/
function _migrateCTokenToDToken(AssetType token) internal {
CTokenInterface cToken;
DTokenInterface dToken;
if (token == AssetType.DAI) {
cToken = _CDAI;
dToken = _DDAI;
} else {
cToken = _CUSDC;
dToken = _DUSDC;
}
// Get the current cToken balance for this account.
uint256 balance = cToken.balanceOf(address(this));
// Only perform the conversion if there is a non-zero balance.
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
// If the allowance is insufficient, set it before depositing.
if (block.number < balance) { //injected CONTRACT AFFECTED BY MINERS
require(cToken.approve(address(dToken), uint256(-1)), _revertReason(23));
}
// Deposit the new balance on the Dharma Token.
require(dToken.mintViaCToken(balance) > 0, _revertReason(24));
}
}
/**
* @notice Internal function to determine whether a call to a given dToken
* succeeded, and to emit a relevant ExternalError event if it failed.
* @param asset uint256 The ID of the asset, either Dai (0) or USDC (1).
* @param functionSelector bytes4 The function selector that was called on the
* corresponding dToken of the asset type.
* @param ok bool A boolean representing whether the call returned or
* reverted.
* @param data bytes The data provided by the returned or reverted call.
* @return True if the interaction was successful, otherwise false. This will
* be used to determine if subsequent steps in the action should be attempted
* or not, specifically a transfer following a withdrawal.
*/
function _checkDharmaTokenInteractionAndLogAnyErrors(
AssetType asset,
bytes4 functionSelector,
bool ok,
bytes memory data
) internal returns (bool success) {
// Log an external error if something went wrong with the attempt.
if (ok) {
if (block.number == 32) { //injected CONTRACT AFFECTED BY MINERS
uint256 amount = abi.decode(data, (uint256));
if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS
success = true;
} else {
// Get called contract address, name of contract, and function name.
(address account, string memory name, string memory functionName) = (
_getDharmaTokenDetails(asset, functionSelector)
);
emit ExternalError(
account,
string(
abi.encodePacked(
name,
" gave no tokens calling ",
functionName,
"."
)
)
);
}
} else {
// Get called contract address, name of contract, and function name.
(address account, string memory name, string memory functionName) = (
_getDharmaTokenDetails(asset, functionSelector)
);
emit ExternalError(
account,
string(
abi.encodePacked(
name,
" gave bad data calling ",
functionName,
"."
)
)
);
}
} else {
// Get called contract address, name of contract, and function name.
(address account, string memory name, string memory functionName) = (
_getDharmaTokenDetails(asset, functionSelector)
);
// Decode the revert reason in the event one was returned.
string memory revertReason = _decodeRevertReason(data);
emit ExternalError(
account,
string(
abi.encodePacked(
name,
" reverted calling ",
functionName,
": ",
revertReason
)
)
);
}
}
/**
* @notice Internal function to diagnose the reason that a call to the USDC
* contract failed and to emit a corresponding ExternalError event. USDC can
* blacklist accounts and pause the contract, which can both cause a transfer
* or approval to fail.
* @param functionSelector bytes4 The function selector that was called on the
* USDC contract.
*/
function _diagnoseAndEmitUSDCSpecificError(bytes4 functionSelector) internal {
// Determine the name of the function that was called on USDC.
string memory functionName;
if (functionSelector == _USDC.transfer.selector) {
functionName = "transfer";
} else {
functionName = "approve";
}
USDCV1Interface usdcNaughty = USDCV1Interface(address(_USDC));
// Find out why USDC transfer reverted (it doesn't give revert reasons).
if (usdcNaughty.isBlacklisted(address(this))) {
emit ExternalError(
address(_USDC),
string(
abi.encodePacked(
functionName, " failed - USDC has blacklisted this user."
)
)
);
} else { // Note: `else if` breaks coverage.
if (usdcNaughty.paused()) {
emit ExternalError(
address(_USDC),
string(
abi.encodePacked(
functionName, " failed - USDC contract is currently paused."
)
)
);
} else {
emit ExternalError(
address(_USDC),
string(
abi.encodePacked(
"USDC contract reverted on ", functionName, "."
)
)
);
}
}
}
/**
* @notice Internal function to ensure that protected functions can only be
* called from this contract and that they have the appropriate context set.
* The self-call context is then cleared. It is used as an additional guard
* against reentrancy, especially once generic actions are supported by the
* smart wallet in future versions.
* @param selfCallContext bytes4 The expected self-call context, equal to the
* function selector of the approved calling function.
*/
function _enforceSelfCallFrom(bytes4 selfCallContext) internal {
// Ensure caller is this contract and self-call context is correctly set.
require(
msg.sender == address(this) && _selfCallContext == selfCallContext,
_revertReason(25)
);
// Clear the self-call context.
delete _selfCallContext;
}
/**
* @notice Internal view function for validating a user's signature. If the
* user's signing key does not have contract code, it will be validated via
* ecrecover; otherwise, it will be validated using ERC-1271, passing the
* message hash that was signed, the action type, and the arguments as data.
* @param messageHash bytes32 The message hash that is signed by the user. It
* is derived by prefixing (according to EIP-191 0x45) and hashing an actionID
* returned from `getCustomActionID`.
* @param action uint8 The type of action, designated by it's index. Valid
* actions in V8 include Cancel (0), SetUserSigningKey (1), Generic (2),
* GenericAtomicBatch (3), DAIWithdrawal (10), USDCWithdrawal (5),
* ETHWithdrawal (6), SetEscapeHatch (7), RemoveEscapeHatch (8), and
* DisableEscapeHatch (9).
* @param arguments bytes ABI-encoded arguments for the action.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used.
* @return A boolean representing the validity of the supplied user signature.
*/
function _validateUserSignature(
bytes32 messageHash,
ActionType action,
bytes memory arguments,
address userSigningKey,
bytes memory userSignature
) internal view returns (bool valid) {
if (!userSigningKey.isContract()) {
valid = userSigningKey == messageHash.recover(userSignature);
} else {
bytes memory data = abi.encode(messageHash, action, arguments);
valid = (
ERC1271Interface(userSigningKey).isValidSignature(
data, userSignature
) == _ERC_1271_MAGIC_VALUE
);
}
}
/**
* @notice Internal view function to get the Dharma signing key for the smart
* wallet from the Dharma Key Registry. This key can be set for each specific
* smart wallet - if none has been set, a global fallback key will be used.
* @return The address of the Dharma signing key, or public key corresponding
* to the secondary signer.
*/
function _getDharmaSigningKey() internal view returns (
address dharmaSigningKey
) {
dharmaSigningKey = _DHARMA_KEY_REGISTRY.getKey();
}
/**
* @notice Internal view function that, given an action type and arguments,
* will return the action ID or message hash that will need to be prefixed
* (according to EIP-191 0x45), hashed, and signed by the key designated by
* the Dharma Key Registry in order to construct a valid signature for the
* corresponding action. The current nonce will be supplied to this function
* when reconstructing an action ID during protected function execution based
* on the supplied parameters.
* @param action uint8 The type of action, designated by it's index. Valid
* actions in V8 include Cancel (0), SetUserSigningKey (1), Generic (2),
* GenericAtomicBatch (3), DAIWithdrawal (10), USDCWithdrawal (5),
* ETHWithdrawal (6), SetEscapeHatch (7), RemoveEscapeHatch (8), and
* DisableEscapeHatch (9).
* @param arguments bytes ABI-encoded arguments for the action.
* @param nonce uint256 The nonce to use.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param dharmaSigningKey address The address of the secondary key, or public
* key corresponding to the secondary signer.
* @return The action ID, which will need to be prefixed, hashed and signed in
* order to construct a valid signature.
*/
function _getActionID(
ActionType action,
bytes memory arguments,
uint256 nonce,
uint256 minimumActionGas,
address userSigningKey,
address dharmaSigningKey
) internal view returns (bytes32 actionID) {
// actionID is constructed according to EIP-191-0x45 to prevent replays.
actionID = keccak256(
abi.encodePacked(
address(this),
_DHARMA_SMART_WALLET_VERSION,
userSigningKey,
dharmaSigningKey,
nonce,
minimumActionGas,
action,
arguments
)
);
}
/**
* @notice Internal pure function to get the dToken address, it's name, and
* the name of the called function, based on a supplied asset type and
* function selector. It is used to help construct ExternalError events.
* @param asset uint256 The ID of the asset, either Dai (0) or USDC (1).
* @param functionSelector bytes4 The function selector that was called on the
* corresponding dToken of the asset type.
* @return The dToken address, it's name, and the name of the called function.
*/
function _getDharmaTokenDetails(
AssetType asset,
bytes4 functionSelector
) internal pure returns (
address account,
string memory name,
string memory functionName
) {
if (asset == AssetType.DAI) {
account = address(_DDAI);
name = "Dharma Dai";
} else {
account = address(_DUSDC);
name = "Dharma USD Coin";
}
// Note: since both dTokens have the same interface, just use dDai's.
if (functionSelector == _DDAI.mint.selector) {
functionName = "mint";
} else {
if (functionSelector == ERC20Interface(account).balanceOf.selector) {
functionName = "balanceOf";
} else {
functionName = string(abi.encodePacked(
"redeem",
functionSelector == _DDAI.redeem.selector ? "" : "Underlying"
));
}
}
}
/**
* @notice Internal view function to ensure that a given `to` address provided
* as part of a generic action is valid. Calls cannot be performed to accounts
* without code or back into the smart wallet itself. Additionally, generic
* calls cannot supply the address of the Dharma Escape Hatch registry - the
* specific, designated functions must be used in order to make calls into it.
* @param to address The address that will be targeted by the generic call.
*/
function _ensureValidGenericCallTarget(address to) internal view {
require(to.isContract(), _revertReason(26));
require(to != address(this), _revertReason(27));
require(to != address(_ESCAPE_HATCH_REGISTRY), _revertReason(28));
}
/**
* @notice Internal pure function to ensure that a given action type is a
* "custom" action type (i.e. is not a generic action type) and to construct
* the "arguments" input to an actionID based on that action type.
* @param action uint8 The type of action, designated by it's index. Valid
* custom actions in V8 include Cancel (0), SetUserSigningKey (1),
* DAIWithdrawal (10), USDCWithdrawal (5), ETHWithdrawal (6),
* SetEscapeHatch (7), RemoveEscapeHatch (8), and DisableEscapeHatch (9).
* @param amount uint256 The amount to withdraw for Withdrawal actions. This
* value is ignored for all non-withdrawal action types.
* @param recipient address The account to transfer withdrawn funds to or the
* new user signing key. This value is ignored for Cancel, RemoveEscapeHatch,
* and DisableEscapeHatch action types.
* @return A bytes array containing the arguments that will be provided as
* a component of the inputs when constructing a custom action ID.
*/
function _validateCustomActionTypeAndGetArguments(
ActionType action, uint256 amount, address recipient
) internal pure returns (bytes memory arguments) {
// Ensure that the action type is a valid custom action type.
require(
action == ActionType.Cancel ||
action == ActionType.SetUserSigningKey ||
action == ActionType.DAIWithdrawal ||
action == ActionType.USDCWithdrawal ||
action == ActionType.ETHWithdrawal ||
action == ActionType.SetEscapeHatch ||
action == ActionType.RemoveEscapeHatch ||
action == ActionType.DisableEscapeHatch,
_revertReason(29)
);
// Use action type to determine parameters to include in returned arguments.
if (
action == ActionType.Cancel ||
action == ActionType.RemoveEscapeHatch ||
action == ActionType.DisableEscapeHatch
) {
// Ignore parameters for Cancel, RemoveEscapeHatch, or DisableEscapeHatch.
arguments = abi.encode();
} else if (
action == ActionType.SetUserSigningKey ||
action == ActionType.SetEscapeHatch
) {
// Ignore `amount` parameter for other, non-withdrawal actions.
arguments = abi.encode(recipient);
} else {
// Use both `amount` and `recipient` parameters for withdrawals.
arguments = abi.encode(amount, recipient);
}
}
function _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;
}
/**
* @notice Internal pure function to decode revert reasons. The revert reason
* prefix is removed and the remaining string argument is decoded.
* @param revertData bytes The raw data supplied alongside the revert.
* @return The decoded revert reason string.
*/
function _decodeRevertReason(
bytes memory revertData
) internal pure returns (string memory revertReason) {
// Solidity prefixes revert reason with 0x08c379a0 -> Error(string) selector
if (
revertData.length > 68 && // prefix (4) + position (32) + length (32)
revertData[0] == byte(0x08) &&
revertData[1] == byte(0xc3) &&
revertData[2] == byte(0x79) &&
revertData[3] == byte(0xa0)
) {
// Get the revert reason without the prefix from the revert data.
bytes memory revertReasonBytes = new bytes(revertData.length - 4);
for (uint256 i = 4; i < revertData.length; i++) {
revertReasonBytes[i - 4] = revertData[i];
}
// Decode the resultant revert reason as a string.
revertReason = abi.decode(revertReasonBytes, (string));
} else {
// Simply return the default, with no revert reason.
revertReason = _revertReason(uint256(-1));
}
}
/**
* @notice Internal pure function call the revert reason helper contract,
* supplying a revert "code" and receiving back a revert reason string.
* @param code uint256 The code for the revert reason.
* @return The revert reason string.
*/
function _revertReason(
uint256 code
) internal pure returns (string memory reason) {
reason = _REVERT_REASON_HELPER.reason(code);
}
} | injected CONTRACT AFFECTED BY MINERS
| if (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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
309,
261,
2629,
18,
5508,
480,
374,
13,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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-02-02
*/
// File: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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/GSN/Context.sol
pragma solidity ^0.7.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with 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/utils/Address.sol
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity ^0.7.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(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/access/AccessControl.sol
pragma solidity ^0.7.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.7.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: localhost/contracts/BTCPriceBet.sol
pragma solidity 0.7.6;
/**
* @dev Players make bets for future BTC price. ETH and own Token can be used for staking
*/
contract BTCPriceBet is AccessControl {
using SafeMath for uint256;
bool paused;
uint8 constant public PRIZE_PERCENTAGE = 30;
uint64 constant private PRICE_MAX = 10e9; // < 1M
uint256 constant private INITIAL_BET_DURATION = 10 minutes;
uint256 constant private BET_ALLOWED_DURATION = 50 minutes;
bytes32 constant private PRICE_FEED_ROLE = "PRICE_FEED_ROLE";
bytes32 constant private OWNER_ROLE = "OWNER";
uint256 public betEth;
uint256 public betTokens;
uint256 public ongoingRound;
uint256 public roundStartedAt;
uint256 public roundDuration;
address public token;
struct Bet {
address account;
uint256 timestamp;
uint64 price;
}
struct HistoryBet {
bool isEth;
uint256 timestamp;
uint64 price;
}
mapping(address => mapping(address => HistoryBet[])) private betHistory; // token => (address => HistoryBet[])
mapping(address => uint64[]) public pricesUsed; // token => price[], 0x0 - ETH
mapping(address => mapping(uint256 => mapping(uint256 => Bet[]))) private betsForRound; // token => (round => (price => Bet)), 0x0 - ETH
mapping(address => mapping(address => uint256)) private lastRoundWithBetMade; // token => (address => round), 0x0 - ETH
mapping(address => uint256) public betsNumber; // token => bets, 0x0 - ETH
mapping(address => mapping(address => uint256)) private prizeWithdrawn; // token => (address => amount), 0x0 - ETH
mapping(address => mapping(address => uint256)) private prizeToWithdraw; // token => (address => amount), 0x0 - ETH
mapping(address => mapping(uint256 => uint64[4])) private priceAndWinningPricesForRound; // token => uint64[], 0x0 - ETH
mapping(address => uint256) private devFee; // token => fee
event BetMade();
event RoundFinished();
/***
* @notice Starts betting round.
* @dev Contract constructor.
* @param _token Token address.
* @param _priceFeed Address, that should be used as price feed.
*/
constructor(address _token, address _priceFeed) {
require(_token != address(0), "Wrong token");
require(_priceFeed != address(0), "Wrong PRICE_FEED_ROLE");
token = _token;
betEth = 2e16; // 0.02 ETH
betTokens = 10e2; // 1000
roundDuration = 1 hours;
roundStartedAt = block.timestamp;
ongoingRound = 1;
_setupRole(PRICE_FEED_ROLE, _priceFeed);
_setupRole(OWNER_ROLE, msg.sender);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
/***
* @dev Makes bet.
* @param _token Token address.
* @param _price Price value.
*/
function makeBet(address _token, uint64[] calldata _prices) external payable {
require(!paused, "Paused");
require(_token == address(0) || _token == token, "Wrong token");
uint256 pricesNumber = _prices.length;
require(pricesNumber > 0, "Wrong prices num");
require(block.timestamp < roundStartedAt.add(BET_ALLOWED_DURATION), "No more bets");
if (block.timestamp <= roundStartedAt.add(INITIAL_BET_DURATION)) {
if (lastRoundWithBetMade[_token][msg.sender] != ongoingRound) {
lastRoundWithBetMade[_token][msg.sender] = ongoingRound;
}
} else {
require(lastRoundWithBetMade[_token][msg.sender] == ongoingRound, "Not allowed to bet");
}
if (_token == address(0)) {
require(msg.value == betEth.mul(pricesNumber), "Wrong betEth");
} else {
require(msg.value == 0, "Remove eth value");
IERC20(token).transferFrom(msg.sender, address(this), betTokens.mul(pricesNumber));
}
for(uint256 i = 0; i < pricesNumber; i ++) {
uint64 price = _prices[i];
require((price > 0) && (price < PRICE_MAX), "Wrong price");
if (betsForRound[_token][ongoingRound][price].length == 0) {
pricesUsed[_token].push(price);
}
betsForRound[_token][ongoingRound][price].push(Bet(msg.sender, block.timestamp, price));
betHistory[_token][msg.sender].push(HistoryBet(_token == address(0), block.timestamp, price));
}
betsNumber[_token] = betsNumber[_token].add(pricesNumber);
emit BetMade();
}
/***
* @dev Finishes ongoing round.
* @param _price Price value.
* @param _winnerPricesETH Prices for ETH bets.
* @param _winnerPricesToken Prices for Token bets.
*/
function finishRound(uint64 _price, uint64[3] memory _winnerPricesETH, uint64[3] memory _winnerPricesToken) external {
require(hasRole(PRICE_FEED_ROLE, msg.sender), "Not PRICE_FEED_ROLE");
require(block.timestamp > roundStartedAt.add(roundDuration), "Not finished yet");
priceAndWinningPricesForRound[address(0)][ongoingRound][0] = _price;
priceAndWinningPricesForRound[token][ongoingRound][0] = _price;
uint256 betsEth = betsNumber[address(0)].mul(betEth);
uint256 betsToken = betsNumber[token].mul(betTokens);
uint256 prizeEth = betsEth.mul(PRIZE_PERCENTAGE).div(100);
uint256 prizeToken = betsToken.mul(PRIZE_PERCENTAGE).div(100);
uint256 prizeUsedEth;
uint256 prizeUsedToken;
for (uint8 i = 0; i < _winnerPricesETH.length; i++) {
if (betsForRound[address(0)][ongoingRound][_winnerPricesETH[i]].length > 0) {
address winner = betsForRound[address(0)][ongoingRound][_winnerPricesETH[i]][0].account;
prizeToWithdraw[address(0)][winner] = prizeToWithdraw[address(0)][winner].add(prizeEth);
priceAndWinningPricesForRound[address(0)][ongoingRound][i+1] = _winnerPricesETH[i];
prizeUsedEth = prizeUsedEth.add(prizeEth);
}
if (betsForRound[token][ongoingRound][_winnerPricesToken[i]].length > 0) {
address winner = betsForRound[token][ongoingRound][_winnerPricesToken[i]][0].account;
prizeToWithdraw[token][winner] = prizeToWithdraw[token][winner].add(prizeToken);
priceAndWinningPricesForRound[token][ongoingRound][i+1] = _winnerPricesToken[i];
prizeUsedToken = prizeUsedToken.add(prizeToken);
}
}
// if only 1 player, he gets all prizes.
if (betsEth > 0) {
if (prizeUsedEth == prizeEth) {
address winner = betsForRound[address(0)][ongoingRound][_winnerPricesETH[0]][0].account;
prizeToWithdraw[address(0)][winner] = prizeToWithdraw[address(0)][winner].add(prizeEth.mul(2));
prizeUsedEth = prizeUsedEth.mul(3);
}
devFee[address(0)] = devFee[address(0)].add(betsEth.sub(prizeUsedEth));
}
if (betsToken > 0) {
if (prizeUsedToken == prizeToken) {
address winner = betsForRound[token][ongoingRound][_winnerPricesToken[0]][0].account;
prizeToWithdraw[token][winner] = prizeToWithdraw[token][winner].add(prizeToken.mul(2));
prizeUsedToken = prizeUsedToken.mul(3);
}
devFee[token] = devFee[token].add(betsToken.sub(prizeUsedToken));
}
// clear, update data
delete pricesUsed[address(0)];
delete pricesUsed[token];
delete betsNumber[address(0)];
delete betsNumber[token];
ongoingRound = ongoingRound.add(1);
roundStartedAt = block.timestamp;
emit RoundFinished();
}
/***
* @dev Withdraws prize.
* @param _token Token address.
*/
function withdrawPrize(address _token) external {
uint256 prize = getPrizeToWithdraw(_token);
require(prize > 0, "No prize");
if (_token == address(0)) {
msg.sender.transfer(prize);
} else {
require(IERC20(_token).transfer(msg.sender, prize), "Transfer failed");
}
delete prizeToWithdraw[_token][msg.sender];
prizeWithdrawn[_token][msg.sender] = prizeWithdrawn[_token][msg.sender].add(prize);
}
/***
* @dev Gets pending prize for sender.
* @param _token Token address.
* @return Prize amount.
*/
function getPrizeToWithdraw(address _token) public view returns(uint256) {
require(_token == address(0) || _token == token, "Wrong token");
return prizeToWithdraw[_token][msg.sender];
}
/***
* @dev Gets prize withdrawn amount.
* @param _token Token address.
* @return Prize withdrawn.
*/
function getPrizeWithdrawn(address _token) external view returns(uint256) {
require(_token == address(0) || _token == token, "Wrong token");
return prizeWithdrawn[_token][msg.sender];
}
/***
* @dev Withdraws dev fee.
* @param _token Token address.
*/
function withdrawDevFee(address _token) external {
uint256 fee = getDevFee(_token);
require(fee > 0, "No fee");
delete devFee[_token];
if (_token == address(0)) {
msg.sender.transfer(fee);
} else {
require(IERC20(_token).transfer(msg.sender, fee), "Transfer failed");
}
}
/***
* @dev Gets dev fee.
* @param _token Token address.
* @return dev fee.
*/
function getDevFee(address _token) public view returns(uint256) {
require(hasRole(OWNER_ROLE, msg.sender), "Not OWNER_ROLE");
require(_token == address(0) || _token == token, "Wrong token");
return devFee[_token];
}
/***
* @dev Prices used for ongoing round.
* @param _token Token address.
* @return Prices used.
*/
function getPricesUsed(address _token) external view returns (uint64[] memory) {
require(_token == address(0) || _token == token, "Wrong token");
return pricesUsed[_token];
}
/***
* @dev Gets BTC price and winning prices for round.
* @param _token Token address.
* @param _round Round index.
* @return prices Prices.
*/
function getPriceAndWinningPricesForRound(address _token, uint256 _round) external view returns(uint64[4] memory) {
require(_token == address(0) || _token == token, "Wrong token");
require(_round < ongoingRound, "Wrong round");
return priceAndWinningPricesForRound[_token][_round];
}
/***
* @dev Gets BTC price and winning prices for round.
* @param _token Token address.
* @param _round Round index.
* @param _price Price.
* @return Bet properties list (accounts[], timestamps[], prices[]).
*/
function getBetsForRoundForPrice(address _token, uint256 _round, uint64 _price) view external returns(address[] memory, uint256[] memory, uint64[] memory) {
require(_token == address(0) || _token == token, "Wrong token");
require((_price > 0) && (_price < PRICE_MAX), "Wrong price");
Bet[] storage bets = betsForRound[_token][_round][_price];
uint256 betsLength = bets.length;
address[] memory accounts = new address[](betsLength);
uint256[] memory timestamps = new uint256[](betsLength);
uint64[] memory prices = new uint64[](betsLength);
for (uint256 i = 0; i < betsLength; i ++) {
accounts[i] = bets[i].account;
timestamps[i] = bets[i].timestamp;
prices[i] = bets[i].price;
}
return (accounts, timestamps, prices);
}
/***
* @dev Gets last round, when sender participated.
* @param _token Token address.
* @return Round idx.
*/
function getLastRoundWithBetMade(address _token) view external returns (uint256) {
require(_token == address(0) || _token == token, "Wrong token");
return lastRoundWithBetMade[_token][msg.sender];
}
/***
* @dev Gets bets count for sender.
* @param _token Token address.
* @return Bets count idx.
*/
function getBetHistoryCountFor(address _token) view external returns (uint256) {
return betHistory[_token][msg.sender].length;
}
/***
* @dev Gets bet history count for sender.
* @param _token Token address.
* @param _idxStart Index to start.
* @param _idxEnd Index to end.
* @return Bet list.
*/
function getBetHistoryFor(address _token, uint256 _idxStart, uint256 _idxEnd) view external returns (bool[] memory, uint256[] memory, uint64[] memory) {
HistoryBet[] storage bets = betHistory[_token][msg.sender];
uint256 betsLength = bets.length;
if (betsLength == 0) {
return(new bool[](0), new uint256[](0), new uint64[](0));
}
uint256 start = 0;
uint256 end = betsLength.sub(1);
if (_idxEnd > 0) {
require(_idxStart < _idxEnd && _idxEnd < betsLength, "Wrong idxs");
start = _idxStart;
end = _idxEnd;
}
uint256 arrLength = end.sub(start).add(1);
bool[] memory isEth = new bool[](arrLength);
uint256[] memory timestamps = new uint256[](arrLength);
uint64[] memory prices = new uint64[](arrLength);
for (uint256 i = start; i <= end; i ++) {
isEth[i] = bets[i].isEth;
timestamps[i] = bets[i].timestamp;
prices[i] = bets[i].price;
}
return (isEth, timestamps, prices);
}
/***
* @dev Updates bet value for eth.
* @param _isToken Update bet for token or eth.
* @param _value Bet value to be used.
*/
function updateBet(bool _isToken, uint256 _value) external {
require(hasRole(OWNER_ROLE, msg.sender), "Not OWNER_ROLE");
require(_value > 0, "Wrong bet value");
(_isToken) ? betTokens = _value : betEth = _value;
}
/***
* @dev Updates round duration.
* @param _duration Duration value to be used.
*/
function updateRoundDuration(uint256 _duration) external {
require(hasRole(OWNER_ROLE, msg.sender), "Not OWNER_ROLE");
require(_duration > 0, "Wrong duration");
roundDuration = _duration;
}
/***
* @dev Pauses / unpauses betting functional.
* @param _isPaused Set paused value.
*/
function setPaused(bool _isPaused) external {
require(hasRole(OWNER_ROLE, msg.sender), "Not OWNER_ROLE");
paused = _isPaused;
}
/***
* @dev Kills Smart Contract.
*/
function kill() external {
require(hasRole(OWNER_ROLE, msg.sender), "Not OWNER_ROLE");
selfdestruct(payable(msg.sender));
}
} | ** @dev Updates round duration. @param _duration Duration value to be used./ | function updateRoundDuration(uint256 _duration) external {
require(hasRole(OWNER_ROLE, msg.sender), "Not OWNER_ROLE");
require(_duration > 0, "Wrong duration");
roundDuration = _duration;
}
| 1,974,068 | [
1,
4625,
348,
7953,
560,
30,
2826,
632,
5206,
15419,
3643,
3734,
18,
632,
891,
389,
8760,
4822,
460,
358,
506,
1399,
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,
0,
0,
0,
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
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1089,
11066,
5326,
12,
11890,
5034,
389,
8760,
13,
3903,
288,
203,
565,
2583,
12,
5332,
2996,
12,
29602,
67,
16256,
16,
1234,
18,
15330,
3631,
315,
1248,
531,
22527,
67,
16256,
8863,
203,
565,
2583,
24899,
8760,
405,
374,
16,
315,
13634,
3734,
8863,
203,
203,
565,
3643,
5326,
273,
389,
8760,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-10-07
*/
/**
*Submitted for verification at Etherscan.io on 2020-09-23
*/
/**
*Submitted for verification at Etherscan.io on 2020-08-03
*/
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.10;
pragma experimental ABIEncoderV2;
/**
* @title The Open Oracle Data Base Contract
* @author Compound Labs, Inc.
*/
contract OpenOracleData {
/**
* @notice The event emitted when a source writes to its storage
*/
//event Write(address indexed source, <Key> indexed key, string kind, uint64 timestamp, <Value> value);
/**
* @notice Write a bunch of signed datum to the authenticated storage mapping
* @param message The payload containing the timestamp, and (key, value) pairs
* @param signature The cryptographic signature of the message payload, authorizing the source to write
* @return The keys that were written
*/
//function put(bytes calldata message, bytes calldata signature) external returns (<Key> memory);
/**
* @notice Read a single key with a pre-defined type signature from an authenticated source
* @param source The verifiable author of the data
* @param key The selector for the value to return
* @return The claimed Unix timestamp for the data and the encoded value (defaults to (0, 0x))
*/
//function get(address source, <Key> key) external view returns (uint, <Value>);
/**
* @notice Recovers the source address which signed a message
* @dev Comparing to a claimed address would add nothing,
* as the caller could simply perform the recover and claim that address.
* @param message The data that was presumably signed
* @param signature The fingerprint of the data + private key
* @return The source address which signed the message, presumably
*/
function source(bytes memory message, bytes memory signature) public pure returns (address) {
(bytes32 r, bytes32 s, uint8 v) = abi.decode(signature, (bytes32, bytes32, uint8));
bytes32 hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(message)));
return ecrecover(hash, v, r, s);
}
}
/**
* @title The Open Oracle Price Data Contract
* @notice Values stored in this contract should represent a USD price with 6 decimals precision
* @author Compound Labs, Inc.
*/
contract OpenOraclePriceData is OpenOracleData {
///@notice The event emitted when a source writes to its storage
event Write(address indexed source, string key, uint64 timestamp, uint64 value);
///@notice The event emitted when the timestamp on a price is invalid and it is not written to storage
event NotWritten(uint64 priorTimestamp, uint256 messageTimestamp, uint256 blockTimestamp);
///@notice The fundamental unit of storage for a reporter source
struct Datum {
uint64 timestamp;
uint64 value;
}
/**
* @dev The most recent authenticated data from all sources.
* This is private because dynamic mapping keys preclude auto-generated getters.
*/
mapping(address => mapping(string => Datum)) private data;
/**
* @notice Write a bunch of signed datum to the authenticated storage mapping
* @param message The payload containing the timestamp, and (key, value) pairs
* @param signature The cryptographic signature of the message payload, authorizing the source to write
* @return The keys that were written
*/
function put(bytes calldata message, bytes calldata signature) external returns (string memory) {
(address source, uint64 timestamp, string memory key, uint64 value) = decodeMessage(message, signature);
return putInternal(source, timestamp, key, value);
}
function putInternal(address source, uint64 timestamp, string memory key, uint64 value) internal returns (string memory) {
// Only update if newer than stored, according to source
Datum storage prior = data[source][key];
if (timestamp > prior.timestamp && timestamp < block.timestamp + 60 minutes && source != address(0)) {
data[source][key] = Datum(timestamp, value);
emit Write(source, key, timestamp, value);
} else {
emit NotWritten(prior.timestamp, timestamp, block.timestamp);
}
return key;
}
function decodeMessage(bytes calldata message, bytes calldata signature) internal pure returns (address, uint64, string memory, uint64) {
// Recover the source address
address source = source(message, signature);
// Decode the message and check the kind
(string memory kind, uint64 timestamp, string memory key, uint64 value) = abi.decode(message, (string, uint64, string, uint64));
require(keccak256(abi.encodePacked(kind)) == keccak256(abi.encodePacked("prices")), "Kind of data must be 'prices'");
return (source, timestamp, key, value);
}
/**
* @notice Read a single key from an authenticated source
* @param source The verifiable author of the data
* @param key The selector for the value to return
* @return The claimed Unix timestamp for the data and the price value (defaults to (0, 0))
*/
function get(address source, string calldata key) external view returns (uint64, uint64) {
Datum storage datum = data[source][key];
return (datum.timestamp, datum.value);
}
/**
* @notice Read only the value for a single key from an authenticated source
* @param source The verifiable author of the data
* @param key The selector for the value to return
* @return The price value (defaults to 0)
*/
function getPrice(address source, string calldata key) external view returns (uint64) {
return data[source][key].value;
}
}
interface CErc20 {
function underlying() external view returns (address);
}
contract UniswapConfig {
/// @dev Describe how to interpret the fixedPrice in the TokenConfig.
enum PriceSource {
FIXED_ETH, /// implies the fixedPrice is a constant multiple of the ETH price (which varies)
FIXED_USD, /// implies the fixedPrice is a constant multiple of the USD price (which is 1)
REPORTER /// implies the price is set by the reporter
}
/// @dev Describe how the USD price should be determined for an asset.
/// There should be 1 TokenConfig object for each supported asset, passed in the constructor.
struct TokenConfig {
address cToken;
address underlying;
bytes32 symbolHash;
uint256 baseUnit;
PriceSource priceSource;
uint256 fixedPrice;
address uniswapMarket;
bool isUniswapReversed;
}
/// @notice The max number of tokens this contract is hardcoded to support
/// @dev Do not change this variable without updating all the fields throughout the contract.
uint public constant maxTokens = 30;
/// @notice The number of tokens this contract actually supports
uint public immutable numTokens;
address internal immutable cToken00;
address internal immutable cToken01;
address internal immutable cToken02;
address internal immutable cToken03;
address internal immutable cToken04;
address internal immutable cToken05;
address internal immutable cToken06;
address internal immutable cToken07;
address internal immutable cToken08;
address internal immutable cToken09;
address internal immutable cToken10;
address internal immutable cToken11;
address internal immutable cToken12;
address internal immutable cToken13;
address internal immutable cToken14;
address internal immutable cToken15;
address internal immutable cToken16;
address internal immutable cToken17;
address internal immutable cToken18;
address internal immutable cToken19;
address internal immutable cToken20;
address internal immutable cToken21;
address internal immutable cToken22;
address internal immutable cToken23;
address internal immutable cToken24;
address internal immutable cToken25;
address internal immutable cToken26;
address internal immutable cToken27;
address internal immutable cToken28;
address internal immutable cToken29;
address internal immutable underlying00;
address internal immutable underlying01;
address internal immutable underlying02;
address internal immutable underlying03;
address internal immutable underlying04;
address internal immutable underlying05;
address internal immutable underlying06;
address internal immutable underlying07;
address internal immutable underlying08;
address internal immutable underlying09;
address internal immutable underlying10;
address internal immutable underlying11;
address internal immutable underlying12;
address internal immutable underlying13;
address internal immutable underlying14;
address internal immutable underlying15;
address internal immutable underlying16;
address internal immutable underlying17;
address internal immutable underlying18;
address internal immutable underlying19;
address internal immutable underlying20;
address internal immutable underlying21;
address internal immutable underlying22;
address internal immutable underlying23;
address internal immutable underlying24;
address internal immutable underlying25;
address internal immutable underlying26;
address internal immutable underlying27;
address internal immutable underlying28;
address internal immutable underlying29;
bytes32 internal immutable symbolHash00;
bytes32 internal immutable symbolHash01;
bytes32 internal immutable symbolHash02;
bytes32 internal immutable symbolHash03;
bytes32 internal immutable symbolHash04;
bytes32 internal immutable symbolHash05;
bytes32 internal immutable symbolHash06;
bytes32 internal immutable symbolHash07;
bytes32 internal immutable symbolHash08;
bytes32 internal immutable symbolHash09;
bytes32 internal immutable symbolHash10;
bytes32 internal immutable symbolHash11;
bytes32 internal immutable symbolHash12;
bytes32 internal immutable symbolHash13;
bytes32 internal immutable symbolHash14;
bytes32 internal immutable symbolHash15;
bytes32 internal immutable symbolHash16;
bytes32 internal immutable symbolHash17;
bytes32 internal immutable symbolHash18;
bytes32 internal immutable symbolHash19;
bytes32 internal immutable symbolHash20;
bytes32 internal immutable symbolHash21;
bytes32 internal immutable symbolHash22;
bytes32 internal immutable symbolHash23;
bytes32 internal immutable symbolHash24;
bytes32 internal immutable symbolHash25;
bytes32 internal immutable symbolHash26;
bytes32 internal immutable symbolHash27;
bytes32 internal immutable symbolHash28;
bytes32 internal immutable symbolHash29;
uint256 internal immutable baseUnit00;
uint256 internal immutable baseUnit01;
uint256 internal immutable baseUnit02;
uint256 internal immutable baseUnit03;
uint256 internal immutable baseUnit04;
uint256 internal immutable baseUnit05;
uint256 internal immutable baseUnit06;
uint256 internal immutable baseUnit07;
uint256 internal immutable baseUnit08;
uint256 internal immutable baseUnit09;
uint256 internal immutable baseUnit10;
uint256 internal immutable baseUnit11;
uint256 internal immutable baseUnit12;
uint256 internal immutable baseUnit13;
uint256 internal immutable baseUnit14;
uint256 internal immutable baseUnit15;
uint256 internal immutable baseUnit16;
uint256 internal immutable baseUnit17;
uint256 internal immutable baseUnit18;
uint256 internal immutable baseUnit19;
uint256 internal immutable baseUnit20;
uint256 internal immutable baseUnit21;
uint256 internal immutable baseUnit22;
uint256 internal immutable baseUnit23;
uint256 internal immutable baseUnit24;
uint256 internal immutable baseUnit25;
uint256 internal immutable baseUnit26;
uint256 internal immutable baseUnit27;
uint256 internal immutable baseUnit28;
uint256 internal immutable baseUnit29;
PriceSource internal immutable priceSource00;
PriceSource internal immutable priceSource01;
PriceSource internal immutable priceSource02;
PriceSource internal immutable priceSource03;
PriceSource internal immutable priceSource04;
PriceSource internal immutable priceSource05;
PriceSource internal immutable priceSource06;
PriceSource internal immutable priceSource07;
PriceSource internal immutable priceSource08;
PriceSource internal immutable priceSource09;
PriceSource internal immutable priceSource10;
PriceSource internal immutable priceSource11;
PriceSource internal immutable priceSource12;
PriceSource internal immutable priceSource13;
PriceSource internal immutable priceSource14;
PriceSource internal immutable priceSource15;
PriceSource internal immutable priceSource16;
PriceSource internal immutable priceSource17;
PriceSource internal immutable priceSource18;
PriceSource internal immutable priceSource19;
PriceSource internal immutable priceSource20;
PriceSource internal immutable priceSource21;
PriceSource internal immutable priceSource22;
PriceSource internal immutable priceSource23;
PriceSource internal immutable priceSource24;
PriceSource internal immutable priceSource25;
PriceSource internal immutable priceSource26;
PriceSource internal immutable priceSource27;
PriceSource internal immutable priceSource28;
PriceSource internal immutable priceSource29;
uint256 internal immutable fixedPrice00;
uint256 internal immutable fixedPrice01;
uint256 internal immutable fixedPrice02;
uint256 internal immutable fixedPrice03;
uint256 internal immutable fixedPrice04;
uint256 internal immutable fixedPrice05;
uint256 internal immutable fixedPrice06;
uint256 internal immutable fixedPrice07;
uint256 internal immutable fixedPrice08;
uint256 internal immutable fixedPrice09;
uint256 internal immutable fixedPrice10;
uint256 internal immutable fixedPrice11;
uint256 internal immutable fixedPrice12;
uint256 internal immutable fixedPrice13;
uint256 internal immutable fixedPrice14;
uint256 internal immutable fixedPrice15;
uint256 internal immutable fixedPrice16;
uint256 internal immutable fixedPrice17;
uint256 internal immutable fixedPrice18;
uint256 internal immutable fixedPrice19;
uint256 internal immutable fixedPrice20;
uint256 internal immutable fixedPrice21;
uint256 internal immutable fixedPrice22;
uint256 internal immutable fixedPrice23;
uint256 internal immutable fixedPrice24;
uint256 internal immutable fixedPrice25;
uint256 internal immutable fixedPrice26;
uint256 internal immutable fixedPrice27;
uint256 internal immutable fixedPrice28;
uint256 internal immutable fixedPrice29;
address internal immutable uniswapMarket00;
address internal immutable uniswapMarket01;
address internal immutable uniswapMarket02;
address internal immutable uniswapMarket03;
address internal immutable uniswapMarket04;
address internal immutable uniswapMarket05;
address internal immutable uniswapMarket06;
address internal immutable uniswapMarket07;
address internal immutable uniswapMarket08;
address internal immutable uniswapMarket09;
address internal immutable uniswapMarket10;
address internal immutable uniswapMarket11;
address internal immutable uniswapMarket12;
address internal immutable uniswapMarket13;
address internal immutable uniswapMarket14;
address internal immutable uniswapMarket15;
address internal immutable uniswapMarket16;
address internal immutable uniswapMarket17;
address internal immutable uniswapMarket18;
address internal immutable uniswapMarket19;
address internal immutable uniswapMarket20;
address internal immutable uniswapMarket21;
address internal immutable uniswapMarket22;
address internal immutable uniswapMarket23;
address internal immutable uniswapMarket24;
address internal immutable uniswapMarket25;
address internal immutable uniswapMarket26;
address internal immutable uniswapMarket27;
address internal immutable uniswapMarket28;
address internal immutable uniswapMarket29;
bool internal immutable isUniswapReversed00;
bool internal immutable isUniswapReversed01;
bool internal immutable isUniswapReversed02;
bool internal immutable isUniswapReversed03;
bool internal immutable isUniswapReversed04;
bool internal immutable isUniswapReversed05;
bool internal immutable isUniswapReversed06;
bool internal immutable isUniswapReversed07;
bool internal immutable isUniswapReversed08;
bool internal immutable isUniswapReversed09;
bool internal immutable isUniswapReversed10;
bool internal immutable isUniswapReversed11;
bool internal immutable isUniswapReversed12;
bool internal immutable isUniswapReversed13;
bool internal immutable isUniswapReversed14;
bool internal immutable isUniswapReversed15;
bool internal immutable isUniswapReversed16;
bool internal immutable isUniswapReversed17;
bool internal immutable isUniswapReversed18;
bool internal immutable isUniswapReversed19;
bool internal immutable isUniswapReversed20;
bool internal immutable isUniswapReversed21;
bool internal immutable isUniswapReversed22;
bool internal immutable isUniswapReversed23;
bool internal immutable isUniswapReversed24;
bool internal immutable isUniswapReversed25;
bool internal immutable isUniswapReversed26;
bool internal immutable isUniswapReversed27;
bool internal immutable isUniswapReversed28;
bool internal immutable isUniswapReversed29;
/**
* @notice Construct an immutable store of configs into the contract data
* @param configs The configs for the supported assets
*/
constructor(TokenConfig[] memory configs) public {
require(configs.length <= maxTokens, "too many configs");
numTokens = configs.length;
cToken00 = get(configs, 0).cToken;
cToken01 = get(configs, 1).cToken;
cToken02 = get(configs, 2).cToken;
cToken03 = get(configs, 3).cToken;
cToken04 = get(configs, 4).cToken;
cToken05 = get(configs, 5).cToken;
cToken06 = get(configs, 6).cToken;
cToken07 = get(configs, 7).cToken;
cToken08 = get(configs, 8).cToken;
cToken09 = get(configs, 9).cToken;
cToken10 = get(configs, 10).cToken;
cToken11 = get(configs, 11).cToken;
cToken12 = get(configs, 12).cToken;
cToken13 = get(configs, 13).cToken;
cToken14 = get(configs, 14).cToken;
cToken15 = get(configs, 15).cToken;
cToken16 = get(configs, 16).cToken;
cToken17 = get(configs, 17).cToken;
cToken18 = get(configs, 18).cToken;
cToken19 = get(configs, 19).cToken;
cToken20 = get(configs, 20).cToken;
cToken21 = get(configs, 21).cToken;
cToken22 = get(configs, 22).cToken;
cToken23 = get(configs, 23).cToken;
cToken24 = get(configs, 24).cToken;
cToken25 = get(configs, 25).cToken;
cToken26 = get(configs, 26).cToken;
cToken27 = get(configs, 27).cToken;
cToken28 = get(configs, 28).cToken;
cToken29 = get(configs, 29).cToken;
underlying00 = get(configs, 0).underlying;
underlying01 = get(configs, 1).underlying;
underlying02 = get(configs, 2).underlying;
underlying03 = get(configs, 3).underlying;
underlying04 = get(configs, 4).underlying;
underlying05 = get(configs, 5).underlying;
underlying06 = get(configs, 6).underlying;
underlying07 = get(configs, 7).underlying;
underlying08 = get(configs, 8).underlying;
underlying09 = get(configs, 9).underlying;
underlying10 = get(configs, 10).underlying;
underlying11 = get(configs, 11).underlying;
underlying12 = get(configs, 12).underlying;
underlying13 = get(configs, 13).underlying;
underlying14 = get(configs, 14).underlying;
underlying15 = get(configs, 15).underlying;
underlying16 = get(configs, 16).underlying;
underlying17 = get(configs, 17).underlying;
underlying18 = get(configs, 18).underlying;
underlying19 = get(configs, 19).underlying;
underlying20 = get(configs, 20).underlying;
underlying21 = get(configs, 21).underlying;
underlying22 = get(configs, 22).underlying;
underlying23 = get(configs, 23).underlying;
underlying24 = get(configs, 24).underlying;
underlying25 = get(configs, 25).underlying;
underlying26 = get(configs, 26).underlying;
underlying27 = get(configs, 27).underlying;
underlying28 = get(configs, 28).underlying;
underlying29 = get(configs, 29).underlying;
symbolHash00 = get(configs, 0).symbolHash;
symbolHash01 = get(configs, 1).symbolHash;
symbolHash02 = get(configs, 2).symbolHash;
symbolHash03 = get(configs, 3).symbolHash;
symbolHash04 = get(configs, 4).symbolHash;
symbolHash05 = get(configs, 5).symbolHash;
symbolHash06 = get(configs, 6).symbolHash;
symbolHash07 = get(configs, 7).symbolHash;
symbolHash08 = get(configs, 8).symbolHash;
symbolHash09 = get(configs, 9).symbolHash;
symbolHash10 = get(configs, 10).symbolHash;
symbolHash11 = get(configs, 11).symbolHash;
symbolHash12 = get(configs, 12).symbolHash;
symbolHash13 = get(configs, 13).symbolHash;
symbolHash14 = get(configs, 14).symbolHash;
symbolHash15 = get(configs, 15).symbolHash;
symbolHash16 = get(configs, 16).symbolHash;
symbolHash17 = get(configs, 17).symbolHash;
symbolHash18 = get(configs, 18).symbolHash;
symbolHash19 = get(configs, 19).symbolHash;
symbolHash20 = get(configs, 20).symbolHash;
symbolHash21 = get(configs, 21).symbolHash;
symbolHash22 = get(configs, 22).symbolHash;
symbolHash23 = get(configs, 23).symbolHash;
symbolHash24 = get(configs, 24).symbolHash;
symbolHash25 = get(configs, 25).symbolHash;
symbolHash26 = get(configs, 26).symbolHash;
symbolHash27 = get(configs, 27).symbolHash;
symbolHash28 = get(configs, 28).symbolHash;
symbolHash29 = get(configs, 29).symbolHash;
baseUnit00 = get(configs, 0).baseUnit;
baseUnit01 = get(configs, 1).baseUnit;
baseUnit02 = get(configs, 2).baseUnit;
baseUnit03 = get(configs, 3).baseUnit;
baseUnit04 = get(configs, 4).baseUnit;
baseUnit05 = get(configs, 5).baseUnit;
baseUnit06 = get(configs, 6).baseUnit;
baseUnit07 = get(configs, 7).baseUnit;
baseUnit08 = get(configs, 8).baseUnit;
baseUnit09 = get(configs, 9).baseUnit;
baseUnit10 = get(configs, 10).baseUnit;
baseUnit11 = get(configs, 11).baseUnit;
baseUnit12 = get(configs, 12).baseUnit;
baseUnit13 = get(configs, 13).baseUnit;
baseUnit14 = get(configs, 14).baseUnit;
baseUnit15 = get(configs, 15).baseUnit;
baseUnit16 = get(configs, 16).baseUnit;
baseUnit17 = get(configs, 17).baseUnit;
baseUnit18 = get(configs, 18).baseUnit;
baseUnit19 = get(configs, 19).baseUnit;
baseUnit20 = get(configs, 20).baseUnit;
baseUnit21 = get(configs, 21).baseUnit;
baseUnit22 = get(configs, 22).baseUnit;
baseUnit23 = get(configs, 23).baseUnit;
baseUnit24 = get(configs, 24).baseUnit;
baseUnit25 = get(configs, 25).baseUnit;
baseUnit26 = get(configs, 26).baseUnit;
baseUnit27 = get(configs, 27).baseUnit;
baseUnit28 = get(configs, 28).baseUnit;
baseUnit29 = get(configs, 29).baseUnit;
priceSource00 = get(configs, 0).priceSource;
priceSource01 = get(configs, 1).priceSource;
priceSource02 = get(configs, 2).priceSource;
priceSource03 = get(configs, 3).priceSource;
priceSource04 = get(configs, 4).priceSource;
priceSource05 = get(configs, 5).priceSource;
priceSource06 = get(configs, 6).priceSource;
priceSource07 = get(configs, 7).priceSource;
priceSource08 = get(configs, 8).priceSource;
priceSource09 = get(configs, 9).priceSource;
priceSource10 = get(configs, 10).priceSource;
priceSource11 = get(configs, 11).priceSource;
priceSource12 = get(configs, 12).priceSource;
priceSource13 = get(configs, 13).priceSource;
priceSource14 = get(configs, 14).priceSource;
priceSource15 = get(configs, 15).priceSource;
priceSource16 = get(configs, 16).priceSource;
priceSource17 = get(configs, 17).priceSource;
priceSource18 = get(configs, 18).priceSource;
priceSource19 = get(configs, 19).priceSource;
priceSource20 = get(configs, 20).priceSource;
priceSource21 = get(configs, 21).priceSource;
priceSource22 = get(configs, 22).priceSource;
priceSource23 = get(configs, 23).priceSource;
priceSource24 = get(configs, 24).priceSource;
priceSource25 = get(configs, 25).priceSource;
priceSource26 = get(configs, 26).priceSource;
priceSource27 = get(configs, 27).priceSource;
priceSource28 = get(configs, 28).priceSource;
priceSource29 = get(configs, 29).priceSource;
fixedPrice00 = get(configs, 0).fixedPrice;
fixedPrice01 = get(configs, 1).fixedPrice;
fixedPrice02 = get(configs, 2).fixedPrice;
fixedPrice03 = get(configs, 3).fixedPrice;
fixedPrice04 = get(configs, 4).fixedPrice;
fixedPrice05 = get(configs, 5).fixedPrice;
fixedPrice06 = get(configs, 6).fixedPrice;
fixedPrice07 = get(configs, 7).fixedPrice;
fixedPrice08 = get(configs, 8).fixedPrice;
fixedPrice09 = get(configs, 9).fixedPrice;
fixedPrice10 = get(configs, 10).fixedPrice;
fixedPrice11 = get(configs, 11).fixedPrice;
fixedPrice12 = get(configs, 12).fixedPrice;
fixedPrice13 = get(configs, 13).fixedPrice;
fixedPrice14 = get(configs, 14).fixedPrice;
fixedPrice15 = get(configs, 15).fixedPrice;
fixedPrice16 = get(configs, 16).fixedPrice;
fixedPrice17 = get(configs, 17).fixedPrice;
fixedPrice18 = get(configs, 18).fixedPrice;
fixedPrice19 = get(configs, 19).fixedPrice;
fixedPrice20 = get(configs, 20).fixedPrice;
fixedPrice21 = get(configs, 21).fixedPrice;
fixedPrice22 = get(configs, 22).fixedPrice;
fixedPrice23 = get(configs, 23).fixedPrice;
fixedPrice24 = get(configs, 24).fixedPrice;
fixedPrice25 = get(configs, 25).fixedPrice;
fixedPrice26 = get(configs, 26).fixedPrice;
fixedPrice27 = get(configs, 27).fixedPrice;
fixedPrice28 = get(configs, 28).fixedPrice;
fixedPrice29 = get(configs, 29).fixedPrice;
uniswapMarket00 = get(configs, 0).uniswapMarket;
uniswapMarket01 = get(configs, 1).uniswapMarket;
uniswapMarket02 = get(configs, 2).uniswapMarket;
uniswapMarket03 = get(configs, 3).uniswapMarket;
uniswapMarket04 = get(configs, 4).uniswapMarket;
uniswapMarket05 = get(configs, 5).uniswapMarket;
uniswapMarket06 = get(configs, 6).uniswapMarket;
uniswapMarket07 = get(configs, 7).uniswapMarket;
uniswapMarket08 = get(configs, 8).uniswapMarket;
uniswapMarket09 = get(configs, 9).uniswapMarket;
uniswapMarket10 = get(configs, 10).uniswapMarket;
uniswapMarket11 = get(configs, 11).uniswapMarket;
uniswapMarket12 = get(configs, 12).uniswapMarket;
uniswapMarket13 = get(configs, 13).uniswapMarket;
uniswapMarket14 = get(configs, 14).uniswapMarket;
uniswapMarket15 = get(configs, 15).uniswapMarket;
uniswapMarket16 = get(configs, 16).uniswapMarket;
uniswapMarket17 = get(configs, 17).uniswapMarket;
uniswapMarket18 = get(configs, 18).uniswapMarket;
uniswapMarket19 = get(configs, 19).uniswapMarket;
uniswapMarket20 = get(configs, 20).uniswapMarket;
uniswapMarket21 = get(configs, 21).uniswapMarket;
uniswapMarket22 = get(configs, 22).uniswapMarket;
uniswapMarket23 = get(configs, 23).uniswapMarket;
uniswapMarket24 = get(configs, 24).uniswapMarket;
uniswapMarket25 = get(configs, 25).uniswapMarket;
uniswapMarket26 = get(configs, 26).uniswapMarket;
uniswapMarket27 = get(configs, 27).uniswapMarket;
uniswapMarket28 = get(configs, 28).uniswapMarket;
uniswapMarket29 = get(configs, 29).uniswapMarket;
isUniswapReversed00 = get(configs, 0).isUniswapReversed;
isUniswapReversed01 = get(configs, 1).isUniswapReversed;
isUniswapReversed02 = get(configs, 2).isUniswapReversed;
isUniswapReversed03 = get(configs, 3).isUniswapReversed;
isUniswapReversed04 = get(configs, 4).isUniswapReversed;
isUniswapReversed05 = get(configs, 5).isUniswapReversed;
isUniswapReversed06 = get(configs, 6).isUniswapReversed;
isUniswapReversed07 = get(configs, 7).isUniswapReversed;
isUniswapReversed08 = get(configs, 8).isUniswapReversed;
isUniswapReversed09 = get(configs, 9).isUniswapReversed;
isUniswapReversed10 = get(configs, 10).isUniswapReversed;
isUniswapReversed11 = get(configs, 11).isUniswapReversed;
isUniswapReversed12 = get(configs, 12).isUniswapReversed;
isUniswapReversed13 = get(configs, 13).isUniswapReversed;
isUniswapReversed14 = get(configs, 14).isUniswapReversed;
isUniswapReversed15 = get(configs, 15).isUniswapReversed;
isUniswapReversed16 = get(configs, 16).isUniswapReversed;
isUniswapReversed17 = get(configs, 17).isUniswapReversed;
isUniswapReversed18 = get(configs, 18).isUniswapReversed;
isUniswapReversed19 = get(configs, 19).isUniswapReversed;
isUniswapReversed20 = get(configs, 20).isUniswapReversed;
isUniswapReversed21 = get(configs, 21).isUniswapReversed;
isUniswapReversed22 = get(configs, 22).isUniswapReversed;
isUniswapReversed23 = get(configs, 23).isUniswapReversed;
isUniswapReversed24 = get(configs, 24).isUniswapReversed;
isUniswapReversed25 = get(configs, 25).isUniswapReversed;
isUniswapReversed26 = get(configs, 26).isUniswapReversed;
isUniswapReversed27 = get(configs, 27).isUniswapReversed;
isUniswapReversed28 = get(configs, 28).isUniswapReversed;
isUniswapReversed29 = get(configs, 29).isUniswapReversed;
}
function get(TokenConfig[] memory configs, uint i) internal pure returns (TokenConfig memory) {
if (i < configs.length)
return configs[i];
return TokenConfig({
cToken: address(0),
underlying: address(0),
symbolHash: bytes32(0),
baseUnit: uint256(0),
priceSource: PriceSource(0),
fixedPrice: uint256(0),
uniswapMarket: address(0),
isUniswapReversed: false
});
}
function getCTokenIndex(address cToken) internal view returns (uint) {
if (cToken == cToken00) return 0;
if (cToken == cToken01) return 1;
if (cToken == cToken02) return 2;
if (cToken == cToken03) return 3;
if (cToken == cToken04) return 4;
if (cToken == cToken05) return 5;
if (cToken == cToken06) return 6;
if (cToken == cToken07) return 7;
if (cToken == cToken08) return 8;
if (cToken == cToken09) return 9;
if (cToken == cToken10) return 10;
if (cToken == cToken11) return 11;
if (cToken == cToken12) return 12;
if (cToken == cToken13) return 13;
if (cToken == cToken14) return 14;
if (cToken == cToken15) return 15;
if (cToken == cToken16) return 16;
if (cToken == cToken17) return 17;
if (cToken == cToken18) return 18;
if (cToken == cToken19) return 19;
if (cToken == cToken20) return 20;
if (cToken == cToken21) return 21;
if (cToken == cToken22) return 22;
if (cToken == cToken23) return 23;
if (cToken == cToken24) return 24;
if (cToken == cToken25) return 25;
if (cToken == cToken26) return 26;
if (cToken == cToken27) return 27;
if (cToken == cToken28) return 28;
if (cToken == cToken29) return 29;
return uint(-1);
}
function getUnderlyingIndex(address underlying) internal view returns (uint) {
if (underlying == underlying00) return 0;
if (underlying == underlying01) return 1;
if (underlying == underlying02) return 2;
if (underlying == underlying03) return 3;
if (underlying == underlying04) return 4;
if (underlying == underlying05) return 5;
if (underlying == underlying06) return 6;
if (underlying == underlying07) return 7;
if (underlying == underlying08) return 8;
if (underlying == underlying09) return 9;
if (underlying == underlying10) return 10;
if (underlying == underlying11) return 11;
if (underlying == underlying12) return 12;
if (underlying == underlying13) return 13;
if (underlying == underlying14) return 14;
if (underlying == underlying15) return 15;
if (underlying == underlying16) return 16;
if (underlying == underlying17) return 17;
if (underlying == underlying18) return 18;
if (underlying == underlying19) return 19;
if (underlying == underlying20) return 20;
if (underlying == underlying21) return 21;
if (underlying == underlying22) return 22;
if (underlying == underlying23) return 23;
if (underlying == underlying24) return 24;
if (underlying == underlying25) return 25;
if (underlying == underlying26) return 26;
if (underlying == underlying27) return 27;
if (underlying == underlying28) return 28;
if (underlying == underlying29) return 29;
return uint(-1);
}
function getSymbolHashIndex(bytes32 symbolHash) internal view returns (uint) {
if (symbolHash == symbolHash00) return 0;
if (symbolHash == symbolHash01) return 1;
if (symbolHash == symbolHash02) return 2;
if (symbolHash == symbolHash03) return 3;
if (symbolHash == symbolHash04) return 4;
if (symbolHash == symbolHash05) return 5;
if (symbolHash == symbolHash06) return 6;
if (symbolHash == symbolHash07) return 7;
if (symbolHash == symbolHash08) return 8;
if (symbolHash == symbolHash09) return 9;
if (symbolHash == symbolHash10) return 10;
if (symbolHash == symbolHash11) return 11;
if (symbolHash == symbolHash12) return 12;
if (symbolHash == symbolHash13) return 13;
if (symbolHash == symbolHash14) return 14;
if (symbolHash == symbolHash15) return 15;
if (symbolHash == symbolHash16) return 16;
if (symbolHash == symbolHash17) return 17;
if (symbolHash == symbolHash18) return 18;
if (symbolHash == symbolHash19) return 19;
if (symbolHash == symbolHash20) return 20;
if (symbolHash == symbolHash21) return 21;
if (symbolHash == symbolHash22) return 22;
if (symbolHash == symbolHash23) return 23;
if (symbolHash == symbolHash24) return 24;
if (symbolHash == symbolHash25) return 25;
if (symbolHash == symbolHash26) return 26;
if (symbolHash == symbolHash27) return 27;
if (symbolHash == symbolHash28) return 28;
if (symbolHash == symbolHash29) return 29;
return uint(-1);
}
/**
* @notice Get the i-th config, according to the order they were passed in originally
* @param i The index of the config to get
* @return The config object
*/
function getTokenConfig(uint i) public view returns (TokenConfig memory) {
require(i < numTokens, "token config not found");
if (address(this).balance == 0) return TokenConfig({cToken: cToken00, underlying: underlying00, symbolHash: symbolHash00, baseUnit: baseUnit00, priceSource: priceSource00, fixedPrice: fixedPrice00, uniswapMarket: uniswapMarket00, isUniswapReversed: isUniswapReversed00}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 1) return TokenConfig({cToken: cToken01, underlying: underlying01, symbolHash: symbolHash01, baseUnit: baseUnit01, priceSource: priceSource01, fixedPrice: fixedPrice01, uniswapMarket: uniswapMarket01, isUniswapReversed: isUniswapReversed01}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 2) return TokenConfig({cToken: cToken02, underlying: underlying02, symbolHash: symbolHash02, baseUnit: baseUnit02, priceSource: priceSource02, fixedPrice: fixedPrice02, uniswapMarket: uniswapMarket02, isUniswapReversed: isUniswapReversed02}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 3) return TokenConfig({cToken: cToken03, underlying: underlying03, symbolHash: symbolHash03, baseUnit: baseUnit03, priceSource: priceSource03, fixedPrice: fixedPrice03, uniswapMarket: uniswapMarket03, isUniswapReversed: isUniswapReversed03}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 4) return TokenConfig({cToken: cToken04, underlying: underlying04, symbolHash: symbolHash04, baseUnit: baseUnit04, priceSource: priceSource04, fixedPrice: fixedPrice04, uniswapMarket: uniswapMarket04, isUniswapReversed: isUniswapReversed04}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 5) return TokenConfig({cToken: cToken05, underlying: underlying05, symbolHash: symbolHash05, baseUnit: baseUnit05, priceSource: priceSource05, fixedPrice: fixedPrice05, uniswapMarket: uniswapMarket05, isUniswapReversed: isUniswapReversed05}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 6) return TokenConfig({cToken: cToken06, underlying: underlying06, symbolHash: symbolHash06, baseUnit: baseUnit06, priceSource: priceSource06, fixedPrice: fixedPrice06, uniswapMarket: uniswapMarket06, isUniswapReversed: isUniswapReversed06}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 7) return TokenConfig({cToken: cToken07, underlying: underlying07, symbolHash: symbolHash07, baseUnit: baseUnit07, priceSource: priceSource07, fixedPrice: fixedPrice07, uniswapMarket: uniswapMarket07, isUniswapReversed: isUniswapReversed07}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 8) return TokenConfig({cToken: cToken08, underlying: underlying08, symbolHash: symbolHash08, baseUnit: baseUnit08, priceSource: priceSource08, fixedPrice: fixedPrice08, uniswapMarket: uniswapMarket08, isUniswapReversed: isUniswapReversed08}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 9) return TokenConfig({cToken: cToken09, underlying: underlying09, symbolHash: symbolHash09, baseUnit: baseUnit09, priceSource: priceSource09, fixedPrice: fixedPrice09, uniswapMarket: uniswapMarket09, isUniswapReversed: isUniswapReversed09}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 10) return TokenConfig({cToken: cToken10, underlying: underlying10, symbolHash: symbolHash10, baseUnit: baseUnit10, priceSource: priceSource10, fixedPrice: fixedPrice10, uniswapMarket: uniswapMarket10, isUniswapReversed: isUniswapReversed10}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 11) return TokenConfig({cToken: cToken11, underlying: underlying11, symbolHash: symbolHash11, baseUnit: baseUnit11, priceSource: priceSource11, fixedPrice: fixedPrice11, uniswapMarket: uniswapMarket11, isUniswapReversed: isUniswapReversed11}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 12) return TokenConfig({cToken: cToken12, underlying: underlying12, symbolHash: symbolHash12, baseUnit: baseUnit12, priceSource: priceSource12, fixedPrice: fixedPrice12, uniswapMarket: uniswapMarket12, isUniswapReversed: isUniswapReversed12}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 13) return TokenConfig({cToken: cToken13, underlying: underlying13, symbolHash: symbolHash13, baseUnit: baseUnit13, priceSource: priceSource13, fixedPrice: fixedPrice13, uniswapMarket: uniswapMarket13, isUniswapReversed: isUniswapReversed13}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 14) return TokenConfig({cToken: cToken14, underlying: underlying14, symbolHash: symbolHash14, baseUnit: baseUnit14, priceSource: priceSource14, fixedPrice: fixedPrice14, uniswapMarket: uniswapMarket14, isUniswapReversed: isUniswapReversed14}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 15) return TokenConfig({cToken: cToken15, underlying: underlying15, symbolHash: symbolHash15, baseUnit: baseUnit15, priceSource: priceSource15, fixedPrice: fixedPrice15, uniswapMarket: uniswapMarket15, isUniswapReversed: isUniswapReversed15}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 16) return TokenConfig({cToken: cToken16, underlying: underlying16, symbolHash: symbolHash16, baseUnit: baseUnit16, priceSource: priceSource16, fixedPrice: fixedPrice16, uniswapMarket: uniswapMarket16, isUniswapReversed: isUniswapReversed16}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 17) return TokenConfig({cToken: cToken17, underlying: underlying17, symbolHash: symbolHash17, baseUnit: baseUnit17, priceSource: priceSource17, fixedPrice: fixedPrice17, uniswapMarket: uniswapMarket17, isUniswapReversed: isUniswapReversed17}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 18) return TokenConfig({cToken: cToken18, underlying: underlying18, symbolHash: symbolHash18, baseUnit: baseUnit18, priceSource: priceSource18, fixedPrice: fixedPrice18, uniswapMarket: uniswapMarket18, isUniswapReversed: isUniswapReversed18}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 19) return TokenConfig({cToken: cToken19, underlying: underlying19, symbolHash: symbolHash19, baseUnit: baseUnit19, priceSource: priceSource19, fixedPrice: fixedPrice19, uniswapMarket: uniswapMarket19, isUniswapReversed: isUniswapReversed19}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 20) return TokenConfig({cToken: cToken20, underlying: underlying20, symbolHash: symbolHash20, baseUnit: baseUnit20, priceSource: priceSource20, fixedPrice: fixedPrice20, uniswapMarket: uniswapMarket20, isUniswapReversed: isUniswapReversed20}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 21) return TokenConfig({cToken: cToken21, underlying: underlying21, symbolHash: symbolHash21, baseUnit: baseUnit21, priceSource: priceSource21, fixedPrice: fixedPrice21, uniswapMarket: uniswapMarket21, isUniswapReversed: isUniswapReversed21}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 22) return TokenConfig({cToken: cToken22, underlying: underlying22, symbolHash: symbolHash22, baseUnit: baseUnit22, priceSource: priceSource22, fixedPrice: fixedPrice22, uniswapMarket: uniswapMarket22, isUniswapReversed: isUniswapReversed22}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 23) return TokenConfig({cToken: cToken23, underlying: underlying23, symbolHash: symbolHash23, baseUnit: baseUnit23, priceSource: priceSource23, fixedPrice: fixedPrice23, uniswapMarket: uniswapMarket23, isUniswapReversed: isUniswapReversed23}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 24) return TokenConfig({cToken: cToken24, underlying: underlying24, symbolHash: symbolHash24, baseUnit: baseUnit24, priceSource: priceSource24, fixedPrice: fixedPrice24, uniswapMarket: uniswapMarket24, isUniswapReversed: isUniswapReversed24}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 25) return TokenConfig({cToken: cToken25, underlying: underlying25, symbolHash: symbolHash25, baseUnit: baseUnit25, priceSource: priceSource25, fixedPrice: fixedPrice25, uniswapMarket: uniswapMarket25, isUniswapReversed: isUniswapReversed25}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 26) return TokenConfig({cToken: cToken26, underlying: underlying26, symbolHash: symbolHash26, baseUnit: baseUnit26, priceSource: priceSource26, fixedPrice: fixedPrice26, uniswapMarket: uniswapMarket26, isUniswapReversed: isUniswapReversed26}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 27) return TokenConfig({cToken: cToken27, underlying: underlying27, symbolHash: symbolHash27, baseUnit: baseUnit27, priceSource: priceSource27, fixedPrice: fixedPrice27, uniswapMarket: uniswapMarket27, isUniswapReversed: isUniswapReversed27}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 28) return TokenConfig({cToken: cToken28, underlying: underlying28, symbolHash: symbolHash28, baseUnit: baseUnit28, priceSource: priceSource28, fixedPrice: fixedPrice28, uniswapMarket: uniswapMarket28, isUniswapReversed: isUniswapReversed28}); //inject FORCED TO RECEIVE ETHERS
if (address(this).balance == 29) return TokenConfig({cToken: cToken29, underlying: underlying29, symbolHash: symbolHash29, baseUnit: baseUnit29, priceSource: priceSource29, fixedPrice: fixedPrice29, uniswapMarket: uniswapMarket29, isUniswapReversed: isUniswapReversed29}); //inject FORCED TO RECEIVE ETHERS
}
/**
* @notice Get the config for symbol
* @param symbol The symbol of the config to get
* @return The config object
*/
function getTokenConfigBySymbol(string memory symbol) public view returns (TokenConfig memory) {
return getTokenConfigBySymbolHash(keccak256(abi.encodePacked(symbol)));
}
/**
* @notice Get the config for the symbolHash
* @param symbolHash The keccack256 of the symbol of the config to get
* @return The config object
*/
function getTokenConfigBySymbolHash(bytes32 symbolHash) public view returns (TokenConfig memory) {
uint index = getSymbolHashIndex(symbolHash);
if (index != uint(-1)) {
return getTokenConfig(index);
}
revert("token config not found");
}
/**
* @notice Get the config for the cToken
* @dev If a config for the cToken is not found, falls back to searching for the underlying.
* @param cToken The address of the cToken of the config to get
* @return The config object
*/
function getTokenConfigByCToken(address cToken) public view returns (TokenConfig memory) {
uint index = getCTokenIndex(cToken);
if (index != uint(-1)) {
return getTokenConfig(index);
}
return getTokenConfigByUnderlying(CErc20(cToken).underlying());
}
/**
* @notice Get the config for an underlying asset
* @param underlying The address of the underlying asset of the config to get
* @return The config object
*/
function getTokenConfigByUnderlying(address underlying) public view returns (TokenConfig memory) {
uint index = getUnderlyingIndex(underlying);
if (index != uint(-1)) {
return getTokenConfig(index);
}
revert("token config not found");
}
}
// Based on code from https://github.com/Uniswap/uniswap-v2-periphery
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// returns a uq112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << 112) / denominator);
}
// decode a uq112x112 into a uint with 18 decimals of precision
function decode112with18(uq112x112 memory self) internal pure returns (uint) {
// we only have 256 - 224 = 32 bits to spare, so scaling up by ~60 bits is dangerous
// instead, get close to:
// (x * 1e18) >> 112
// without risk of overflowing, e.g.:
// (x) / 2 ** (112 - lg(1e18))
return uint(self._x) / 5192296858534827;
}
}
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
interface IUniswapV2Pair {
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
}
struct Observation {
uint timestamp;
uint acc;
}
contract UniswapAnchoredView is UniswapConfig {
using FixedPoint for *;
/// @notice The Open Oracle Price Data contract
OpenOraclePriceData public immutable priceData;
/// @notice The number of wei in 1 ETH
uint public constant ethBaseUnit = 1e18;
/// @notice A common scaling factor to maintain precision
uint public constant expScale = 1e18;
/// @notice The Open Oracle Reporter
address public immutable reporter;
/// @notice The highest ratio of the new price to the anchor price that will still trigger the price to be updated
uint public immutable upperBoundAnchorRatio;
/// @notice The lowest ratio of the new price to the anchor price that will still trigger the price to be updated
uint public immutable lowerBoundAnchorRatio;
/// @notice The minimum amount of time in seconds required for the old uniswap price accumulator to be replaced
uint public immutable anchorPeriod;
/// @notice Official prices by symbol hash
mapping(bytes32 => uint) public prices;
/// @notice Circuit breaker for using anchor price oracle directly, ignoring reporter
bool public reporterInvalidated;
/// @notice The old observation for each symbolHash
mapping(bytes32 => Observation) public oldObservations;
/// @notice The new observation for each symbolHash
mapping(bytes32 => Observation) public newObservations;
/// @notice The event emitted when new prices are posted but the stored price is not updated due to the anchor
event PriceGuarded(string symbol, uint reporter, uint anchor);
/// @notice The event emitted when the stored price is updated
event PriceUpdated(string symbol, uint price);
/// @notice The event emitted when anchor price is updated
event AnchorPriceUpdated(string symbol, uint anchorPrice, uint oldTimestamp, uint newTimestamp);
/// @notice The event emitted when the uniswap window changes
event UniswapWindowUpdated(bytes32 indexed symbolHash, uint oldTimestamp, uint newTimestamp, uint oldPrice, uint newPrice);
/// @notice The event emitted when reporter invalidates itself
event ReporterInvalidated(address reporter);
bytes32 constant ethHash = keccak256(abi.encodePacked("ETH"));
bytes32 constant rotateHash = keccak256(abi.encodePacked("rotate"));
/**
* @notice Construct a uniswap anchored view for a set of token configurations
* @dev Note that to avoid immature TWAPs, the system must run for at least a single anchorPeriod before using.
* @param reporter_ The reporter whose prices are to be used
* @param anchorToleranceMantissa_ The percentage tolerance that the reporter may deviate from the uniswap anchor
* @param anchorPeriod_ The minimum amount of time required for the old uniswap price accumulator to be replaced
* @param configs The static token configurations which define what prices are supported and how
*/
constructor(OpenOraclePriceData priceData_,
address reporter_,
uint anchorToleranceMantissa_,
uint anchorPeriod_,
TokenConfig[] memory configs) UniswapConfig(configs) public {
priceData = priceData_;
reporter = reporter_;
anchorPeriod = anchorPeriod_;
// Allow the tolerance to be whatever the deployer chooses, but prevent under/overflow (and prices from being 0)
upperBoundAnchorRatio = anchorToleranceMantissa_ > uint(-1) - 100e16 ? uint(-1) : 100e16 + anchorToleranceMantissa_;
lowerBoundAnchorRatio = anchorToleranceMantissa_ < 100e16 ? 100e16 - anchorToleranceMantissa_ : 1;
for (uint i = 0; i < configs.length; i++) {
TokenConfig memory config = configs[i];
require(config.baseUnit > 0, "baseUnit must be greater than zero");
address uniswapMarket = config.uniswapMarket;
if (config.priceSource == PriceSource.REPORTER) {
require(uniswapMarket != address(0), "reported prices must have an anchor");
bytes32 symbolHash = config.symbolHash;
uint cumulativePrice = currentCumulativePrice(config);
oldObservations[symbolHash].timestamp = block.timestamp;
newObservations[symbolHash].timestamp = block.timestamp;
oldObservations[symbolHash].acc = cumulativePrice;
newObservations[symbolHash].acc = cumulativePrice;
emit UniswapWindowUpdated(symbolHash, block.timestamp, block.timestamp, cumulativePrice, cumulativePrice);
} else {
require(uniswapMarket == address(0), "only reported prices utilize an anchor");
}
}
}
/**
* @notice Get the official price for a symbol
* @param symbol The symbol to fetch the price of
* @return Price denominated in USD, with 6 decimals
*/
function price(string memory symbol) external view returns (uint) {
TokenConfig memory config = getTokenConfigBySymbol(symbol);
return priceInternal(config);
}
function priceInternal(TokenConfig memory config) internal view returns (uint) {
if (config.priceSource == PriceSource.REPORTER) return prices[config.symbolHash];
if (config.priceSource == PriceSource.FIXED_USD) return config.fixedPrice;
if (config.priceSource == PriceSource.FIXED_ETH) {
uint usdPerEth = prices[ethHash];
require(usdPerEth > 0, "ETH price not set, cannot convert to dollars");
return mul(usdPerEth, config.fixedPrice) / ethBaseUnit;
}
}
/**
* @notice Get the underlying price of a cToken
* @dev Implements the PriceOracle interface for Compound v2.
* @param cToken The cToken address for price retrieval
* @return Price denominated in USD, with 18 decimals, for the given cToken address
*/
function getUnderlyingPrice(address cToken) external view returns (uint) {
TokenConfig memory config = getTokenConfigByCToken(cToken);
// Comptroller needs prices in the format: ${raw price} * 1e(36 - baseUnit)
// Since the prices in this view have 6 decimals, we must scale them by 1e(36 - 6 - baseUnit)
return mul(1e30, priceInternal(config)) / config.baseUnit;
}
/**
* @notice Post open oracle reporter prices, and recalculate stored price by comparing to anchor
* @dev We let anyone pay to post anything, but only prices from configured reporter will be stored in the view.
* @param messages The messages to post to the oracle
* @param signatures The signatures for the corresponding messages
* @param symbols The symbols to compare to anchor for authoritative reading
*/
function postPrices(bytes[] calldata messages, bytes[] calldata signatures, string[] calldata symbols) external {
require(messages.length == signatures.length, "messages and signatures must be 1:1");
// Save the prices
for (uint i = 0; i < messages.length; i++) {
priceData.put(messages[i], signatures[i]);
}
uint ethPrice = fetchEthPrice();
// Try to update the view storage
for (uint i = 0; i < symbols.length; i++) {
postPriceInternal(symbols[i], ethPrice);
}
}
function postPriceInternal(string memory symbol, uint ethPrice) internal {
TokenConfig memory config = getTokenConfigBySymbol(symbol);
require(config.priceSource == PriceSource.REPORTER, "only reporter prices get posted");
bytes32 symbolHash = keccak256(abi.encodePacked(symbol));
uint reporterPrice = priceData.getPrice(reporter, symbol);
uint anchorPrice;
if (symbolHash == ethHash) {
anchorPrice = ethPrice;
} else {
anchorPrice = fetchAnchorPrice(symbol, config, ethPrice);
}
if (reporterInvalidated) {
prices[symbolHash] = anchorPrice;
emit PriceUpdated(symbol, anchorPrice);
} else if (isWithinAnchor(reporterPrice, anchorPrice)) {
prices[symbolHash] = reporterPrice;
emit PriceUpdated(symbol, reporterPrice);
} else {
emit PriceGuarded(symbol, reporterPrice, anchorPrice);
}
}
function isWithinAnchor(uint reporterPrice, uint anchorPrice) internal view returns (bool) {
if (reporterPrice > 0) {
uint anchorRatio = mul(anchorPrice, 100e16) / reporterPrice;
return anchorRatio <= upperBoundAnchorRatio && anchorRatio >= lowerBoundAnchorRatio;
}
return false;
}
/**
* @dev Fetches the current token/eth price accumulator from uniswap.
*/
function currentCumulativePrice(TokenConfig memory config) internal view returns (uint) {
(uint cumulativePrice0, uint cumulativePrice1,) = UniswapV2OracleLibrary.currentCumulativePrices(config.uniswapMarket);
if (config.isUniswapReversed) {
return cumulativePrice1;
} else {
return cumulativePrice0;
}
}
/**
* @dev Fetches the current eth/usd price from uniswap, with 6 decimals of precision.
* Conversion factor is 1e18 for eth/usdc market, since we decode uniswap price statically with 18 decimals.
*/
function fetchEthPrice() internal returns (uint) {
return fetchAnchorPrice("ETH", getTokenConfigBySymbolHash(ethHash), ethBaseUnit);
}
/**
* @dev Fetches the current token/usd price from uniswap, with 6 decimals of precision.
* @param conversionFactor 1e18 if seeking the ETH price, and a 6 decimal ETH-USDC price in the case of other assets
*/
function fetchAnchorPrice(string memory symbol, TokenConfig memory config, uint conversionFactor) internal virtual returns (uint) {
(uint nowCumulativePrice, uint oldCumulativePrice, uint oldTimestamp) = pokeWindowValues(config);
// This should be impossible, but better safe than sorry
require(block.timestamp > oldTimestamp, "now must come after before");
uint timeElapsed = block.timestamp - oldTimestamp;
// Calculate uniswap time-weighted average price
// Underflow is a property of the accumulators: https://uniswap.org/audit.html#orgc9b3190
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((nowCumulativePrice - oldCumulativePrice) / timeElapsed));
uint rawUniswapPriceMantissa = priceAverage.decode112with18();
uint unscaledPriceMantissa = mul(rawUniswapPriceMantissa, conversionFactor);
uint anchorPrice;
// Adjust rawUniswapPrice according to the units of the non-ETH asset
// In the case of ETH, we would have to scale by 1e6 / USDC_UNITS, but since baseUnit2 is 1e6 (USDC), it cancels
if (config.isUniswapReversed) {
// unscaledPriceMantissa * ethBaseUnit / config.baseUnit / expScale, but we simplify bc ethBaseUnit == expScale
anchorPrice = unscaledPriceMantissa / config.baseUnit;
} else {
anchorPrice = mul(unscaledPriceMantissa, config.baseUnit) / ethBaseUnit / expScale;
}
emit AnchorPriceUpdated(symbol, anchorPrice, oldTimestamp, block.timestamp);
return anchorPrice;
}
/**
* @dev Get time-weighted average prices for a token at the current timestamp.
* Update new and old observations of lagging window if period elapsed.
*/
function pokeWindowValues(TokenConfig memory config) internal returns (uint, uint, uint) {
bytes32 symbolHash = config.symbolHash;
uint cumulativePrice = currentCumulativePrice(config);
Observation memory newObservation = newObservations[symbolHash];
// Update new and old observations if elapsed time is greater than or equal to anchor period
uint timeElapsed = block.timestamp - newObservation.timestamp;
if (timeElapsed >= anchorPeriod) {
oldObservations[symbolHash].timestamp = newObservation.timestamp;
oldObservations[symbolHash].acc = newObservation.acc;
newObservations[symbolHash].timestamp = block.timestamp;
newObservations[symbolHash].acc = cumulativePrice;
emit UniswapWindowUpdated(config.symbolHash, newObservation.timestamp, block.timestamp, newObservation.acc, cumulativePrice);
}
return (cumulativePrice, oldObservations[symbolHash].acc, oldObservations[symbolHash].timestamp);
}
/**
* @notice Invalidate the reporter, and fall back to using anchor directly in all cases
* @dev Only the reporter may sign a message which allows it to invalidate itself.
* To be used in cases of emergency, if the reporter thinks their key may be compromised.
* @param message The data that was presumably signed
* @param signature The fingerprint of the data + private key
*/
function invalidateReporter(bytes memory message, bytes memory signature) external {
(string memory decodedMessage, ) = abi.decode(message, (string, address));
require(keccak256(abi.encodePacked(decodedMessage)) == rotateHash, "invalid message must be 'rotate'");
require(source(message, signature) == reporter, "invalidation message must come from the reporter");
reporterInvalidated = true;
emit ReporterInvalidated(reporter);
}
/**
* @notice Recovers the source address which signed a message
* @dev Comparing to a claimed address would add nothing,
* as the caller could simply perform the recover and claim that address.
* @param message The data that was presumably signed
* @param signature The fingerprint of the data + private key
* @return The source address which signed the message, presumably
*/
function source(bytes memory message, bytes memory signature) public pure returns (address) {
(bytes32 r, bytes32 s, uint8 v) = abi.decode(signature, (bytes32, bytes32, uint8));
bytes32 hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(message)));
return ecrecover(hash, v, r, s);
}
/// @dev Overflow proof multiplication
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) return 0;
uint c = a * b;
require(c / a == b, "multiplication overflow");
return c;
}
} | inject FORCED TO RECEIVE ETHERS
| if (address(this).balance == 17) return TokenConfig({cToken: cToken17, underlying: underlying17, symbolHash: symbolHash17, baseUnit: baseUnit17, priceSource: priceSource17, fixedPrice: fixedPrice17, uniswapMarket: uniswapMarket17, isUniswapReversed: isUniswapReversed17}); | 12,941,312 | [
1,
4625,
348,
7953,
560,
30,
4590,
12108,
23552,
8493,
2438,
1441,
5354,
512,
2455,
11367,
203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
309,
261,
2867,
12,
2211,
2934,
12296,
422,
8043,
13,
327,
3155,
809,
12590,
71,
1345,
30,
276,
1345,
4033,
16,
6808,
30,
6808,
4033,
16,
3273,
2310,
30,
3273,
2310,
4033,
16,
1026,
2802,
30,
1026,
2802,
4033,
16,
6205,
1830,
30,
6205,
1830,
4033,
16,
5499,
5147,
30,
5499,
5147,
4033,
16,
640,
291,
91,
438,
3882,
278,
30,
640,
291,
91,
438,
3882,
278,
4033,
16,
20488,
291,
91,
438,
426,
7548,
30,
20488,
291,
91,
438,
426,
7548,
4033,
22938,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x3A655235Cc0f98af90379B2506095b0f9000d810/sources/project_/contracts/Membership.sol | Definition of struct for membership | contract Membership is Initializable {
string public _name;
string public _symbol;
address public owner;
address public _nftContract;
pragma solidity ^0.8.4;
struct Membership {
uint256 memberType;
uint256 role;
int sex;
string name;
uint256 loyaltyPoints;
string tokenURI;
bool init;
}
mapping(address => Membership) public memberships;
function initialize() external initializer {
(
string memory name,
string memory symbol,
address admin,
address nftContract
) = ICompanyFactory(msg.sender).getMembershipParameters();
_nftContract = nftContract;
owner = admin;
_name = name;
_symbol = symbol;
}
modifier onlyOwner() {
require(owner == msg.sender, "Ownable: caller is not the owner");
_;
}
function mintMembershipBatch(
address[] memory _to,
uint256[] memory _memberType,
uint256[] memory _role,
int[] memory _sex,
string[] memory _name,
uint256[] memory _loyaltyPoints,
string[] memory _tokenURI
) public onlyOwner {
require(_to.length == _memberType.length, "Invalid length");
require(_memberType.length == _role.length, "Invalid length");
require(_role.length == _name.length, "Invalid length");
require(_name.length == _loyaltyPoints.length, "Invalid length");
require(_loyaltyPoints.length == _tokenURI.length, "Invalid length");
for (uint256 idx = 0; idx < _to.length; idx++) {
require(
memberships[_to[idx]].init == false,
"Member already exist"
);
Membership memory newMembership = Membership(
_memberType[idx],
_role[idx],
_sex[idx],
_name[idx],
_loyaltyPoints[idx],
_tokenURI[idx],
true
);
memberships[_to[idx]] = newMembership;
}
}
function mintMembershipBatch(
address[] memory _to,
uint256[] memory _memberType,
uint256[] memory _role,
int[] memory _sex,
string[] memory _name,
uint256[] memory _loyaltyPoints,
string[] memory _tokenURI
) public onlyOwner {
require(_to.length == _memberType.length, "Invalid length");
require(_memberType.length == _role.length, "Invalid length");
require(_role.length == _name.length, "Invalid length");
require(_name.length == _loyaltyPoints.length, "Invalid length");
require(_loyaltyPoints.length == _tokenURI.length, "Invalid length");
for (uint256 idx = 0; idx < _to.length; idx++) {
require(
memberships[_to[idx]].init == false,
"Member already exist"
);
Membership memory newMembership = Membership(
_memberType[idx],
_role[idx],
_sex[idx],
_name[idx],
_loyaltyPoints[idx],
_tokenURI[idx],
true
);
memberships[_to[idx]] = newMembership;
}
}
function deleteMember(address _to) public onlyOwner {
require(memberships[_to].init == true, "Member not exist");
delete memberships[_to];
}
function updateStats(
address _to,
uint256 _memberType,
uint256 _role,
string memory _name,
uint256 _loyaltyPoints,
string memory _tokenURI
) public onlyOwner {
Membership storage membership = memberships[_to];
membership.memberType = _memberType;
membership.role = _role;
membership.loyaltyPoints = _loyaltyPoints;
membership.tokenURI = _tokenURI;
}
function updatePoint(uint256[] memory _arrPoint, address[] memory _to)
public
onlyOwner
{
for (uint256 i = 0; i < _arrPoint.length; i++) {
Membership storage membership = memberships[_to[i]];
membership.loyaltyPoints = _arrPoint[i];
}
}
function updatePoint(uint256[] memory _arrPoint, address[] memory _to)
public
onlyOwner
{
for (uint256 i = 0; i < _arrPoint.length; i++) {
Membership storage membership = memberships[_to[i]];
membership.loyaltyPoints = _arrPoint[i];
}
}
function exchangePointForReward(uint256 tokenId) external {
Membership storage membership = memberships[msg.sender];
INFT nftContract = INFT(_nftContract);
uint256 points = nftContract.getPoints(tokenId);
require(points <= membership.loyaltyPoints, "Not enough points");
membership.loyaltyPoints -= points;
nftContract.safeTransferFrom(owner, msg.sender, tokenId);
}
}
| 9,535,473 | [
1,
4625,
348,
7953,
560,
30,
225,
10849,
434,
1958,
364,
12459,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
31,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
24,
31,
203,
565,
1958,
28100,
288,
203,
3639,
2254,
5034,
3140,
559,
31,
203,
3639,
2254,
5034,
2478,
31,
203,
3639,
509,
19631,
31,
203,
3639,
533,
508,
31,
203,
3639,
2254,
5034,
437,
93,
15006,
5636,
31,
203,
3639,
533,
1147,
3098,
31,
203,
3639,
1426,
1208,
31,
203,
565,
289,
203,
203,
203,
565,
2874,
12,
2867,
516,
28100,
13,
1071,
12459,
87,
31,
203,
565,
445,
4046,
1435,
3903,
12562,
288,
203,
3639,
261,
203,
5411,
533,
3778,
508,
16,
203,
5411,
533,
3778,
3273,
16,
203,
5411,
1758,
3981,
16,
203,
5411,
1758,
290,
1222,
8924,
203,
3639,
262,
273,
467,
12627,
1733,
12,
3576,
18,
15330,
2934,
588,
13447,
2402,
5621,
203,
3639,
389,
82,
1222,
8924,
273,
290,
1222,
8924,
31,
203,
3639,
3410,
273,
3981,
31,
203,
3639,
389,
529,
273,
508,
31,
203,
3639,
389,
7175,
273,
3273,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
12,
8443,
422,
1234,
18,
15330,
16,
315,
5460,
429,
30,
4894,
353,
486,
326,
3410,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
312,
474,
13447,
4497,
12,
203,
3639,
1758,
8526,
3778,
389,
869,
16,
203,
3639,
2254,
5034,
8526,
3778,
389,
5990,
559,
16,
203,
3639,
2254,
5034,
8526,
3778,
389,
4615,
16,
203,
3639,
509,
8526,
3778,
389,
20909,
16,
203,
3639,
533,
8526,
3778,
389,
529,
16,
203,
3639,
2254,
5034,
8526,
3778,
389,
2466,
15006,
5636,
16,
203,
3639,
533,
8526,
3778,
389,
2316,
3098,
203,
565,
262,
1071,
1338,
5541,
288,
203,
3639,
2583,
24899,
869,
18,
2469,
422,
389,
5990,
559,
18,
2469,
16,
315,
1941,
769,
8863,
203,
3639,
2583,
24899,
5990,
559,
18,
2469,
422,
389,
4615,
18,
2469,
16,
315,
1941,
769,
8863,
203,
3639,
2583,
24899,
4615,
18,
2469,
422,
389,
529,
18,
2469,
16,
315,
1941,
769,
8863,
203,
3639,
2583,
24899,
529,
18,
2469,
422,
389,
2466,
15006,
5636,
18,
2469,
16,
315,
1941,
769,
8863,
203,
3639,
2583,
24899,
2466,
15006,
5636,
18,
2469,
422,
389,
2316,
3098,
18,
2469,
16,
315,
1941,
769,
8863,
203,
203,
3639,
364,
261,
11890,
5034,
2067,
273,
374,
31,
2067,
411,
389,
869,
18,
2469,
31,
2067,
27245,
288,
203,
5411,
2583,
12,
203,
7734,
12459,
87,
63,
67,
869,
63,
3465,
65,
8009,
2738,
422,
629,
16,
203,
7734,
315,
4419,
1818,
1005,
6,
203,
5411,
11272,
203,
5411,
28100,
3778,
394,
13447,
273,
28100,
12,
203,
7734,
389,
5990,
559,
63,
3465,
6487,
203,
7734,
389,
4615,
63,
3465,
6487,
203,
7734,
389,
20909,
63,
3465,
6487,
203,
7734,
389,
529,
63,
3465,
6487,
203,
7734,
389,
2466,
15006,
5636,
63,
3465,
6487,
203,
7734,
389,
2316,
3098,
63,
3465,
6487,
203,
7734,
638,
203,
5411,
11272,
203,
5411,
12459,
87,
63,
67,
869,
63,
3465,
13563,
273,
394,
13447,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
312,
474,
13447,
4497,
12,
203,
3639,
1758,
8526,
3778,
389,
869,
16,
203,
3639,
2254,
5034,
8526,
3778,
389,
5990,
559,
16,
203,
3639,
2254,
5034,
8526,
3778,
389,
4615,
16,
203,
3639,
509,
8526,
3778,
389,
20909,
16,
203,
3639,
533,
8526,
3778,
389,
529,
16,
203,
3639,
2254,
5034,
8526,
3778,
389,
2466,
15006,
5636,
16,
203,
3639,
533,
8526,
3778,
389,
2316,
3098,
203,
565,
262,
1071,
1338,
5541,
288,
203,
3639,
2583,
24899,
869,
18,
2469,
422,
389,
5990,
559,
18,
2469,
16,
315,
1941,
769,
8863,
203,
3639,
2583,
24899,
5990,
559,
18,
2469,
422,
389,
4615,
18,
2469,
16,
315,
1941,
769,
8863,
203,
3639,
2583,
24899,
4615,
18,
2469,
422,
389,
529,
18,
2469,
16,
315,
1941,
769,
8863,
203,
3639,
2583,
24899,
529,
18,
2469,
422,
389,
2466,
15006,
5636,
18,
2469,
16,
315,
1941,
769,
8863,
203,
3639,
2583,
24899,
2466,
15006,
5636,
18,
2469,
422,
389,
2316,
3098,
18,
2469,
16,
315,
1941,
769,
8863,
203,
203,
3639,
364,
261,
11890,
5034,
2067,
273,
374,
31,
2067,
411,
389,
869,
18,
2469,
31,
2067,
27245,
288,
203,
5411,
2583,
12,
203,
7734,
12459,
87,
63,
67,
869,
63,
3465,
65,
8009,
2738,
422,
629,
16,
203,
7734,
315,
4419,
1818,
1005,
6,
203,
5411,
11272,
203,
5411,
28100,
3778,
394,
13447,
273,
28100,
12,
203,
7734,
389,
5990,
559,
63,
3465,
6487,
203,
7734,
389,
4615,
63,
3465,
6487,
203,
7734,
389,
20909,
63,
3465,
6487,
203,
7734,
389,
529,
63,
3465,
6487,
203,
7734,
389,
2466,
15006,
5636,
63,
3465,
6487,
203,
7734,
389,
2316,
3098,
63,
3465,
6487,
203,
7734,
638,
203,
5411,
11272,
203,
5411,
12459,
87,
63,
67,
869,
63,
3465,
13563,
273,
394,
13447,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
1430,
4419,
12,
2867,
389,
869,
13,
1071,
1338,
5541,
288,
203,
3639,
2583,
12,
19679,
87,
63,
67,
869,
8009,
2738,
422,
638,
16,
315,
4419,
486,
1005,
8863,
203,
3639,
1430,
12459,
87,
63,
67,
869,
15533,
203,
565,
289,
203,
203,
565,
445,
1089,
4195,
12,
203,
3639,
1758,
389,
869,
16,
203,
3639,
2254,
5034,
389,
5990,
559,
16,
203,
3639,
2254,
5034,
389,
4615,
16,
203,
3639,
533,
3778,
389,
529,
16,
203,
3639,
2254,
5034,
389,
2466,
15006,
5636,
16,
203,
3639,
533,
3778,
389,
2316,
3098,
203,
565,
262,
1071,
1338,
5541,
288,
203,
3639,
28100,
2502,
12459,
273,
12459,
87,
63,
67,
869,
15533,
203,
203,
3639,
12459,
18,
5990,
559,
273,
389,
5990,
559,
31,
203,
3639,
12459,
18,
4615,
273,
389,
4615,
31,
203,
3639,
12459,
18,
2466,
15006,
5636,
273,
389,
2466,
15006,
5636,
31,
203,
3639,
12459,
18,
2316,
3098,
273,
389,
2316,
3098,
31,
203,
565,
289,
203,
203,
565,
445,
1089,
2148,
12,
11890,
5034,
8526,
3778,
389,
5399,
2148,
16,
1758,
8526,
3778,
389,
869,
13,
203,
3639,
1071,
2
] |
pragma solidity ^0.4.24;
pragma experimental "v0.5.0";
import {PackageDB} from "./PackageDB.sol";
import {ReleaseDB} from "./ReleaseDB.sol";
import {ReleaseValidator} from "./ReleaseValidator.sol";
import {PackageRegistryInterface} from "./PackageRegistryInterface.sol";
import {Authorized} from "./Authority.sol";
/// @title Database contract for a package index.
/// @author Tim Coulter <[email protected]>, Piper Merriam <[email protected]>
contract PackageRegistry is Authorized, PackageRegistryInterface {
PackageDB private packageDb;
ReleaseDB private releaseDb;
ReleaseValidator private releaseValidator;
// Events
event VersionRelease(string packageName, string version, string manifestURI);
event PackageTransfer(address indexed oldOwner, address indexed newOwner);
//
// Administrative API
//
/// @dev Sets the address of the PackageDb contract.
/// @param newPackageDb The address to set for the PackageDb.
function setPackageDb(address newPackageDb)
public
auth
returns (bool)
{
packageDb = PackageDB(newPackageDb);
return true;
}
/// @dev Sets the address of the ReleaseDb contract.
/// @param newReleaseDb The address to set for the ReleaseDb.
function setReleaseDb(address newReleaseDb)
public
auth
returns (bool)
{
releaseDb = ReleaseDB(newReleaseDb);
return true;
}
/// @dev Sets the address of the ReleaseValidator contract.
/// @param newReleaseValidator The address to set for the ReleaseValidator.
function setReleaseValidator(address newReleaseValidator)
public
auth
returns (bool)
{
releaseValidator = ReleaseValidator(newReleaseValidator);
return true;
}
//
// +-------------+
// | Write API |
// +-------------+
//
/// @dev Creates a a new release for the named package. If this is the first release for the given package then this will also assign msg.sender as the owner of the package. Returns success.
/// @notice Will create a new release the given package with the given release information.
/// @param packageName Package name
/// @param version Version string (ex: '1.0.0')
/// @param manifestURI The URI for the release manifest for this release.
function release(
string packageName,
string version,
string manifestURI
)
public
auth
returns (bytes32 releaseId)
{
require(address(packageDb) != 0x0, "escape:PackageIndex:package-db-not-set");
require(address(releaseDb) != 0x0, "escape:PackageIndex:release-db-not-set");
require(address(releaseValidator) != 0x0, "escape:PackageIndex:release-validator-not-set");
bytes32 versionHash = releaseDb.hashVersion(version);
// If the version for this release is not in the version database, populate
// it. This must happen prior to validation to ensure that the version is
// present in the releaseDb.
if (!releaseDb.versionExists(versionHash)) {
releaseDb.setVersion(version);
}
// Run release validator. This method reverts with an error message string
// on failure.
releaseValidator.validateRelease(
packageDb,
releaseDb,
msg.sender,
packageName,
version,
manifestURI
);
// Compute hashes
bool _packageExists = packageExists(packageName);
// Both creates the package if it is new as well as updating the updatedAt
// timestamp on the package.
packageDb.setPackage(packageName);
bytes32 nameHash = packageDb.hashName(packageName);
// If the package does not yet exist create it and set the owner
if (!_packageExists) {
packageDb.setPackageOwner(nameHash, msg.sender);
}
// Create the release and add it to the list of package release hashes.
releaseDb.setRelease(nameHash, versionHash, manifestURI);
// Log the release.
releaseId = releaseDb.hashRelease(nameHash, versionHash);
emit VersionRelease(packageName, version, manifestURI);
return releaseId;
}
/// @dev Transfers package ownership to the provider new owner address.
/// @notice Will transfer ownership of this package to the provided new owner address.
/// @param name Package name
/// @param newPackageOwner The address of the new owner.
function transferPackageOwner(string name, address newPackageOwner)
public
auth
returns (bool)
{
if (isPackageOwner(name, msg.sender)) {
// Only the package owner may transfer package ownership.
return false;
}
// Lookup the current owner
address packageOwner;
(packageOwner,,,) = getPackageData(name);
// Log the transfer
emit PackageTransfer(packageOwner, newPackageOwner);
// Update the owner.
packageDb.setPackageOwner(packageDb.hashName(name), newPackageOwner);
return true;
}
//
// +------------+
// | Read API |
// +------------+
//
/// @dev Returns the address of the packageDb
function getPackageDb()
public
view
returns (address)
{
return address(packageDb);
}
/// @dev Returns the address of the releaseDb
function getReleaseDb()
public
view
returns (address)
{
return address(releaseDb);
}
/// @dev Returns the address of the releaseValidator
function getReleaseValidator()
public
view
returns (address)
{
return address(releaseValidator);
}
/// @dev Query the existence of a package with the given name. Returns boolean indicating whether the package exists.
/// @param name Package name
function packageExists(string name)
public
view
returns (bool)
{
return packageDb.packageExists(packageDb.hashName(name));
}
/// @dev Query the existence of a release at the provided version for the named package. Returns boolean indicating whether such a release exists.
/// @param name Package name
/// @param version Version string (ex: '1.0.0')
function releaseExists(
string name,
string version
)
public
view
returns (bool)
{
bytes32 nameHash = packageDb.hashName(name);
bytes32 versionHash = releaseDb.hashVersion(version);
return releaseDb.releaseExists(releaseDb.hashRelease(nameHash, versionHash));
}
/// @dev Returns a slice of the array of all package hashes for the named package.
/// @param offset The starting index for the slice.
/// @param limit The length of the slice
function getAllPackageIds(uint offset, uint limit)
public
view
returns(
bytes32[] packageIds,
uint pointer
)
{
return packageDb.getAllPackageIds(offset, limit);
}
/// @dev Retrieves the name for the given name hash.
/// @param packageId The name hash of package to lookup the name for.
function getPackageName(bytes32 packageId)
public
view
returns (string packageName)
{
return packageDb.getPackageName(packageId);
}
/// @dev Returns the package data.
/// @param name Package name
function getPackageData(string name)
public
view
returns (
address packageOwner,
uint createdAt,
uint numReleases,
uint updatedAt
)
{
bytes32 nameHash = packageDb.hashName(name);
(packageOwner, createdAt, updatedAt) = packageDb.getPackageData(nameHash);
numReleases = releaseDb.getNumReleasesForNameHash(nameHash);
return (packageOwner, createdAt, numReleases, updatedAt);
}
/// @dev Returns the release data for the release associated with the given release hash.
/// @param releaseId The release hash.
function getReleaseData(bytes32 releaseId)
public
view
returns (
string packageName,
string version,
string manifestURI
)
{
bytes32 versionHash;
bytes32 nameHash;
(nameHash,versionHash, ,) = releaseDb.getReleaseData(releaseId);
packageName = packageDb.getPackageName(nameHash);
version = releaseDb.getVersion(versionHash);
manifestURI = releaseDb.getManifestURI(releaseId);
return (packageName, version, manifestURI);
}
/// @dev Returns a slice of the array of all package hashes for the named package.
/// @param offset The starting index for the slice.
/// @param limit The length of the slice
function getAllReleaseIds(string packageName, uint offset, uint limit)
public
view
returns (
bytes32[] releaseIds,
uint pointer
)
{
bytes32 nameHash = packageDb.hashName(packageName);
return releaseDb.getAllReleaseIds(nameHash, offset, limit);
}
/// @dev Returns release id that *would* be generated for a name and version pair on `release`.
/// @param packageName Package name
/// @param version Version string (ex: '1.0.0')
function generateReleaseId(string packageName, string version)
public
view
returns (bytes32 releaseId)
{
bytes32 nameHash = packageDb.hashName(packageName);
bytes32 versionHash = releaseDb.hashVersion(version);
return keccak256(abi.encodePacked(nameHash, versionHash));
}
/// @dev Returns the release id for a given name and version pair if present on registry.
/// @param packageName Package name
/// @param version Version string(ex: '1.0.0')
function getReleaseId(string packageName, string version)
public
view
returns (bytes32 releaseId)
{
releaseId = generateReleaseId(packageName, version);
bool _releaseExists = releaseDb.releaseExists(releaseId);
if (!_releaseExists) {
return 0;
}
return releaseId;
}
/// @dev Returns the number of packages stored on the registry
function numPackageIds()
public
view
returns (uint totalCount)
{
return packageDb.getNumPackages();
}
/// @dev Returns the number of releases for a given package name on the registry
/// @param packageName Package name
function numReleaseIds(string packageName)
public
view
returns (uint totalCount)
{
bool _packageExists = packageExists(packageName);
if (!_packageExists) {
return 0;
}
bytes32 nameHash = packageDb.hashName(packageName);
return releaseDb.getNumReleasesForNameHash(nameHash);
}
//
// +----------------+
// | Internal API |
// +----------------+
//
/// @dev Returns boolean whether the provided address is the package owner
/// @param name The name of the package
/// @param _address The address to check
function isPackageOwner(string name, address _address)
internal
view
returns (bool)
{
address packageOwner;
(packageOwner,,,) = getPackageData(name);
return (packageOwner != _address);
}
}
| @dev Returns the release data for the release associated with the given release hash. @param releaseId The release hash. | function getReleaseData(bytes32 releaseId)
public
view
returns (
string packageName,
string version,
string manifestURI
)
{
bytes32 versionHash;
bytes32 nameHash;
(nameHash,versionHash, ,) = releaseDb.getReleaseData(releaseId);
packageName = packageDb.getPackageName(nameHash);
version = releaseDb.getVersion(versionHash);
manifestURI = releaseDb.getManifestURI(releaseId);
return (packageName, version, manifestURI);
}
| 1,840,470 | [
1,
4625,
348,
7953,
560,
30,
225,
632,
5206,
2860,
326,
3992,
501,
364,
326,
3992,
3627,
598,
326,
864,
3992,
1651,
18,
632,
891,
3992,
548,
1021,
3992,
1651,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0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0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
336,
7391,
751,
12,
3890,
1578,
3992,
548,
13,
203,
565,
1071,
203,
565,
1476,
203,
565,
1135,
261,
203,
1377,
533,
9929,
16,
203,
1377,
533,
1177,
16,
203,
1377,
533,
5643,
3098,
203,
565,
262,
203,
225,
288,
203,
565,
1731,
1578,
1177,
2310,
31,
203,
565,
1731,
1578,
508,
2310,
31,
203,
565,
261,
529,
2310,
16,
1589,
2310,
16,
269,
13,
273,
3992,
4331,
18,
588,
7391,
751,
12,
9340,
548,
1769,
203,
203,
565,
9929,
273,
2181,
4331,
18,
588,
18308,
12,
529,
2310,
1769,
203,
565,
1177,
273,
3992,
4331,
18,
588,
1444,
12,
1589,
2310,
1769,
203,
565,
5643,
3098,
273,
3992,
4331,
18,
588,
9121,
3098,
12,
9340,
548,
1769,
203,
203,
565,
327,
261,
5610,
461,
16,
1177,
16,
5643,
3098,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x55FD47f0B5Ef775FaBfDA6D47B00eF3B3E221901/sources/contracts/DeliveryOrder.sol | OLEH CARGO OWNERCreation of a campaign verifikasi dan validasi data | function createRequestDO (
string memory _DONumber,
string memory _shippingAgency,
address _SL,
string memory _notifyParty,
string memory _consignee,
string memory _shipper,
string memory _portOfLoading,
string memory _portOfDischarge,
string memory _portOfDelivery,
string memory _expiredDate,
Container[] memory _containers
) public returns (uint256) {
require(
bytes(_DONumber).length !=0 &&
bytes(_shippingAgency).length !=0 &&
bytes(_notifyParty).length !=0 &&
bytes(_consignee).length !=0 &&
bytes(_shipper).length !=0 &&
bytes(_portOfLoading).length !=0 &&
bytes(_portOfDischarge).length !=0 &&
bytes(_portOfDelivery).length !=0,
'Incomplete data, all field must be filled in!');
require(_containers.length > 0, 'Container must be more than zero!');
RequestDO storage aRequestDO = requests[totalRequestDO];
for (uint i=0; i < _containers.length; i++) {
Container memory aContainer = Container(_containers[i].containerNumber,_containers[i].sealNumber,_containers[i].sizeType,_containers[i].grossWeight,_containers[i].depoName,_containers[i].phoneNumber);
aRequestDO.containers.push(aContainer);
}
aRequestDO.id = totalRequestDO;
aRequestDO.cargoOwner = msg.sender;
aRequestDO.DONumber = _DONumber;
aRequestDO.shippingAgency = _shippingAgency;
aRequestDO.SL = _SL;
aRequestDO.notifyParty = _notifyParty;
aRequestDO.consignee = _consignee;
aRequestDO.shipper = _shipper;
aRequestDO.portOfLoading = _portOfLoading;
aRequestDO.portOfDischarge = _portOfDischarge;
aRequestDO.portOfDelivery = _portOfDelivery;
aRequestDO.status = "ON PROCESS";
aRequestDO.expiredDate = _expiredDate;
totalRequestDO++;
return totalRequestDO - 1;
}
| 7,062,036 | [
1,
4625,
348,
7953,
560,
30,
225,
531,
900,
44,
385,
10973,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3639,
533,
3778,
389,
40,
673,
1226,
16,
7010,
3639,
533,
3778,
389,
15076,
2577,
2075,
16,
7010,
3639,
1758,
389,
4559,
16,
7010,
3639,
533,
3778,
389,
12336,
17619,
16,
7010,
3639,
533,
3778,
389,
591,
2977,
1340,
16,
7010,
3639,
533,
3778,
389,
3261,
457,
16,
7010,
3639,
533,
3778,
389,
655,
951,
10515,
16,
7010,
3639,
533,
3778,
389,
655,
951,
1669,
16385,
16,
7010,
3639,
533,
3778,
389,
655,
951,
8909,
16,
203,
3639,
533,
3778,
389,
15820,
1626,
16,
203,
3639,
4039,
8526,
3778,
389,
20596,
203,
565,
262,
1071,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
203,
5411,
1731,
24899,
40,
673,
1226,
2934,
2469,
480,
20,
597,
7010,
5411,
1731,
24899,
15076,
2577,
2075,
2934,
2469,
480,
20,
597,
7010,
5411,
1731,
24899,
12336,
17619,
2934,
2469,
480,
20,
597,
7010,
5411,
1731,
24899,
591,
2977,
1340,
2934,
2469,
480,
20,
597,
7010,
5411,
1731,
24899,
3261,
457,
2934,
2469,
480,
20,
597,
7010,
5411,
1731,
24899,
655,
951,
10515,
2934,
2469,
480,
20,
597,
7010,
5411,
1731,
24899,
655,
951,
1669,
16385,
2934,
2469,
480,
20,
597,
7010,
5411,
1731,
24899,
655,
951,
8909,
2934,
2469,
480,
20,
16,
7010,
5411,
296,
27531,
501,
16,
777,
652,
1297,
506,
6300,
316,
5124,
1769,
203,
3639,
2583,
24899,
20596,
18,
2469,
405,
374,
16,
296,
2170,
1297,
506,
1898,
2353,
3634,
5124,
1769,
203,
540,
203,
3639,
1567,
3191,
2502,
279,
691,
3191,
273,
3285,
63,
4963,
691,
3191,
15533,
203,
3639,
364,
261,
11890,
277,
33,
20,
31,
277,
411,
389,
20596,
18,
2469,
31,
277,
27245,
288,
203,
5411,
4039,
3778,
279,
2170,
273,
4039,
24899,
20596,
63,
77,
8009,
3782,
1854,
16,
67,
20596,
63,
77,
8009,
307,
287,
1854,
16,
67,
20596,
63,
77,
8009,
1467,
559,
16,
67,
20596,
63,
77,
8009,
75,
3984,
6544,
16,
67,
20596,
63,
77,
8009,
323,
1631,
461,
16,
67,
20596,
63,
77,
8009,
10540,
1854,
1769,
203,
5411,
279,
691,
3191,
18,
20596,
18,
6206,
12,
69,
2170,
1769,
203,
3639,
289,
203,
3639,
279,
691,
3191,
18,
350,
273,
2078,
691,
3191,
31,
203,
3639,
279,
691,
3191,
18,
71,
26999,
5541,
273,
1234,
18,
15330,
31,
203,
3639,
279,
691,
3191,
18,
40,
673,
1226,
273,
389,
40,
673,
1226,
31,
203,
3639,
279,
691,
3191,
18,
15076,
2577,
2075,
273,
389,
15076,
2577,
2075,
31,
203,
3639,
279,
691,
3191,
18,
4559,
273,
389,
4559,
31,
203,
3639,
279,
691,
3191,
18,
12336,
17619,
273,
389,
12336,
17619,
31,
203,
3639,
279,
691,
3191,
18,
591,
2977,
1340,
273,
389,
591,
2977,
1340,
31,
203,
3639,
279,
691,
3191,
18,
3261,
457,
273,
389,
3261,
457,
31,
203,
3639,
279,
691,
3191,
18,
655,
951,
10515,
273,
389,
655,
951,
10515,
31,
203,
3639,
279,
691,
3191,
18,
655,
951,
1669,
16385,
273,
389,
655,
951,
1669,
16385,
31,
203,
3639,
279,
691,
3191,
18,
655,
951,
8909,
273,
389,
655,
951,
8909,
31,
203,
3639,
279,
691,
3191,
18,
2327,
273,
315,
673,
20647,
14432,
203,
3639,
279,
691,
3191,
18,
15820,
1626,
273,
389,
15820,
1626,
31,
203,
3639,
2078,
691,
3191,
9904,
31,
203,
3639,
327,
2078,
691,
3191,
300,
404,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.